From 97416c1cd2b03720b06007ee9dcbd6873d798d6c Mon Sep 17 00:00:00 2001 From: htt1997 Date: Wed, 23 Aug 2023 16:03:52 +0800 Subject: [PATCH] update code Signed-off-by: htt1997 --- .gitignore | 1 + CMakeLists.txt | 2 +- data_object/CMakeLists.txt | 2 +- .../adaptor/js_distributedobjectstore.h | 1 - .../src/adaptor/js_distributedobjectstore.cpp | 7 +- data_share/CMakeLists.txt | 9 +- data_share/datashare.gni | 14 + .../dataShare/src/napi_datashare_helper.cpp | 4 +- .../general_controller_provider_impl.h | 56 + .../src/general_controller_provider_impl.cpp | 2 +- .../consumer/src/datashare_helper_impl.cpp | 2 +- .../native/proxy/src/ams_mgr_proxy.cpp | 1 + data_share/interfaces/inner_api/BUILD.gn | 84 +- .../interfaces/inner_api/common/BUILD.gn | 104 +- .../consumer/libdatashare_consumer.map | 2 - data_share/test/native/BUILD.gn | 97 ++ .../proxydatas_with_permission_test.cpp | 65 + .../src/abnormal_branch_test.cpp | 267 +++++ .../src/controller_test.cpp | 274 +++++ .../src/mediadatashare_unit_test.cpp | 7 +- datamgr_service/CMakeLists.txt | 2 +- .../distributeddataservice/CMakeLists.txt | 2 +- .../app/src/feature_stub_impl.cpp | 8 +- .../app/src/feature_stub_impl.h | 4 +- .../app/src/kvstore_data_service.cpp | 12 +- .../app/src/kvstore_data_service.h | 4 +- .../app/src/uninstaller/uninstaller_impl.cpp | 4 +- .../framework/feature/feature_system.cpp | 6 +- .../framework/include/error/general_error.h | 2 +- .../include/feature/feature_system.h | 4 +- .../include/serializable/serializable.h | 8 +- .../framework/include/store/general_store.h | 6 +- .../framework/serializable/serializable.cpp | 6 - .../service/CMakeLists.txt | 15 +- .../service/cloud/GetSchema.puml | 35 + .../service/cloud/cloud_service_impl.cpp | 33 +- .../service/cloud/cloud_service_impl.h | 4 +- .../service/cloud/sync_manager.cpp | 4 +- .../data_share/data_share_service_impl.cpp | 2 +- .../data_share/data_share_service_impl.h | 2 +- .../strategies/publish_strategy.cpp | 2 +- .../service/object/object_service_impl.cpp | 7 +- .../service/object/object_service_impl.h | 2 +- .../service/rdb/rdb_cloud_data_translate.cpp | 2 +- .../service/rdb/rdb_cloud_data_translate.h | 2 +- .../service/rdb/rdb_result_set_impl.cpp | 2 +- .../service/rdb/rdb_service_impl.cpp | 50 +- .../service/rdb/rdb_service_impl.h | 8 + .../service/rdb/rdb_service_stub.cpp | 15 + .../service/rdb/rdb_service_stub.h | 5 +- .../service/rdb/rdb_watcher.cpp | 5 + .../service/test/config_factory_test.cpp | 2 +- .../datashareservicestub_fuzzer.cpp | 2 +- .../service/udmf/data_manager.cpp | 29 +- .../service/udmf/data_manager.h | 5 +- .../service/udmf/lifecycle/lifecycle_policy.h | 2 +- kv_store/BUILD.gn | 1 + kv_store/CMakeLists.txt | 2 +- kv_store/bundle.json | 1 + kv_store/frameworks/CMakeLists.txt | 10 +- kv_store/frameworks/common/itypes_util.h | 15 +- kv_store/frameworks/common/test/BUILD.gn | 104 ++ .../common/test/executor_pool_test.cpp | 9 +- .../frameworks/common/test/traits_test.cpp | 6 - .../test/unittest/types_util_test.cpp | 66 + .../distributeddata/src/js_util.cpp | 2 +- .../distributedkvstore/src/js_util.cpp | 9 +- .../distributeddb/common/include/db_common.h | 2 +- .../common/include/db_constant.h | 1 + .../distributeddb/common/include/db_types.h | 2 - .../distributeddb/common/src/db_constant.cpp | 2 + .../common/src/task_pool_impl.cpp | 22 +- .../distributeddb/common/src/task_pool_impl.h | 2 +- .../include/communicator_aggregator.h | 2 +- .../src/communicator_aggregator.cpp | 2 +- .../communicator/src/communicator_linker.cpp | 15 +- .../libs/distributeddb/distributeddb.gni | 2 + .../include/cloud/icloud_data_translate.h | 2 +- .../interfaces/include/store_observer.h | 2 +- .../relational_store_delegate_impl.cpp | 7 +- .../relational/relational_store_manager.cpp | 8 +- .../relational_store_sqlite_ext.cpp | 107 +- .../relational/relational_sync_able_storage.h | 8 +- .../storage/include/cloud/cloud_meta_data.h | 18 +- .../include/icloud_sync_storage_interface.h | 6 +- .../storage/include/storage_proxy.h | 18 +- .../storage/src/cloud/cloud_meta_data.cpp | 25 +- .../storage/src/cloud/cloud_storage_utils.cpp | 27 +- .../storage/src/cloud/schema_mgr.cpp | 4 +- .../src/operation/local_database_oper.cpp | 2 +- .../src/relational_sync_able_storage.cpp | 62 +- .../sqlite/cloud_sync_log_table_manager.cpp | 3 + .../sqlite_relational_database_upgrader.cpp | 7 +- .../relational/sqlite_relational_store.cpp | 12 +- .../sqlite_relational_store_connection.cpp | 6 +- ...qlite_single_relational_storage_engine.cpp | 27 +- .../sqlite_single_ver_natural_store.cpp | 1 + .../sqlite/sqlite_single_ver_natural_store.h | 2 +- ...single_ver_relational_storage_executor.cpp | 101 +- ...e_single_ver_relational_storage_executor.h | 8 +- ...ver_relational_storage_extend_executor.cpp | 85 +- .../storage/src/sqlite/sqlite_utils.cpp | 2 + .../storage/src/storage_engine.cpp | 4 +- .../storage/src/storage_proxy.cpp | 45 +- .../syncer/src/cloud/cloud_db_proxy.cpp | 3 +- .../syncer/src/cloud/cloud_db_proxy.h | 2 +- .../src/cloud/cloud_force_pull_strategy.cpp | 20 +- .../src/cloud/cloud_sync_tag_assets.cpp | 213 ++++ .../syncer/src/cloud/cloud_sync_tag_assets.h | 33 +- .../syncer/src/cloud/cloud_sync_utils.cpp | 121 +- .../syncer/src/cloud/cloud_sync_utils.h | 18 +- .../syncer/src/cloud/cloud_syncer.cpp | 826 +++++-------- .../syncer/src/cloud/cloud_syncer.h | 129 +- .../syncer/src/cloud/icloud_syncer.h | 48 + .../syncer/src/cloud/process_notifier.cpp | 116 ++ .../syncer/src/cloud/process_notifier.h | 38 +- .../syncer/src/generic_syncer.cpp | 5 +- .../syncer/src/sync_task_context.cpp | 9 +- .../libs/distributeddb/test/BUILD.gn | 16 + .../cloudsync_fuzzer/cloudsync_fuzzer.cpp | 190 ++- .../test/fuzztest/storage_fuzzer/BUILD.gn | 113 ++ .../test/fuzztest/storage_fuzzer/corpus/init | 20 +- .../test/fuzztest/storage_fuzzer/project.xml | 25 + .../storage_fuzzer/storage_fuzzer.cpp | 223 ++++ .../fuzztest/storage_fuzzer/storage_fuzzer.h | 21 + ...ces_relational_remove_device_data_test.cpp | 706 +++++++++++ ...stributeddb_interfaces_relational_test.cpp | 5 +- .../distributeddb_cloud_check_sync_test.cpp | 201 ++++ ..._cloud_interfaces_relational_sync_test.cpp | 369 +----- .../distributeddb_cloud_meta_data_test.cpp | 12 +- ...stributeddb_cloud_save_cloud_data_test.cpp | 67 ++ ...relational_cloud_syncable_storage_test.cpp | 10 +- ...distributeddb_relational_get_data_test.cpp | 66 +- .../common/syncer/cloud/cloud_syncer_test.h | 5 +- .../distributeddb_cloud_db_proxy_test.cpp | 22 +- .../distributeddb_cloud_strategy_test.cpp | 23 + ...stributeddb_cloud_syncer_download_test.cpp | 27 +- ...distributeddb_cloud_syncer_upload_test.cpp | 25 +- .../mock_icloud_sync_storage_interface.h | 3 +- .../cloud/virtual_cloud_data_translate.cpp | 5 +- .../cloud/virtual_cloud_data_translate.h | 2 +- .../syncer/cloud/virtual_cloud_syncer.cpp | 10 + .../syncer/cloud/virtual_cloud_syncer.h | 3 + kv_store/kv_store.gni | 2 + .../single_kvstore_client/BUILD.gn | 128 +- .../distributed_test.cpp | 314 ++--- .../distributed_test_agent.cpp | 320 +++-- .../distributed_test_helper.cpp | 91 -- mock/CMakeLists.txt | 237 +++- preferences/CMakeLists.txt | 10 +- .../frameworks/common/include/log_print.h | 36 +- .../js/napi/common/include/js_logger.h | 34 - .../js/napi/common/include/js_utils.h | 2 - .../js/napi/common/src/js_utils.cpp | 21 +- .../include/data_preferences_observer_stub.h | 59 - .../src/data_preferences_observer_stub.cpp | 79 -- .../src/data_preferences_observer_stub.cpp | 40 - .../frameworks/native/include/executor_pool.h | 3 +- .../frameworks/native/include/logger.h | 33 - .../native/include/preferences_impl.h | 23 +- .../preferences_observer_stub.h} | 20 +- .../native/include/priority_queue.h | 1 - .../frameworks/native/include/task_pool.h | 89 -- .../native/include/task_scheduler.h | 127 -- .../frameworks/native/include/visibility.h | 3 + .../ability_base/zuri/include/uri.h} | 21 +- .../native/mock/ability_base/zuri/src/uri.cpp | 21 + .../data_ability_observer_interface.h} | 33 +- .../include/data_ability_observer_stub.h | 25 +- .../include/dataobs_mgr_client.h | 33 +- .../src/data_ability_observer_stub.cpp} | 25 +- .../src/dataobs_mgr_client.cpp | 48 + .../mock/c_utils/utils/base/include/refbase.h | 637 ++++++++++ .../mock/c_utils/utils/base/src/refbase.cpp | 438 +++++++ .../include/preferences_file_lock.h} | 6 +- .../include/preferences_file_operation.h} | 84 +- .../include/preferences_thread.h | 0 .../src/preferences_file_lock.cpp} | 34 +- .../src/preferences_thread.cpp | 8 +- .../native/src/preferences_helper.cpp | 12 +- .../native/src/preferences_impl.cpp | 355 +++--- .../native/src/preferences_xml_utils.cpp | 151 ++- .../frameworks/native/src/task_executor.cpp | 43 - .../frameworks/native/src/task_pool.cpp | 317 ----- .../frameworks/native/src/task_queue.cpp | 78 -- preferences/interfaces/inner_api/BUILD.gn | 70 +- .../src/PreferencesInstanceSyncJsPref.test.js | 46 +- .../src/PreferencesHelperSyncJsunit.test.js | 39 +- .../src/PreferencesCallBackJsunit.test.js | 433 ------- .../src/PreferencesHelperJsunit.test.js | 147 --- .../src/PreferencesPromiseJsunit.test.js | 469 -------- .../src/StorageCallBackJsunit.test.js | 494 -------- .../unittest/src/StorageHelperJsunit.test.js | 134 --- .../unittest/src/StoragePromiseJsunit.test.js | 326 ----- .../js/unittest/src/StorageSyncJsunit.test.js | 449 ------- .../unittest/src/SystemStorageJsunit.test.js | 514 -------- .../src/V9_PreferencesCallBackJsunit.test.js | 612 ---------- .../src/V9_PreferencesPromiseJsunit.test.js | 362 ------ preferences/test/js/unittest/src/config.json | 62 - .../test/native/unittest/preferences_test.cpp | 30 +- .../unittest/preferences_xml_utils_test.cpp | 4 +- relational_store/CMakeLists.txt | 72 +- relational_store/bundle.json | 3 +- .../js/napi/common/include/js_utils.h | 15 +- .../js/napi/common/src/js_utils.cpp | 129 +- .../include/napi_data_ability_predicates.h | 4 +- .../src/napi_data_ability_predicates.cpp | 160 ++- .../dataability/src/napi_predicates_utils.cpp | 8 +- .../js/napi/rdb/include/napi_rdb_js_utils.h | 3 + .../js/napi/rdb/include/napi_rdb_predicates.h | 6 +- .../js/napi/rdb/include/napi_result_set.h | 5 +- .../rdb/mock/include/napi_rdb_predicates.h | 6 +- .../napi/rdb/mock/include/napi_result_set.h | 3 +- .../js/napi/rdb/src/napi_rdb_js_utils.cpp | 10 + .../js/napi/rdb/src/napi_rdb_predicates.cpp | 103 +- .../js/napi/rdb/src/napi_rdb_store.cpp | 191 ++- .../js/napi/rdb/src/napi_rdb_store_helper.cpp | 4 +- .../js/napi/rdb/src/napi_result_set.cpp | 186 +-- .../js/napi/rdb/src/napi_values_bucket.cpp | 10 +- .../include/napi_rdb_js_utils.h | 7 + .../include/napi_rdb_predicates.h | 6 +- .../mock/include/napi_rdb_predicates.h | 6 +- .../relationalstore/src/napi_rdb_js_utils.cpp | 18 +- .../src/napi_rdb_predicates.cpp | 100 +- .../relationalstore/src/napi_rdb_store.cpp | 173 ++- .../src/napi_rdb_store_helper.cpp | 2 +- .../relationalstore/src/napi_result_set.cpp | 6 +- .../native/appdatafwk/src/shared_block.cpp | 275 ++--- .../src/data_ability_predicates.cpp | 20 +- .../dataability/src/predicates_utils.cpp | 36 +- .../native/rdb/include/rdb_service_proxy.h | 16 +- .../native/rdb/include/rdb_store_impl.h | 26 +- .../native/rdb/include/rdb_store_manager.h | 1 + .../include/shared_block_serializer_info.h | 29 +- .../native/rdb/include/sqlite_connection.h | 2 - .../rdb/include/sqlite_shared_result_set.h | 4 +- .../native/rdb/include/sqlite_sql_builder.h | 16 +- .../native/rdb/include/step_result_set.h | 5 +- .../native/rdb/include/string_utils.h | 2 + .../native/rdb/mock/include/rdb_store_impl.h | 13 +- .../rdb/mock/include/rdb_store_manager.h | 1 + .../rdb/mock/include/sqlite_connection.h | 2 - .../rdb/mock/include/sqlite_sql_builder.h | 16 +- .../native/rdb/mock/include/step_result_set.h | 5 +- .../native/rdb/mock/include/string_utils.h | 2 + .../native/rdb/src/abs_predicates.cpp | 231 ++-- .../native/rdb/src/abs_rdb_predicates.cpp | 26 +- .../native/rdb/src/abs_shared_result_set.cpp | 13 +- .../frameworks/native/rdb/src/rdb_helper.cpp | 7 +- .../native/rdb/src/rdb_predicates.cpp | 11 - .../native/rdb/src/rdb_service_proxy.cpp | 91 +- .../native/rdb/src/rdb_sql_utils.cpp | 1 + .../native/rdb/src/rdb_store_impl.cpp | 136 ++- .../native/rdb/src/rdb_store_manager.cpp | 21 + .../native/rdb/src/security_policy.cpp | 2 +- .../frameworks/native/rdb/src/share_block.cpp | 15 +- .../rdb/src/shared_block_serializer_info.cpp | 82 +- .../native/rdb/src/sqlite_connection.cpp | 24 - .../rdb/src/sqlite_shared_result_set.cpp | 42 +- .../native/rdb/src/sqlite_sql_builder.cpp | 112 +- .../native/rdb/src/sqlite_statement.cpp | 2 +- .../native/rdb/src/step_result_set.cpp | 14 +- .../native/rdb/src/string_utils.cpp | 18 +- .../native/rdb/src/value_object.cpp | 25 +- .../native/rdb/src/values_bucket.cpp | 5 - .../rdb_data_share_adapter/src/rdb_utils.cpp | 13 +- .../appdatafwk/include/shared_block.h | 38 +- .../cloud_data/include/cloud_service.h | 1 + .../dataability/include/predicates_utils.h | 20 +- .../inner_api/rdb/include/abs_predicates.h | 43 +- .../rdb/include/abs_rdb_predicates.h | 5 +- .../rdb/include/abs_shared_result_set.h | 1 - ...data_relational_store_ipc_interface_code.h | 1 + .../inner_api/rdb/include/rdb_predicates.h | 10 - .../inner_api/rdb/include/rdb_service.h | 3 + .../inner_api/rdb/include/rdb_store.h | 143 ++- .../inner_api/rdb/include/values_bucket.h | 1 - .../rdb/mock/include/abs_rdb_predicates.h | 57 - .../rdb/mock/include/rdb_predicates.h | 2 - .../inner_api/rdb/mock/include/rdb_store.h | 42 +- .../rdb/mock/include/values_bucket.h | 1 - .../ndk/src/relational_predicates.cpp | 79 +- .../ndk/src/relational_predicates.h | 6 +- .../ndk/src/relational_predicates_objects.cpp | 14 +- .../ndk/src/relational_predicates_objects.h | 11 +- .../interfaces/ndk/src/relational_store.cpp | 13 +- .../ndk/src/relational_value_object.cpp | 118 -- .../src/RdbStoreDistributedJsunit.test.js | 5 +- .../src/RdbstoreEncryptionJsunit.test.js | 231 ++-- .../src/RdbstoreRdbstoreJsunit.test.js | 139 +-- .../unittest/src/RdbstoreUpdateJsunit.test.js | 390 +++--- .../unittest/src/RdbStoreCloud.test.js | 176 ++- .../unittest/src/RdbStoreCloudSync.test.js | 289 +++-- .../src/RdbStoreDistributedJsunit.test.js | 111 +- ...reBackupRestoreWithFAContextJsunit.test.js | 31 +- .../src/RdbstoreEncryptionJsunit.test.js | 260 ++-- .../unittest/src/RdbstoreInsertJsunit.test.js | 2 +- .../src/RdbstoreRdbstoreJsunit.test.js | 176 +-- .../unittest/src/RdbstoreUpdateJsunit.test.js | 1063 ++++++++--------- .../unittest/data_ability_predicates_test.cpp | 14 +- relational_store/test/native/rdb/BUILD.gn | 1 + .../rdbstore_fuzzer/rdbstore_fuzzer.cpp | 31 +- .../rdb/unittest/rdb_distributed_test.cpp | 90 +- .../native/rdb/unittest/rdb_insert_test.cpp | 26 + .../rdb/unittest/rdb_open_callback_test.cpp | 1 - .../rdb/unittest/rdb_predicates_test.cpp | 44 +- .../rdb_sqlite_shared_result_set_test.cpp | 47 +- .../unittest/rdb_step_result_get_row_test.cpp | 60 +- .../rdb/unittest/rdb_step_result_set_test.cpp | 15 + .../rdb/unittest/rdb_store_config_test.cpp | 1 - .../rdb/unittest/rdb_transaction_test.cpp | 33 + .../native/rdb/unittest/rdb_update_test.cpp | 23 + .../native/rdb/unittest/rdb_utils_test.cpp | 80 +- .../rdb/unittest/rdb_value_bucket_test.cpp | 80 ++ .../test/ndk/unittest/rdb_cursor_test.cpp | 136 ++- .../test/ndk/unittest/rdb_predicates_test.cpp | 262 +++- .../test/ndk/unittest/rdb_store_test.cpp | 208 +++- test/CMakeLists.txt | 4 +- test/include/CMakeLists.txt | 2 + udmf/BUILD.gn | 3 +- udmf/CMakeLists.txt | 20 +- .../test/unittest/udmf_client_test.cpp | 10 +- ...napi.cpp => unified_data_channel_napi.cpp} | 68 +- .../data/uniform_type_descriptor_napi.cpp | 75 ++ .../jskitsimpl/unittest/UdmfCallbackJsTest.js | 61 +- .../jskitsimpl/unittest/UdmfJsTest.js | 107 +- .../jskitsimpl/unittest/UdmfPromiseJsTest.js | 61 +- .../innerkits/common/unified_meta.h | 42 +- udmf/interfaces/jskits/BUILD.gn | 80 +- ...dmf_napi.h => unified_data_channel_napi.h} | 9 +- .../data/uniform_type_descriptor_napi.h | 32 +- ...p => unified_data_channel_napi_module.cpp} | 33 +- .../uniform_type_descriptor_napi_module.cpp | 41 + 333 files changed, 10969 insertions(+), 11073 deletions(-) create mode 100644 data_share/frameworks/native/consumer/controller/provider/include/general_controller_provider_impl.h create mode 100644 data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp create mode 100644 data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/cloud/GetSchema.puml create mode 100644 kv_store/frameworks/common/test/BUILD.gn create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.cpp rename relational_store/interfaces/ndk/src/relational_predicates_impl.h => kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.h (51%) create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/icloud_syncer.h create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.cpp rename relational_store/interfaces/ndk/src/relational_values_bucket_impl.h => kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.h (45%) create mode 100644 kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/BUILD.gn rename preferences/test/js/unittest/src/BUILD.gn => kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/corpus/init (58%) create mode 100644 kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/project.xml create mode 100644 kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.h create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_check_sync_test.cpp delete mode 100644 kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.cpp delete mode 100644 preferences/frameworks/js/napi/common/include/js_logger.h delete mode 100644 preferences/frameworks/native/common/mock/include/data_preferences_observer_stub.h delete mode 100644 preferences/frameworks/native/common/mock/src/data_preferences_observer_stub.cpp delete mode 100644 preferences/frameworks/native/common/src/data_preferences_observer_stub.cpp delete mode 100644 preferences/frameworks/native/include/logger.h rename preferences/frameworks/native/{common/include/data_preferences_observer_stub.h => include/preferences_observer_stub.h} (70%) delete mode 100644 preferences/frameworks/native/include/task_pool.h delete mode 100644 preferences/frameworks/native/include/task_scheduler.h rename preferences/frameworks/native/{src/preferences_thread.cpp => mock/ability_base/zuri/include/uri.h} (72%) create mode 100644 preferences/frameworks/native/mock/ability_base/zuri/src/uri.cpp rename preferences/frameworks/native/{include/task_queue.h => mock/ability_runtime/dataobs_manager/include/data_ability_observer_interface.h} (51%) rename relational_store/interfaces/ndk/src/relational_value_object_impl.h => preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/data_ability_observer_stub.h (54%) rename relational_store/interfaces/ndk/src/relational_cursor_impl.h => preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/dataobs_mgr_client.h (47%) rename preferences/frameworks/native/{common/mock/src/filelock.cpp => mock/ability_runtime/dataobs_manager/src/data_ability_observer_stub.cpp} (68%) create mode 100644 preferences/frameworks/native/mock/ability_runtime/dataobs_manager/src/dataobs_mgr_client.cpp create mode 100644 preferences/frameworks/native/mock/c_utils/utils/base/include/refbase.h create mode 100644 preferences/frameworks/native/mock/c_utils/utils/base/src/refbase.cpp rename preferences/frameworks/native/{include/filelock.h => platform/include/preferences_file_lock.h} (90%) rename preferences/frameworks/native/{include/adaptor.h => platform/include/preferences_file_operation.h} (38%) rename preferences/frameworks/native/{ => platform}/include/preferences_thread.h (100%) rename preferences/frameworks/native/{src/filelock.cpp => platform/src/preferences_file_lock.cpp} (80%) rename preferences/frameworks/native/{common/mock => platform}/src/preferences_thread.cpp (77%) delete mode 100644 preferences/frameworks/native/src/task_executor.cpp delete mode 100644 preferences/frameworks/native/src/task_pool.cpp delete mode 100644 preferences/frameworks/native/src/task_queue.cpp delete mode 100644 preferences/test/js/unittest/src/PreferencesCallBackJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/PreferencesHelperJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/PreferencesPromiseJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/StorageCallBackJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/StorageHelperJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/StoragePromiseJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/StorageSyncJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/SystemStorageJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/V9_PreferencesCallBackJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/V9_PreferencesPromiseJsunit.test.js delete mode 100644 preferences/test/js/unittest/src/config.json delete mode 100644 relational_store/interfaces/inner_api/rdb/mock/include/abs_rdb_predicates.h delete mode 100644 relational_store/interfaces/ndk/src/relational_value_object.cpp rename kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.h => relational_store/test/native/rdb/unittest/rdb_utils_test.cpp (34%) rename udmf/framework/jskitsimpl/data/{udmf_napi.cpp => unified_data_channel_napi.cpp} (78%) create mode 100644 udmf/framework/jskitsimpl/data/uniform_type_descriptor_napi.cpp rename udmf/interfaces/jskits/data/{udmf_napi.h => unified_data_channel_napi.h} (82%) rename preferences/frameworks/native/include/task_executor.h => udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h (54%) rename udmf/interfaces/jskits/module/{udmf_napi_module.cpp => unified_data_channel_napi_module.cpp} (83%) create mode 100644 udmf/interfaces/jskits/module/uniform_type_descriptor_napi_module.cpp diff --git a/.gitignore b/.gitignore index 17d0b085..551a53e2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /cmake-build-debug/ /.idea/ /*/.gitee/ +*.puml diff --git a/CMakeLists.txt b/CMakeLists.txt index 3ade48b4..3a010461 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(LDBProj) set(CMAKE_CXX_STANDARD 17) diff --git a/data_object/CMakeLists.txt b/data_object/CMakeLists.txt index a79a48e3..a6f21894 100644 --- a/data_object/CMakeLists.txt +++ b/data_object/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(data_object) set(CMAKE_CXX_STANDARD 17) diff --git a/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h b/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h index f468b56a..d231d575 100644 --- a/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h +++ b/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h @@ -46,7 +46,6 @@ private: static bool GetBundleNameWithContext(napi_env env, napi_value argv, std::string &bundleName); static std::string GetBundleName(napi_env env); static bool IsSandBox(); - static std::atomic sequenceNum_; }; } // namespace OHOS::ObjectStore #endif // JS_DISTRIBUTEDDATAOBJECTSTORE_H diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp index 2ff20210..bbcf8b58 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp @@ -16,6 +16,7 @@ #include "js_distributedobjectstore.h" #include +#include #include "ability_context.h" #include "accesstoken_kit.h" @@ -32,11 +33,9 @@ namespace OHOS::ObjectStore { constexpr size_t TYPE_SIZE = 10; -const int MIN_NUMERIC = 999999; const std::string DISTRIBUTED_DATASYNC = "ohos.permission.DISTRIBUTED_DATASYNC"; static ConcurrentMap> g_statusCallBacks; static ConcurrentMap> g_changeCallBacks; -std::atomic JSDistributedObjectStore::sequenceNum_{ MIN_NUMERIC }; bool JSDistributedObjectStore::AddCallback(napi_env env, ConcurrentMap> &callbacks, const std::string &objectId, napi_value callback) { @@ -507,7 +506,9 @@ napi_value JSDistributedObjectStore::JSDeleteCallback(napi_env env, napi_callbac napi_value JSDistributedObjectStore::JSEquenceNum(napi_env env, napi_callback_info info) { - std::string str = std::to_string(sequenceNum_++); + std::random_device randomDevice; + std::uniform_int_distribution distribution(0, std::numeric_limits::max()); + std::string str = std::to_string(distribution(randomDevice)); napi_value result = nullptr; napi_status status = napi_create_string_utf8(env, str.c_str(), str.size(), &result); CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); diff --git a/data_share/CMakeLists.txt b/data_share/CMakeLists.txt index 28c378aa..9f7967ce 100644 --- a/data_share/CMakeLists.txt +++ b/data_share/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(data_share) set(CMAKE_CXX_STANDARD 17) @@ -7,6 +7,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -fPIC -fpic -ffunction-s set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wformat=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=deprecated-declarations -Wno-deprecated-declarations") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") set(MOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../mock) add_definitions(-DNAPI_EXPERIMENTAL) @@ -34,12 +35,6 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/common/incl 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}/../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) diff --git a/data_share/datashare.gni b/data_share/datashare.gni index ee65df1a..e4c79ef5 100644 --- a/data_share/datashare.gni +++ b/data_share/datashare.gni @@ -38,3 +38,17 @@ datashare_native_consumer_path = "${datashare_base_path}/frameworks/native/consumer" datashare_native_proxy_path = "${datashare_base_path}/frameworks/native/proxy" + +foundation_path = "//foundation" + +kvstore_base_path = "//foundation/distributeddatamgr/kv_store" + +access_token_path = "//base/security/access_token" + +base_hiviewdfx_hilog_path = "//base/hiviewdfx/hilog" + +commonlibrary_cutils_path = "//commonlibrary/c_utils" + +utils_system_safwk_path = "//utils/system/safwk" + +thirdparty_json_path = "//third_party/json" 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 ae772fcc..e0f89346 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 @@ -722,14 +722,14 @@ napi_value NapiDataShareHelper::Napi_Publish(napi_env env, napi_callback_info in NAPI_CALL_BASE(env, napi_typeof(env, argv[1], &valueType), napi_invalid_arg); NAPI_ASSERT_CALL_ERRCODE(env, valueType == napi_string, context->error = std::make_shared("bundleName", "string"), napi_invalid_arg); + context->publishData = DataShareJSUtils::Convert2PublishedData(env, argv[0]); + context->bundleName = DataShareJSUtils::Convert2String(env, argv[1]); if (argc > 2) { NAPI_CALL_BASE(env, napi_typeof(env, argv[PARAM2], &valueType), napi_invalid_arg); if (valueType == napi_number) { napi_get_value_int32(env, argv[PARAM2], &(context->publishData.version_)); } } - context->publishData = DataShareJSUtils::Convert2PublishedData(env, argv[0]); - context->bundleName = DataShareJSUtils::Convert2String(env, argv[1]); return napi_ok; }; auto output = [context](napi_env env, napi_value *result) -> napi_status { diff --git a/data_share/frameworks/native/consumer/controller/provider/include/general_controller_provider_impl.h b/data_share/frameworks/native/consumer/controller/provider/include/general_controller_provider_impl.h new file mode 100644 index 00000000..1f75d74c --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/provider/include/general_controller_provider_impl.h @@ -0,0 +1,56 @@ +/* + * 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; + + void NotifyChange(const Uri &uri) 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/general_controller_provider_impl.cpp b/data_share/frameworks/native/consumer/controller/provider/src/general_controller_provider_impl.cpp index ccc8fc47..d3f15ca2 100644 --- 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 @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "general_controller_porvider_impl.h" +#include "general_controller_provider_impl.h" #include "datashare_log.h" diff --git a/data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp b/data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp index 71c7dc73..92818bed 100644 --- a/data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp @@ -21,7 +21,7 @@ #include "datashare_log.h" #include "datashare_result_set.h" -#include "general_controller_porvider_impl.h" +#include "general_controller_provider_impl.h" #include "general_controller_service_impl.h" namespace OHOS { diff --git a/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp b/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp index 3d6cb04b..1c0bcce8 100644 --- a/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp +++ b/data_share/frameworks/native/proxy/src/ams_mgr_proxy.cpp @@ -53,6 +53,7 @@ int AmsMgrProxy::Connect( want.SetUri(uri); std::lock_guard lock(mutex_); if (ConnectSA()) { + LOG_INFO("connect datashareextability start"); int ret = proxy_->ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::DATASHARE); if (ret != ERR_OK) { LOG_ERROR("connect ability failed, ret = %{public}d", ret); diff --git a/data_share/interfaces/inner_api/BUILD.gn b/data_share/interfaces/inner_api/BUILD.gn index 60772513..44567d4f 100644 --- a/data_share/interfaces/inner_api/BUILD.gn +++ b/data_share/interfaces/inner_api/BUILD.gn @@ -52,49 +52,53 @@ config("datashare_public_config") { ] } +datashare_consumer_sources = [ + "${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/ams_mgr_proxy.cpp", + "${datashare_native_proxy_path}/src/data_proxy_observer_stub.cpp", + "${datashare_native_proxy_path}/src/data_share_manager_impl.cpp", + "${datashare_native_proxy_path}/src/data_share_service_proxy.cpp", + "${datashare_native_proxy_path}/src/idata_share_client_death_observer.cpp", + "${datashare_native_proxy_path}/src/published_data_subscriber_manager.cpp", + "${datashare_native_proxy_path}/src/rdb_subscriber_manager.cpp", +] + +datashare_consumer_external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_context_native", + "ability_runtime:app_context", + "ability_runtime:dataobs_manager", + "ability_runtime:extension_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "ipc:ipc_single", + "ipc_js:rpc", + "napi:ace_napi", + "samgr:samgr_proxy", +] + ohos_shared_library("datashare_consumer") { include_dirs = [ "//foundation/distributeddatamgr/kv_store/frameworks/common" ] - sources = [ - "${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/ams_mgr_proxy.cpp", - "${datashare_native_proxy_path}/src/data_proxy_observer_stub.cpp", - "${datashare_native_proxy_path}/src/data_share_manager_impl.cpp", - "${datashare_native_proxy_path}/src/data_share_service_proxy.cpp", - "${datashare_native_proxy_path}/src/idata_share_client_death_observer.cpp", - "${datashare_native_proxy_path}/src/published_data_subscriber_manager.cpp", - "${datashare_native_proxy_path}/src/rdb_subscriber_manager.cpp", - ] + sources = datashare_consumer_sources configs = [ ":ability_config" ] public_configs = [ ":datashare_public_config" ] version_script = "consumer/libdatashare_consumer.map" innerapi_tags = [ "platformsdk" ] deps = [ "${datashare_innerapi_path}/common:datashare_common" ] - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "ability_runtime:ability_context_native", - "ability_runtime:app_context", - "ability_runtime:dataobs_manager", - "ability_runtime:extension_manager", - "c_utils:utils", - "common_event_service:cesfwk_innerkits", - "hilog:libhilog", - "ipc:ipc_single", - "ipc_js:rpc", - "napi:ace_napi", - "samgr:samgr_proxy", - ] + external_deps = datashare_consumer_external_deps subsystem_name = "distributeddatamgr" part_name = "data_share" @@ -165,3 +169,17 @@ ohos_shared_library("datashare_ext_ability_module") { subsystem_name = "distributeddatamgr" part_name = "data_share" } + +ohos_static_library("datashare_consumer_static") { + include_dirs = [ "${kvstore_base_path}/frameworks/common" ] + + sources = datashare_consumer_sources + configs = [ ":ability_config" ] + public_configs = [ ":datashare_public_config" ] + deps = [ "${datashare_innerapi_path}/common:datashare_common_static" ] + + external_deps = datashare_consumer_external_deps + + subsystem_name = "distributeddatamgr" + part_name = "data_share" +} diff --git a/data_share/interfaces/inner_api/common/BUILD.gn b/data_share/interfaces/inner_api/common/BUILD.gn index 878748b1..c74fc92a 100644 --- a/data_share/interfaces/inner_api/common/BUILD.gn +++ b/data_share/interfaces/inner_api/common/BUILD.gn @@ -30,35 +30,52 @@ config("datashare_public_config") { [ "${datashare_base_path}/interfaces/inner_api/common/include" ] } +datashare_common_include_dirs = [ + "${datashare_common_napi_path}/include", + "${datashare_common_native_path}/include", + "${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_path}/communication/ipc/ipc/native/src/napi_common/include", + "${kvstore_base_path}/frameworks/common", +] + +datashare_common_sources = [ + "${datashare_common_napi_path}/src/datashare_error_impl.cpp", + "${datashare_common_napi_path}/src/datashare_js_utils.cpp", + "${datashare_common_napi_path}/src/datashare_predicates_proxy.cpp", + "${datashare_common_napi_path}/src/datashare_result_set_proxy.cpp", + "${datashare_common_napi_path}/src/napi_datashare_values_bucket.cpp", + "${datashare_common_native_path}/src/datashare_abs_result_set.cpp", + "${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", +] + +datashare_common_external_deps = [ + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_napi_common", + "ipc:ipc_single", + "napi:ace_napi", +] + ohos_shared_library("datashare_common") { - include_dirs = [ - "${datashare_common_napi_path}/include", - "${datashare_common_native_path}/include", - "${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", - ] - - sources = [ - "${datashare_common_napi_path}/src/datashare_error_impl.cpp", - "${datashare_common_napi_path}/src/datashare_js_utils.cpp", - "${datashare_common_napi_path}/src/datashare_predicates_proxy.cpp", - "${datashare_common_napi_path}/src/datashare_result_set_proxy.cpp", - "${datashare_common_napi_path}/src/napi_datashare_values_bucket.cpp", - "${datashare_common_native_path}/src/datashare_abs_result_set.cpp", - "${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", - ] + include_dirs = datashare_common_include_dirs + + sources = datashare_common_sources deps = [] @@ -69,18 +86,25 @@ ohos_shared_library("datashare_common") { version_script = "libdatashare_common.map" innerapi_tags = [ "platformsdk" ] - external_deps = [ - "ability_base:zuri", - "ability_runtime:abilitykit_native", - "c_utils:utils", - "hilog:libhilog", - "hisysevent:libhisysevent", - "hitrace:hitrace_meter", - "hitrace:libhitracechain", - "ipc:ipc_napi_common", - "ipc:ipc_single", - "napi:ace_napi", - ] + external_deps = datashare_common_external_deps + + subsystem_name = "distributeddatamgr" + part_name = "data_share" +} + +ohos_static_library("datashare_common_static") { + include_dirs = datashare_common_include_dirs + + sources = datashare_common_sources + + deps = [] + + public_deps = [] + + configs = [ ":ability_config" ] + public_configs = [ ":datashare_public_config" ] + + external_deps = datashare_common_external_deps subsystem_name = "distributeddatamgr" part_name = "data_share" diff --git a/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map b/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map index ae4289ff..19853035 100644 --- a/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map +++ b/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map @@ -19,8 +19,6 @@ *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 5ff2afac..53b5c8d7 100644 --- a/data_share/test/native/BUILD.gn +++ b/data_share/test/native/BUILD.gn @@ -19,6 +19,8 @@ group("unittest") { deps = [] deps += [ + ":AbnormalBranchTest", + ":ControllerTest", ":ErrorCodeTest", ":JoinTest", ":NativeDataShareTest", @@ -221,3 +223,98 @@ ohos_unittest("ProxyDatasTest") { "samgr:samgr_proxy", ] } + +ohos_unittest("ControllerTest") { + module_out_path = "data_share/native_datashare" + + include_dirs = [ + "${ability_runtime_inner_api_path}/ability_manager/include", + "${ability_runtime_inner_api_path}/app_manager/include/appmgr", + "${ability_runtime_inner_api_path}/dataobs_manager/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${access_token_path}/frameworks/common/include", + "${base_hiviewdfx_hilog_path}/interfaces/native/innerkits/include", + "${foundation_path}/aafwk/standard/interfaces/innerkits/uri/include", + "${commonlibrary_cutils_path}/base/include", + "${utils_system_safwk_path}/native/include", + "${foundation_path}/communication/ipc/interfaces/innerkits/ipc_core/include", + "${thirdparty_json_path}/include", + "${datashare_innerapi_path}/consumer/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_innerapi_path}/common/include", + "${datashare_native_proxy_path}/include", + "${ability_runtime_inner_api_path}/extension_manager/include/", + ] + + sources = [ "./unittest/mediadatashare_test/src/controller_test.cpp" ] + + deps = [ + "${datashare_innerapi_path}:datashare_consumer_static", + "${datashare_innerapi_path}/common:datashare_common_static", + ] + + 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", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_single", + "media_library:media_library", + "relational_store:rdb_data_ability_adapter", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} + +ohos_unittest("AbnormalBranchTest") { + module_out_path = "data_share/native_datashare" + + include_dirs = [ + "${access_token_path}/frameworks/common/include", + "${base_hiviewdfx_hilog_path}/interfaces/native/innerkits/include", + "${foundation_path}/aafwk/standard/interfaces/innerkits/uri/include", + "${commonlibrary_cutils_path}/base/include", + "${utils_system_safwk_path}/native/include", + "${foundation_path}/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributeddatamgr/data_share/frameworks/native/proxy/include/", + "//foundation/distributeddatamgr/data_share/frameworks/native/common/include/", + ] + + sources = [ "./unittest/mediadatashare_test/src/abnormal_branch_test.cpp" ] + + deps = [ + "${datashare_innerapi_path}:datashare_consumer_static", + "${datashare_innerapi_path}/common:datashare_common_static", + ] + + 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", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_single", + "media_library:media_library", + "relational_store:rdb_data_ability_adapter", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] +} diff --git a/data_share/test/native/unittest/datashareproxy_test/proxydatas_with_permission_test.cpp b/data_share/test/native/unittest/datashareproxy_test/proxydatas_with_permission_test.cpp index 42b9acfb..e76367b0 100644 --- a/data_share/test/native/unittest/datashareproxy_test/proxydatas_with_permission_test.cpp +++ b/data_share/test/native/unittest/datashareproxy_test/proxydatas_with_permission_test.cpp @@ -127,6 +127,40 @@ HWTEST_F(ProxyDatasTest, ProxyDatasTest_QUERY_Test_001, TestSize.Level0) LOG_INFO("ProxyDatasTest_QUERY_Test_001::End"); } +HWTEST_F(ProxyDatasTest, ProxyDatasTest_ResultSet_Test_001, TestSize.Level0) +{ + LOG_INFO("ProxyDatasTest_ResultSet_Test_001::Start"); + auto helper = dataShareHelper; + Uri uri(DATA_SHARE_PROXY_URI); + DataShare::DataSharePredicates predicates; + predicates.EqualTo(TBL_NAME0, "wang"); + std::vector columns; + auto resultSet = helper->Query(uri, predicates, columns); + EXPECT_NE(resultSet, nullptr); + int result = 0; + resultSet->GetRowCount(result); + EXPECT_EQ(result, 1); + + AppDataFwk::SharedBlock *block = nullptr; + bool hasBlock = resultSet->HasBlock(); + EXPECT_EQ(hasBlock, true); + block = resultSet->GetBlock(); + EXPECT_NE(block, nullptr); + + std::vector blob; + int err = resultSet->GetBlob(-1, blob); + EXPECT_EQ(err, E_INVALID_COLUMN_INDEX); + resultSet->SetBlock(nullptr); + EXPECT_EQ(nullptr, resultSet->GetBlock()); + std::string stringValue; + result = resultSet->GetString(0, stringValue); + EXPECT_EQ(result, E_ERROR); + int intValue; + result = resultSet->GetInt(0, intValue); + EXPECT_EQ(result, E_ERROR); + LOG_INFO("ProxyDatasTest_ResultSet_Test_001::End"); +} + HWTEST_F(ProxyDatasTest, ProxyDatasTest_Template_Test_001, TestSize.Level0) { LOG_INFO("ProxyDatasTest_Template_Test_001::Start"); @@ -319,5 +353,36 @@ HWTEST_F(ProxyDatasTest, ProxyDatasTest_UnsubscribePublishedData_Test_001, TestS } LOG_INFO("ProxyDatasTest_UnsubscribePublishedData_Test_001::End"); } + +HWTEST_F(ProxyDatasTest, ProxyDatasTest_extSpCtl_Null_Test_001, TestSize.Level0) +{ + LOG_INFO("ProxyDatasTest_extSpCtl_Null_Test_001::Start"); + auto helper = dataShareHelper; + bool ret = helper->Release(); + EXPECT_EQ(ret, true); + Uri uri(""); + std::string str; + std::vector result = helper->GetFileTypes(uri, str); + EXPECT_EQ(result.size(), 0); + int err = helper->OpenFile(uri, str); + EXPECT_EQ(err, -1); + err = helper->OpenRawFile(uri, str); + EXPECT_EQ(err, -1); + LOG_INFO("ProxyDatasTest_extSpCtl_Null_Test_001::End"); +} + +HWTEST_F(ProxyDatasTest, ProxyDatasTest_extSpCtl_Null_Test_002, TestSize.Level0) +{ + LOG_INFO("ProxyDatasTest_extSpCtl_Null_Test_002::Start"); + auto helper = dataShareHelper; + bool ret = helper->Release(); + EXPECT_EQ(ret, true); + Uri uri(""); + Uri uriResult = helper->NormalizeUri(uri); + EXPECT_EQ(uriResult, uri); + uriResult = helper->DenormalizeUri(uri); + EXPECT_EQ(uriResult, uri); + LOG_INFO("ProxyDatasTest_extSpCtl_Null_Test_002::End"); +} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp new file mode 100644 index 00000000..68e6b599 --- /dev/null +++ b/data_share/test/native/unittest/mediadatashare_test/src/abnormal_branch_test.cpp @@ -0,0 +1,267 @@ +/* + * 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 +#include +#include "accesstoken_kit.h" +#include "datashare_helper.h" +#include "datashare_log.h" +#include "datashare_template.h" +#include "hap_token_info.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "token_setproc.h" +#include "datashare_errno.h" +#include "published_data_subscriber_manager.h" +#include "rdb_subscriber_manager.h" +#include "ishared_result_set_stub.h" +#include "message_parcel.h" +#include "ikvstore_data_service.h" +#include "shared_block.h" +#include "datashare_connection.h" + +namespace OHOS { +namespace DataShare { +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +class AbnormalBranchTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AbnormalBranchTest::SetUpTestCase(void) +{ +} +void AbnormalBranchTest::TearDownTestCase(void) +{ +} +void AbnormalBranchTest::SetUp(void) +{ +} +void AbnormalBranchTest::TearDown(void) +{ +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_shareBlock_Null_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_shareBlock_Null_Test_001::Start"); + DataShareBlockWriterImpl impl; + int result = impl.AllocRow(); + EXPECT_EQ(result, E_ERROR); + result = impl.Write(1); + EXPECT_EQ(result, E_ERROR); + int64_t intValue = 0; + result = impl.Write(1, intValue); + EXPECT_EQ(result, E_ERROR); + double doubleValue = 0.0; + result = impl.Write(1, doubleValue); + EXPECT_EQ(result, E_ERROR); + uint8_t *unitValue = nullptr; + result = impl.Write(1, unitValue, 0); + EXPECT_EQ(result, E_ERROR); + char *charValue = nullptr; + result = impl.Write(1, charValue, 0); + EXPECT_EQ(result, E_ERROR); + LOG_INFO("AbnormalBranchTest_shareBlock_Null_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_ResultSetStubNull_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_ResultSetStubNull_Test_001::Start"); + ISharedResultSetStub stub(nullptr); + std::shared_ptr result = nullptr; + OHOS::MessageParcel parcel; + sptr resultSet = stub.CreateStub(result, parcel); + EXPECT_EQ(resultSet, nullptr); + LOG_INFO("AbnormalBranchTest_ResultSetStubNull_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_RegisterClientDeathObserverNull_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_RegisterClientDeathObserverNull_Test_001::Start"); + DataShareKvServiceProxy proxy(nullptr); + std::string appId; + uint32_t result = proxy.RegisterClientDeathObserver(appId, nullptr); + EXPECT_EQ(result, -1); + LOG_INFO("AbnormalBranchTest_RegisterClientDeathObserverNull_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_mReadOnlyInvalid_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_mReadOnlyInvalid_Test_001::Start"); + std::string name; + size_t size = 0; + bool readOnly = true; + AppDataFwk::SharedBlock temp(name, nullptr, size, readOnly); + int result = temp.Clear(); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + result = temp.SetColumnNum(1); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + result = temp.AllocRow(); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + result = temp.FreeLastRow(); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + int64_t intValue = 0; + result = temp.PutLong(1, 1, intValue); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + double doubleValue = 0.0; + result = temp.PutDouble(1, 1, doubleValue); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + result = temp.PutNull(1, 1); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + result = temp.SetRawData(nullptr, size); + EXPECT_EQ(result, AppDataFwk::SharedBlock::SHARED_BLOCK_INVALID_OPERATION); + LOG_INFO("AbnormalBranchTest_mReadOnlyInvalid_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_CreatorPossibleNull_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_CreatorPossibleNull_Test_001::Start"); + std::string strUri; + CreateOptions options; + options.token_ = nullptr; + std::string bundleName; + std::shared_ptr dataHelper = DataShare::DataShareHelper::Creator(strUri, options, bundleName); + EXPECT_EQ(dataHelper, nullptr); + LOG_INFO("AbnormalBranchTest_CreatorPossibleNull_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_CreatorPossibleNull_Test_002, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_CreatorPossibleNull_Test_002::Start"); + std::string strUri; + CreateOptions options; + options.token_ = nullptr; + options.isProxy_ = false; + std::string bundleName; + std::shared_ptr dataHelper = DataShare::DataShareHelper::Creator(strUri, options, bundleName); + EXPECT_EQ(dataHelper, nullptr); + LOG_INFO("AbnormalBranchTest_CreatorPossibleNull_Test_002::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_AddObserversProxyNull_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_AddObserversProxyNull_Test_001::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + int64_t subscriberId = 0; + const PublishedDataCallback callback = [](const PublishedDataChangeNode &changeNode){}; + std::vector results = PublishedDataSubscriberManager::GetInstance().AddObservers(subscriber, + proxy, uris, subscriberId, callback); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_AddObserversProxyNull_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_AddObserversProxyNull_Test_002, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_AddObserversProxyNull_Test_002::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + TemplateId templateId; + const RdbCallback callback = [](const RdbChangeNode &changeNode){}; + std::vector results = RdbSubscriberManager::GetInstance().AddObservers(subscriber, proxy, uris, + templateId, callback); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_AddObserversProxyNull_Test_002::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_DelObserversProxyNull_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_DelObserversProxyNull_Test_001::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + int64_t subscriberId = 0; + std::vector results = PublishedDataSubscriberManager::GetInstance().DelObservers(subscriber, + proxy); + EXPECT_EQ(results.size(), uris.size()); + results = PublishedDataSubscriberManager::GetInstance().DelObservers(subscriber, proxy, uris, subscriberId); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_DelObserversProxyNull_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_DelObserversProxyNull_Test_002, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_DelObserversProxyNull_Test_002::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + TemplateId templateId; + std::vector results = RdbSubscriberManager::GetInstance().DelObservers(subscriber, proxy, uris, + templateId); + EXPECT_EQ(results.size(), uris.size()); + results = RdbSubscriberManager::GetInstance().DelObservers(subscriber, proxy); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_DelObserversProxyNull_Test_002::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_EnableObserversProxyNull_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_EnableObserversProxyNull_Test_001::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + int64_t subscriberId = 0; + std::vector results = PublishedDataSubscriberManager::GetInstance().EnableObservers(subscriber, + proxy, uris, subscriberId); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_EnableObserversProxyNull_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_EnableObserversProxyNull_Test_002, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_EnableObserversProxyNull_Test_002::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + TemplateId templateId; + std::vector results = RdbSubscriberManager::GetInstance().EnableObservers(subscriber, proxy, + uris, templateId); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_EnableObserversProxyNull_Test_002::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_DisableObserversProxyNull_Test_001, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_DisableObserversProxyNull_Test_001::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + int64_t subscriberId = 0; + std::vector results = PublishedDataSubscriberManager::GetInstance().DisableObservers(subscriber, + proxy, uris, subscriberId); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_DisableObserversProxyNull_Test_001::End"); +} + +HWTEST_F(AbnormalBranchTest, AbnormalBranchTest_DisableObserversProxyNull_Test_002, TestSize.Level0) +{ + LOG_INFO("AbnormalBranchTest_DisableObserversProxyNull_Test_002::Start"); + void *subscriber = nullptr; + std::shared_ptr proxy = nullptr; + const std::vector uris = {}; + TemplateId templateId; + std::vector results = RdbSubscriberManager::GetInstance().DisableObservers(subscriber, proxy, + uris, templateId); + EXPECT_EQ(results.size(), uris.size()); + LOG_INFO("AbnormalBranchTest_DisableObserversProxyNull_Test_002::End"); +} +} // namespace DataShare +} // namespace OHOS \ No newline at end of file diff --git a/data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp new file mode 100644 index 00000000..b727ef3a --- /dev/null +++ b/data_share/test/native/unittest/mediadatashare_test/src/controller_test.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (C) 2021-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 + +#include "abs_shared_result_set.h" +#include "accesstoken_kit.h" +#include "data_ability_observer_interface.h" +#include "dataobs_mgr_changeinfo.h" +#include "datashare_connection.h" +#include "datashare_helper.h" +#include "datashare_log.h" +#include "ext_special_controller.h" +#include "extension_manager_proxy.h" +#include "general_controller.h" +#include "general_controller_provider_impl.h" +#include "hap_token_info.h" +#include "iservice_registry.h" +#include "rdb_data_ability_utils.h" +#include "system_ability_definition.h" +#include "token_setproc.h" + +namespace OHOS { +namespace DataShare { +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +class ControllerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ControllerTest::SetUpTestCase(void) {} +void ControllerTest::TearDownTestCase(void) {} +void ControllerTest::SetUp(void) {} +void ControllerTest::TearDown(void) {} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplInsertTest_001, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplInsertTest_001::Start"); + Uri uri(""); + std::shared_ptr tempGenConProImp = + std::make_shared(nullptr, uri, nullptr); + DataShare::DataShareValuesBucket valuesBucket; + double valueD1 = 20.07; + valuesBucket.Put("phoneNumber", valueD1); + int result = tempGenConProImp->Insert(uri, valuesBucket); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ProviderImplInsertTest_001::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplInsertTest_002, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplInsertTest_002::Start"); + Uri uri(""); + sptr connection = + new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); + auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + std::shared_ptr tempGenConProImp = + std::make_shared(dataShareConnection, uri, nullptr); + DataShare::DataShareValuesBucket valuesBucket; + double valueD1 = 20.07; + valuesBucket.Put("phoneNumber", valueD1); + int result = tempGenConProImp->Insert(uri, valuesBucket); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ProviderImplInsertTest_002::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplUpdateTest_001, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplUpdateTest_001::Start"); + Uri uri(""); + std::shared_ptr tempGenConProImp = + std::make_shared(nullptr, uri, nullptr); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("name", "Controller_Test001"); + DataShare::DataShareValuesBucket valuesBucket; + valuesBucket.Put("name", "Controller_Test002"); + int result = tempGenConProImp->Update(uri, predicates, valuesBucket); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ProviderImplUpdateTest_001::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplUpdateTest_002, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplUpdateTest_002::Start"); + Uri uri(""); + sptr connection = + new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); + auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + std::shared_ptr tempGenConProImp = + std::make_shared(dataShareConnection, uri, nullptr); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("name", "Controller_Test001"); + DataShare::DataShareValuesBucket valuesBucket; + valuesBucket.Put("name", "Controller_Test002"); + int result = tempGenConProImp->Update(uri, predicates, valuesBucket); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ProviderImplUpdateTest_002::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplDeleteTest_001, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplDeleteTest_001::Start"); + Uri uri(""); + std::shared_ptr tempGenConProImp = + std::make_shared(nullptr, uri, nullptr); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("name", "Controller_Test001"); + int result = tempGenConProImp->Delete(uri, predicates); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ProviderImplDeleteTest_001::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplDeleteTest_002, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplDeleteTest_002::Start"); + Uri uri(""); + sptr connection = + new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); + auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + std::shared_ptr tempGenConProImp = + std::make_shared(dataShareConnection, uri, nullptr); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("name", "Controller_Test001"); + int result = tempGenConProImp->Delete(uri, predicates); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ProviderImplDeleteTest_002::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplQueryTest_001, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplQueryTest_001::Start"); + Uri uri(""); + std::shared_ptr tempGenConProImp = + std::make_shared(nullptr, uri, nullptr); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("name", "Controller_Test001"); + vector columns; + DatashareBusinessError error; + auto result = tempGenConProImp->Query(uri, predicates, columns, error); + EXPECT_EQ(result, nullptr); + LOG_INFO("ControllerTest_ProviderImplQueryTest_001::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ProviderImplQueryTest_002, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ProviderImplQueryTest_002::Start"); + Uri uri(""); + sptr connection = + new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); + auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + std::shared_ptr tempGenConProImp = + std::make_shared(dataShareConnection, uri, nullptr); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("name", "Controller_Test001"); + vector columns; + DatashareBusinessError error; + auto result = tempGenConProImp->Query(uri, predicates, columns, error); + EXPECT_EQ(result, nullptr); + LOG_INFO("ControllerTest_ProviderImplQueryTest_002::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerBatchInsertTest_001, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ExtSpecialControllerBatchInsertTest_001::Start"); + Uri uri(""); + std::shared_ptr tempExtSpeCon = + std::make_shared(nullptr, uri, nullptr); + DataShare::DataShareValuesBucket valuesBucket1; + valuesBucket1.Put("name", "dataShareTest006"); + valuesBucket1.Put("phoneNumber", 20.6); + DataShare::DataShareValuesBucket valuesBucket2; + valuesBucket2.Put("name", "dataShareTest007"); + valuesBucket2.Put("phoneNumber", 20.5); + std::vector values; + values.push_back(valuesBucket1); + values.push_back(valuesBucket2); + int result = tempExtSpeCon->BatchInsert(uri, values); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ExtSpecialControllerBatchInsertTest_001::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerBatchInsertTest_002, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ExtSpecialControllerBatchInsertTest_002::Start"); + Uri uri(""); + sptr connection = + new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); + auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + std::shared_ptr tempExtSpeCon = + std::make_shared(dataShareConnection, uri, nullptr); + DataShare::DataShareValuesBucket valuesBucket1; + valuesBucket1.Put("name", "dataShareTest006"); + valuesBucket1.Put("phoneNumber", 20.6); + DataShare::DataShareValuesBucket valuesBucket2; + valuesBucket2.Put("name", "dataShareTest007"); + valuesBucket2.Put("phoneNumber", 20.5); + std::vector values; + values.push_back(valuesBucket1); + values.push_back(valuesBucket2); + int result = tempExtSpeCon->BatchInsert(uri, values); + EXPECT_EQ((result < 0), true); + LOG_INFO("ControllerTest_ExtSpecialControllerBatchInsertTest_002::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerNormalizeUriTest_001, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ExtSpecialControllerNormalizeUriTest_001::Start"); + Uri uri(""); + std::shared_ptr tempExtSpeCon = + std::make_shared(nullptr, uri, nullptr); + Uri result = tempExtSpeCon->NormalizeUri(uri); + EXPECT_EQ(result, Uri("")); + LOG_INFO("ControllerTest_ExtSpecialControllerNormalizeUriTest_001::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerNormalizeUriTest_002, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ExtSpecialControllerNormalizeUriTest_002::Start"); + Uri uri(""); + sptr connection = + new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); + auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + std::shared_ptr tempExtSpeCon = + std::make_shared(dataShareConnection, uri, nullptr); + Uri result = tempExtSpeCon->NormalizeUri(uri); + EXPECT_EQ(result, Uri("")); + LOG_INFO("ControllerTest_ExtSpecialControllerNormalizeUriTest_002::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerDenormalizeUriTest_001, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ExtSpecialControllerDenormalizeUriTest_001::Start"); + Uri uri(""); + std::shared_ptr tempExtSpeCon = + std::make_shared(nullptr, uri, nullptr); + Uri result = tempExtSpeCon->DenormalizeUri(uri); + EXPECT_EQ(result, Uri("")); + LOG_INFO("ControllerTest_ExtSpecialControllerDenormalizeUriTest_001::End"); +} + +HWTEST_F(ControllerTest, ControllerTest_ExtSpecialControllerDenormalizeUriTest_002, TestSize.Level0) +{ + LOG_INFO("ControllerTest_ExtSpecialControllerDenormalizeUriTest_002::Start"); + Uri uri(""); + sptr connection = + new (std::nothrow) DataShare::DataShareConnection(uri, nullptr); + auto dataShareConnection = std::shared_ptr(connection.GetRefPtr()); + std::shared_ptr tempExtSpeCon = + std::make_shared(dataShareConnection, uri, nullptr); + Uri result = tempExtSpeCon->DenormalizeUri(uri); + EXPECT_EQ(result, Uri("")); + LOG_INFO("ControllerTest_ExtSpecialControllerDenormalizeUriTest_002::End"); +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp index 6e25720d..f6600fa1 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp @@ -797,7 +797,6 @@ HWTEST_F(MediaDataShareUnitTest, MediaDataShare_ResultSet_Test_001, TestSize.Lev std::shared_ptr helper = g_dataShareHelper; DataShare::DataSharePredicates predicates; predicates.Contains("name", "dataShareTest"); - std::vector columns; DataShare::DataShareResultSet resultSet; std::vector names; int err = resultSet.GetAllColumnNames(names); @@ -841,7 +840,11 @@ HWTEST_F(MediaDataShareUnitTest, MediaDataShare_ResultSet_Test_002, TestSize.Lev if (resultSet != nullptr) { resultSet->GoToFirstRow(); resultSet->GetColumnIndex("name", columnIndex); - int err = resultSet->GetBlob(columnIndex, blob); + std::string columnName; + int err = resultSet->GetColumnName(columnIndex, columnName); + EXPECT_EQ(err, 0); + EXPECT_EQ(columnName, "name"); + err = resultSet->GetBlob(columnIndex, blob); EXPECT_EQ(err, 0); EXPECT_NE(blob.size(), 0); diff --git a/datamgr_service/CMakeLists.txt b/datamgr_service/CMakeLists.txt index 9596fba6..32101c8a 100644 --- a/datamgr_service/CMakeLists.txt +++ b/datamgr_service/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(datamgr_service) add_subdirectory(services/distributeddataservice) add_subdirectory(services/distributeddataservice/service/data_share/gaussdb_rd) diff --git a/datamgr_service/services/distributeddataservice/CMakeLists.txt b/datamgr_service/services/distributeddataservice/CMakeLists.txt index 27b18304..75970a93 100644 --- a/datamgr_service/services/distributeddataservice/CMakeLists.txt +++ b/datamgr_service/services/distributeddataservice/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(dds) add_subdirectory(adapter) diff --git a/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.cpp b/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.cpp index f1f52b91..4ac875df 100644 --- a/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.cpp +++ b/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.cpp @@ -53,20 +53,20 @@ int32_t FeatureStubImpl::OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const return featureImpl_->OnAppExit(uid, pid, tokenId, bundleName); } -int32_t FeatureStubImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) +int32_t FeatureStubImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) { if (featureImpl_ == nullptr) { return -1; } - return featureImpl_->OnAppUninstall(bundleName, user, index, tokenId); + return featureImpl_->OnAppUninstall(bundleName, user, index); } -int32_t FeatureStubImpl::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) +int32_t FeatureStubImpl::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) { if (featureImpl_ == nullptr) { return -1; } - return featureImpl_->OnAppUpdate(bundleName, user, index, tokenId); + return featureImpl_->OnAppUpdate(bundleName, user, index); } int32_t FeatureStubImpl::ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) diff --git a/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.h b/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.h index b00646bc..b9714b95 100644 --- a/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.h +++ b/datamgr_service/services/distributeddataservice/app/src/feature_stub_impl.h @@ -32,8 +32,8 @@ public: MessageOption &option) override; int32_t OnInitialize(std::shared_ptr executor); int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName); - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId); - int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId); + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index); + int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index); int32_t ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m); int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account); int32_t Online(const std::string &device); diff --git a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp index 04a931c9..9eb32d47 100644 --- a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -683,21 +683,21 @@ void KvStoreDataService::OnDeviceOnReady(const AppDistributedKv::DeviceInfo &inf }); } -int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) +int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t user, int32_t index) { features_.ForEachCopies( - [bundleName, user, index, tokenId](const auto &, sptr &value) { - value->OnAppUninstall(bundleName, user, index, tokenId); + [bundleName, user, index](const auto &, sptr &value) { + value->OnAppUninstall(bundleName, user, index); return false; }); return 0; } -int32_t KvStoreDataService::OnUpdate(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) +int32_t KvStoreDataService::OnUpdate(const std::string &bundleName, int32_t user, int32_t index) { features_.ForEachCopies( - [bundleName, user, index, tokenId](const auto &, sptr &value) { - value->OnAppUpdate(bundleName, user, index, tokenId); + [bundleName, user, index](const auto &, sptr &value) { + value->OnAppUpdate(bundleName, user, index); return false; }); return 0; diff --git a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h index 12f949b2..a264d67b 100644 --- a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h @@ -75,9 +75,9 @@ public: void OnDeviceOnReady(const AppDistributedKv::DeviceInfo &info); - int32_t OnUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId); + int32_t OnUninstall(const std::string &bundleName, int32_t user, int32_t index); - int32_t OnUpdate(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId); + int32_t OnUpdate(const std::string &bundleName, int32_t user, int32_t index); private: void NotifyAccountEvent(const AccountEventInfo &eventInfo); diff --git a/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp b/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp index 01c06c4c..c6f05c8c 100644 --- a/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp +++ b/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp @@ -63,7 +63,7 @@ void UninstallEventSubscriber::OnReceiveEvent(const CommonEventData &event) void UninstallEventSubscriber::OnUninstall(const std::string &bundleName, int32_t userId, int32_t appIndex) { - kvStoreDataService_->OnUninstall(bundleName, userId, appIndex, IPCSkeleton::GetCallingTokenID()); + kvStoreDataService_->OnUninstall(bundleName, userId, appIndex); std::string prefix = StoreMetaData::GetPrefix( { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName }); std::vector storeMetaData; @@ -87,7 +87,7 @@ void UninstallEventSubscriber::OnUninstall(const std::string &bundleName, int32_ void UninstallEventSubscriber::OnUpdate(const std::string &bundleName, int32_t userId, int32_t appIndex) { - kvStoreDataService_->OnUpdate(bundleName, userId, appIndex, IPCSkeleton::GetCallingTokenID()); + kvStoreDataService_->OnUpdate(bundleName, userId, appIndex); std::string prefix = StoreMetaData::GetPrefix( { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName }); std::vector storeMetaData; diff --git a/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp b/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp index 74907ec8..98f67a10 100644 --- a/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp +++ b/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp @@ -65,14 +65,12 @@ int32_t FeatureSystem::Feature::OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId return E_OK; } -int32_t FeatureSystem::Feature::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, - uint32_t tokenId) +int32_t FeatureSystem::Feature::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) { return E_OK; } -int32_t FeatureSystem::Feature::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index, - uint32_t tokenId) +int32_t FeatureSystem::Feature::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) { return E_OK; } diff --git a/datamgr_service/services/distributeddataservice/framework/include/error/general_error.h b/datamgr_service/services/distributeddataservice/framework/include/error/general_error.h index 956478a6..575047f7 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/error/general_error.h +++ b/datamgr_service/services/distributeddataservice/framework/include/error/general_error.h @@ -19,7 +19,6 @@ namespace OHOS::DistributedData { enum GeneralError : int32_t { E_OK = 0, E_ERROR, - E_PARTIAL_ERROR, E_NETWORK_ERROR, E_CLOUD_DISABLED, E_LOCKED_BY_OTHERS, @@ -33,6 +32,7 @@ enum GeneralError : int32_t { E_ALREADY_CLOSED, E_UNOPENED, E_RETRY_TIMEOUT, + E_PARTIAL_ERROR, E_BUTT, }; } diff --git a/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h b/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h index d549cc6d..a94f0157 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h +++ b/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h @@ -46,8 +46,8 @@ public: virtual int32_t OnInitialize(); virtual int32_t OnBind(const BindInfo &bindInfo); virtual int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName); - virtual int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId); - virtual int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId); + virtual int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index); + virtual int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index); virtual int32_t ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m); virtual int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account); virtual int32_t Online(const std::string &device); diff --git a/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h b/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h index 6843d643..f30c9f07 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h +++ b/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h @@ -68,7 +68,13 @@ public: API_EXPORT static bool SetValue(json &node, const double &value); API_EXPORT static bool SetValue(json &node, const uint64_t &value); // Use bool & to forbid the const T * auto convert to bool, const bool will convert to const uint32_t &value; - API_EXPORT static bool SetValue(json &node, bool &value); + template + API_EXPORT static std::enable_if_t, bool> SetValue(json &node, const T &value) + { + node = static_cast(value); + return true; + } + API_EXPORT static bool SetValue(json &node, const std::vector &value); API_EXPORT static bool SetValue(json &node, const Serializable &value); diff --git a/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h b/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h index c7f78e9a..c39a328b 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h +++ b/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h @@ -67,6 +67,8 @@ public: virtual int32_t Execute(const std::string &table, const std::string &sql) = 0; + virtual int32_t SetDistributedTables(const std::vector &tables, int type) = 0; + virtual int32_t BatchInsert(const std::string &table, VBuckets &&values) = 0; virtual int32_t BatchUpdate(const std::string &table, const std::string &sql, VBuckets &&values) = 0; @@ -89,9 +91,7 @@ public: virtual int32_t AddRef() = 0; - virtual int32_t Release() = 0; - - virtual int32_t SetDistributedTables(const std::vector &tables, int type) = 0; + virtual int32_t Release() = 0; }; } // namespace OHOS::DistributedData #endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_STORE_GENERAL_STORE_H diff --git a/datamgr_service/services/distributeddataservice/framework/serializable/serializable.cpp b/datamgr_service/services/distributeddataservice/framework/serializable/serializable.cpp index 68fa96db..591c32f8 100644 --- a/datamgr_service/services/distributeddataservice/framework/serializable/serializable.cpp +++ b/datamgr_service/services/distributeddataservice/framework/serializable/serializable.cpp @@ -186,12 +186,6 @@ bool Serializable::SetValue(json &node, const uint64_t &value) return true; } -bool Serializable::SetValue(json &node, bool &value) -{ - node = value; - return true; -} - bool Serializable::SetValue(json &node, const std::vector &value) { node = value; diff --git a/datamgr_service/services/distributeddataservice/service/CMakeLists.txt b/datamgr_service/services/distributeddataservice/service/CMakeLists.txt index 310a7518..d9622fd0 100644 --- a/datamgr_service/services/distributeddataservice/service/CMakeLists.txt +++ b/datamgr_service/services/distributeddataservice/service/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(service) set(CMAKE_CXX_STANDARD 17) @@ -7,6 +7,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -fPIC -fpic -ffunction-s set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wformat=0 -fpermissive") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=deprecated-declarations -Wno-deprecated-declarations") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") set(MOCK_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../mock") set(KV_STORE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../kv_store") @@ -52,12 +53,12 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/data_share/gaussdb_rd/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/data_share/subscriber_managers) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/data_share) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/rdb) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/kvdb) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/udmf/lifecycle) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/udmf/permission) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/udmf/preprocess) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/udmf/store) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/udmf) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/kvdb) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../framework/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../adapter/include/log) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../adapter/include) @@ -72,11 +73,6 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../adapter/include/security) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../adapter/include/utils) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../app/src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../kv_store/frameworks/common) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../relational_store/interfaces/inner_api/appdatafwk/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../relational_store/interfaces/inner_api/cloud_data/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_data_share_adapter/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../relational_store/interfaces/inner_api/rdb_bms_adapter/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../data_share/interfaces/inner_api/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../data_share/interfaces/inner_api/provider/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../data_share/interfaces/inner_api/consumer/include) @@ -85,14 +81,11 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../data_share/framework include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../data_object/frameworks/innerkitsimpl/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../udmf/framework/common) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../udmf/framework/service) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../udmf/interfaces/innerkits/common) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../udmf/interfaces/innerkits/common) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../udmf/interfaces/innerkits/data) 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) include(${KV_STORE_DIR}/interfaces/CMakeLists.txt OPTIONAL) -set(links secure mock kvdb svcFwk adapter data_share udmf document_ut) +set(links secure mock kvdb svcFwk adapter data_share udmf document_ut cloud_data) set(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/../../../") add_library(service SHARED ${serviceSrc}) target_link_libraries(service ${links}) diff --git a/datamgr_service/services/distributeddataservice/service/cloud/GetSchema.puml b/datamgr_service/services/distributeddataservice/service/cloud/GetSchema.puml new file mode 100644 index 00000000..e96955ef --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/cloud/GetSchema.puml @@ -0,0 +1,35 @@ +@startuml +autonumber +actor Actor +entity CloudServiceImpl +entity MetaDataManager +entity CloudServer + +Actor -> CloudServiceImpl:GetScheama +CloudServiceImpl -> CloudServiceImpl:GetSchemaMeta(userId, bundleName, instanceId) +CloudServiceImpl -> MetaDataManager:GetCloudInfo(userId); +CloudServiceImpl <-- MetaDataManager:bool +alt 元数据不存在 +CloudServiceImpl -> CloudServer:GetCloudInfo(userId); +CloudServiceImpl <-- MetaDataManager:bool +end + +CloudServiceImpl -> CloudServiceImpl:CheckCloudInfo +alt CloudInfo invaild +CloudServiceImpl -> CloudServiceImpl:return +end + +CloudServiceImpl -> MetaDataManager:GetSchemaMeta(bundleName, instanceId) +CloudServiceImpl <-- MetaDataManager:bool +alt 找到APP Schema +CloudServiceImpl -> CloudServiceImpl:return +end + +CloudServiceImpl -> MetaDataManager:IsCloud(bundleName) +CloudServiceImpl <-- MetaDataManager:bool +alt false && +CloudServiceImpl -> CloudServiceImpl: 认证接受 +else 某种失败情况 +Bob -> Alice: 请重复 +end +@enduml \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index 65ba0305..596bd7db 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -21,7 +21,6 @@ #include "checker/checker_manager.h" #include "cloud/cloud_server.h" #include "communicator/device_manager_adapter.h" -#include "device_manager_adapter.h" #include "eventcenter/event_center.h" #include "ipc_skeleton.h" #include "log_print.h" @@ -177,8 +176,14 @@ int32_t CloudServiceImpl::Clean(const std::string &id, const std::mapExecute(std::move(task)); } + +std::map CloudServiceImpl::ConvertAction(const std::map &actions) +{ + std::map genActions; + for (const auto &[bundleName, action] : actions) { + switch (action) { + case CloudService::Action::CLEAR_CLOUD_INFO: + genActions.emplace(bundleName, GeneralStore::CleanMode::CLOUD_INFO); + break; + case CloudService::Action::CLEAR_CLOUD_DATA_AND_INFO: + genActions.emplace(bundleName, GeneralStore::CleanMode::CLOUD_DATA); + break; + default: + ZLOGE("invalid action. action:%{public}d, bundleName:%{public}s", action, bundleName.c_str()); + return {}; + } + } + return genActions; +} } // namespace OHOS::CloudData \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h index b2ed723a..85096676 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h @@ -38,7 +38,7 @@ public: int32_t OnInitialize() override; int32_t OnBind(const BindInfo &info) override; int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account) override; - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) override; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; int32_t Online(const std::string &device) override; int32_t Offline(const std::string &device) override; @@ -60,6 +60,8 @@ private: using Handles = std::deque; using Task = ExecutorPool::Task; + static std::map ConvertAction(const std::map &actions); + static constexpr int32_t RETRY_TIMES = 3; static constexpr int32_t RETRY_INTERVAL = 60; static constexpr int32_t EXPIRE_INTERVAL = 2 * 24; // 2 day diff --git a/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp b/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp index 8cf44724..e89cef75 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -362,8 +362,8 @@ AutoCache::Store SyncManager::GetStore(const StoreMetaData &meta, int32_t user, auto cloudDB = instance->ConnectCloudDB(meta.tokenId, dbMeta); auto assetLoader = instance->ConnectAssetLoader(meta.tokenId, dbMeta); if (mustBind && (cloudDB == nullptr || assetLoader == nullptr)) { - ZLOGE("failed, no cloud DB <0x%{public}x %{public}s<->%{public}s>", meta.tokenId, dbMeta.name.c_str(), - dbMeta.alias.c_str()); + ZLOGE("failed, no cloud DB <0x%{public}x %{public}s<->%{public}s>", meta.tokenId, + Anonymous::Change(dbMeta.name).c_str(), Anonymous::Change(dbMeta.alias).c_str()); return nullptr; } diff --git a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index 7ac7378b..ca9b7216 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -445,7 +445,7 @@ void DataShareServiceImpl::OnConnectDone() } int32_t DataShareServiceImpl::OnAppUninstall( - const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) + const std::string &bundleName, int32_t user, int32_t index) { ZLOGI("%{public}s uninstalled", bundleName.c_str()); PublishedData::Delete(bundleName, user); diff --git a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h index 4c82a69c..a71cc0d4 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h @@ -68,7 +68,7 @@ public: const int64_t subscriberId) override; void OnConnectDone() override; int32_t OnBind(const BindInfo &binderInfo) override; - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) override; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName) override; void NotifyObserver(const std::string &uri) override; diff --git a/datamgr_service/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp b/datamgr_service/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp index ca17e44a..26b116d4 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp @@ -49,7 +49,7 @@ int32_t PublishStrategy::Execute(std::shared_ptr context, const Publish if (status != E_OK) { ZLOGE("db Upsert failed, %{public}s %{public}s %{public}d", context->calledBundleName.c_str(), DistributedData::Anonymous::Change(context->uri).c_str(), status); - return -1; + return status; } return E_OK; } diff --git a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp index 55464231..c38e77dd 100644 --- a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp @@ -219,15 +219,14 @@ void ObjectServiceImpl::Clear() return; } -int32_t ObjectServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) +int32_t ObjectServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) { ZLOGI("begin. %{public}s", bundleName.c_str()); int32_t result = ObjectStoreManager::GetInstance()->DeleteByAppId(bundleName); if (result != OBJECT_SUCCESS) { pid_t uid = IPCSkeleton::GetCallingUid(); - uint32_t tokenId = IPCSkeleton::GetCallingTokenID(); - ZLOGE("Delete fail %{public}d, bundleName = %{public}s, uid = %{public}d, tokenId = 0x%{public}x", - result, bundleName.c_str(), uid, tokenId); + ZLOGE("Delete fail %{public}d, bundleName = %{public}s, uid = %{public}d", + result, bundleName.c_str(), uid); } return result; } diff --git a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h index 5206481e..f9e038a1 100644 --- a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h @@ -43,7 +43,7 @@ public: int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &appId) override; int32_t OnInitialize() override; int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account) override; - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId) override; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; int32_t OnBind(const BindInfo &bindInfo) override; private: diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp index 9f7981f0..163734b4 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp @@ -63,7 +63,7 @@ Asset RdbCloudDataTranslate::BlobToAsset(const std::vector &blob) return ValueProxy::Convert(asset); } -Assets RdbCloudDataTranslate::BlobToAssets(std::vector &blob) +Assets RdbCloudDataTranslate::BlobToAssets(const std::vector &blob) { DataAssets assets; if (ParserRawData(blob.data(), blob.size(), assets) == 0) { diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.h index f4d35043..dd8129e5 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.h @@ -30,7 +30,7 @@ public: std::vector AssetToBlob(const Asset &asset) override; std::vector AssetsToBlob(const Assets &assets) override; Asset BlobToAsset(const std::vector &blob) override; - Assets BlobToAssets(std::vector &blob) override; + Assets BlobToAssets(const std::vector &blob) override; private: using Serializable = DistributedData::Serializable; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp index 348fb808..269654c9 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_result_set_impl.cpp @@ -72,7 +72,7 @@ int RdbResultSetImpl::GetColumnIndex(const std::string &columnName, int &columnI } for (size_t i = 0; i < colNames_.size(); i++) { if (colNames_[i] == columnName) { - columnIndex = i; + columnIndex = static_cast(i); return NativeRdb::E_OK; } } diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 9994fee7..9a2ec41b 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -232,7 +232,6 @@ int32_t RdbServiceImpl::SetDistributedTables(const RdbSyncerParam ¶m, const Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } - return store->SetDistributedTables(tables, type); } @@ -435,6 +434,22 @@ int32_t RdbServiceImpl::OnInitialize() return RDB_OK; } +int32_t RdbServiceImpl::Delete(const RdbSyncerParam ¶m) +{ + auto tokenId = IPCSkeleton::GetCallingTokenID(); + AutoCache::GetInstance().CloseStore(tokenId, param.storeName_); + RdbSyncerParam tmpParam = param; + HapTokenInfo hapTokenInfo; + AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo); + tmpParam.bundleName_ = hapTokenInfo.bundleName; + auto storeMeta = GetStoreMetaData(tmpParam); + MetaDataManager::GetInstance().DelMeta(storeMeta.GetKey()); + MetaDataManager::GetInstance().DelMeta(storeMeta.GetSecretKey(), true); + MetaDataManager::GetInstance().DelMeta(storeMeta.GetStrategyKey()); + MetaDataManager::GetInstance().DelMeta(storeMeta.GetKeyLocal(), true); + return RDB_OK; +} + int32_t RdbServiceImpl::GetSchema(const RdbSyncerParam ¶m) { if (!CheckAccess(param.bundleName_, param.storeName_)) { @@ -618,6 +633,39 @@ int32_t RdbServiceImpl::OnBind(const BindInfo &bindInfo) return 0; } +int32_t RdbServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) +{ + return CloseStore(bundleName, user, index); +} + +int32_t RdbServiceImpl::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) +{ + return CloseStore(bundleName, user, index); +} + +int32_t RdbServiceImpl::CloseStore(const std::string &bundleName, int32_t user, int32_t index) const +{ + std::string prefix = StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(user), "default", bundleName }); + std::vector storeMetaData; + if (!MetaDataManager::GetInstance().LoadMeta(prefix, storeMetaData)) { + ZLOGE("load meta failed! bundleName:%{public}s, user:%{public}d, index:%{public}d", + bundleName.c_str(), user, index); + return E_ERROR; + } + for (const auto &meta : storeMetaData) { + if (meta.storeType < StoreMetaData::STORE_RELATIONAL_BEGIN || + meta.storeType > StoreMetaData::STORE_RELATIONAL_END) { + continue; + } + if (meta.instanceId == index && !meta.appId.empty() && !meta.storeId.empty()) { + AutoCache::GetInstance().CloseStore(meta.tokenId); + break; + } + } + return E_OK; +} + void RdbServiceImpl::SyncAgent::ReInit(pid_t pid, const std::string &bundleName) { pid_ = pid; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h index f09d641b..8a8a738a 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -65,8 +65,14 @@ public: int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName) override; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; + + int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) override; + int32_t GetSchema(const RdbSyncerParam ¶m) override; + int32_t Delete(const RdbSyncerParam ¶m) override; + int32_t OnBind(const BindInfo &bindInfo) override; private: @@ -124,6 +130,8 @@ private: static bool GetPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password); + int32_t CloseStore(const std::string &bundleName, int32_t user, int32_t index) const; + static Factory factory_; ConcurrentMap syncAgents_; std::shared_ptr executors_; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp index 8e602e5c..2e42628b 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp @@ -56,6 +56,21 @@ int32_t RdbServiceStub::OnGetSchema(MessageParcel &data, MessageParcel &reply) return RDB_OK; } +int32_t RdbServiceStub::OnDelete(MessageParcel &data, MessageParcel &reply) +{ + RdbSyncerParam param; + if (!ITypesUtil::Unmarshal(data, param)) { + ZLOGE("Unmarshal storeName_:%{public}s", Anonymous::Change(param.storeName_).c_str()); + return IPC_STUB_INVALID_DATA_ERR; + } + auto status = Delete(param); + if (!ITypesUtil::Marshal(reply, status)) { + ZLOGE("Marshal status:0x%{public}x", status); + return IPC_STUB_WRITE_PARCEL_ERR; + } + return RDB_OK; +} + int32_t RdbServiceStub::OnRemoteInitNotifier(MessageParcel &data, MessageParcel &reply) { RdbSyncerParam param; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.h index fbd2173a..8b4aff5f 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.h @@ -36,6 +36,8 @@ private: int32_t OnGetSchema(MessageParcel& data, MessageParcel& reply); + int32_t OnDelete(MessageParcel& data, MessageParcel& reply); + int32_t OnRemoteInitNotifier(MessageParcel& data, MessageParcel& reply); int32_t OnRemoteSetDistributedTables(MessageParcel& data, MessageParcel& reply); @@ -62,7 +64,8 @@ private: [static_cast(RdbServiceCode::RDB_SERVICE_CMD_SUBSCRIBE)] = &RdbServiceStub::OnRemoteDoSubscribe, [static_cast(RdbServiceCode::RDB_SERVICE_CMD_UNSUBSCRIBE)] = &RdbServiceStub::OnRemoteDoUnSubscribe, [static_cast(RdbServiceCode::RDB_SERVICE_CMD_REMOTE_QUERY)] = &RdbServiceStub::OnRemoteDoRemoteQuery, - [static_cast(RdbServiceCode::RDB_SERVICE_CMD_GET_SCHEMA)] = &RdbServiceStub::OnGetSchema + [static_cast(RdbServiceCode::RDB_SERVICE_CMD_GET_SCHEMA)] = &RdbServiceStub::OnGetSchema, + [static_cast(RdbServiceCode::RDB_SERVICE_CMD_DELETE)] = &RdbServiceStub::OnDelete }; }; } // namespace OHOS::DistributedRdb diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.cpp index a0d4d0ed..7544ebda 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.cpp @@ -19,6 +19,7 @@ #include "error/general_error.h" #include "log_print.h" +#include "utils/anonymous.h" namespace OHOS::DistributedRdb { using namespace DistributedData; @@ -38,6 +39,10 @@ int32_t RdbWatcher::OnChange(const Origin &origin, const PRIFields &primaryField rdbOrigin.dataType = origin.dataType; rdbOrigin.id = origin.id; rdbOrigin.store = origin.store; + ZLOGD("store:%{public}s data change from :%{public}s, dataType:%{public}d, origin:%{public}d.", + Anonymous::Change(rdbOrigin.store).c_str(), + rdbOrigin.id.empty() ? "empty" : Anonymous::Change(*rdbOrigin.id.begin()).c_str(), + rdbOrigin.dataType, rdbOrigin.origin); notifier->OnChange(rdbOrigin, primaryFields, std::move(values)); return E_OK; } diff --git a/datamgr_service/services/distributeddataservice/service/test/config_factory_test.cpp b/datamgr_service/services/distributeddataservice/service/test/config_factory_test.cpp index 70a6a5ad..02106109 100644 --- a/datamgr_service/services/distributeddataservice/service/test/config_factory_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/config_factory_test.cpp @@ -61,7 +61,7 @@ HWTEST_F(ConfigFactoryTest, ComponentConfig, TestSize.Level0) { auto *components = ConfigFactory::GetInstance().GetComponentConfig(); ASSERT_NE(components, nullptr); - ASSERT_EQ(components->size(), 3); + ASSERT_EQ(components->size(), 4); const ComponentConfig &config = (*components)[0]; ASSERT_EQ(config.description, "3rd party adapter"); ASSERT_EQ(config.lib, "libconfigdemo.z.so"); diff --git a/datamgr_service/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/datashareservicestub_fuzzer.cpp b/datamgr_service/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/datashareservicestub_fuzzer.cpp index f077c324..88e4f915 100644 --- a/datamgr_service/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/datashareservicestub_fuzzer.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/datashareservicestub_fuzzer.cpp @@ -28,7 +28,7 @@ using namespace OHOS::DataShare; namespace OHOS { const std::u16string INTERFACE_TOKEN = u"OHOS.DataShare.IDataShareService"; constexpr uint32_t CODE_MIN = 0; -constexpr uint32_t CODE_MAX = 16; +constexpr uint32_t CODE_MAX = 17; constexpr size_t NUM_MIN = 5; constexpr size_t NUM_MAX = 12; diff --git a/datamgr_service/services/distributeddataservice/service/udmf/data_manager.cpp b/datamgr_service/services/distributeddataservice/service/udmf/data_manager.cpp index 4d1af700..b8c38af5 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/data_manager.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/data_manager.cpp @@ -17,6 +17,7 @@ #include "data_manager.h" #include "checker_manager.h" +#include "dfx_types.h" #include "file.h" #include "lifecycle/lifecycle_manager.h" #include "log_print.h" @@ -109,7 +110,7 @@ int32_t DataManager::RetrieveData(const QueryOption &query, UnifiedData &unified } int32_t res = store->Get(query.key, unifiedData); if (res != E_OK) { - ZLOGE("Get data from store failed, key: %{public}s.", query.key.c_str()); + ZLOGE("Get data from store failed, res: %{public}d, key: %{public}s.", res, query.key.c_str()); return res; } @@ -122,7 +123,7 @@ int32_t DataManager::RetrieveData(const QueryOption &query, UnifiedData &unified CheckerManager::CheckInfo info; info.tokenId = query.tokenId; - if (!CheckerManager::GetInstance().IsValid(runtime->privileges, info)) { + if (!CheckerManager::GetInstance().IsValid(runtime->privileges, info) && !CheckPermissionInCache(query)) { return E_NO_PERMISSION; } @@ -138,10 +139,21 @@ int32_t DataManager::RetrieveData(const QueryOption &query, UnifiedData &unified ZLOGE("Remove data failed, intention: %{public}s.", key.intention.c_str()); return E_DB_ERROR; } + privilegeCache_.erase(query.key); + PreProcessUtils::SetRemoteData(unifiedData); return E_OK; } +bool DataManager::CheckPermissionInCache(const QueryOption &query) +{ + auto iter = privilegeCache_.find(query.key); + if (iter != privilegeCache_.end() && iter->second.tokenId == query.tokenId) { + return true; + } + return false; +} + int32_t DataManager::ProcessingUri(const QueryOption &query, UnifiedData &unifiedData) { std::string localDeviceId = PreProcessUtils::GetLocalDeviceId(); @@ -320,16 +332,15 @@ int32_t DataManager::AddPrivilege(const QueryOption &query, const Privilege &pri UnifiedData data; int32_t res = store->Get(query.key, data); + if (res == E_NOT_FOUND) { + privilegeCache_[query.key] = privilege; + ZLOGW("Add privilege in cache, key: %{public}s.", query.key.c_str()); + return E_OK; + } if (res != E_OK) { - ZLOGE("Get data from store failed, intention: %{public}s.", key.intention.c_str()); + ZLOGE("Get data from store failed, res:%{public}d,intention: %{public}s.", res, key.intention.c_str()); return res; } - - if (data.IsEmpty()) { - ZLOGE("Invalid parameters, unified data has no record, intention: %{public}s.", key.intention.c_str()); - return E_INVALID_PARAMETERS; - } - data.GetRuntime()->privileges.emplace_back(privilege); if (store->Update(data) != E_OK) { ZLOGE("Update unified data failed, intention: %{public}s.", key.intention.c_str()); diff --git a/datamgr_service/services/distributeddataservice/service/udmf/data_manager.h b/datamgr_service/services/distributeddataservice/service/udmf/data_manager.h index 981d701b..02a8f013 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/data_manager.h +++ b/datamgr_service/services/distributeddataservice/service/udmf/data_manager.h @@ -22,7 +22,7 @@ #include #include "error_code.h" -#include "store/store_cache.h" +#include "store_cache.h" #include "unified_data.h" #include "unified_types.h" @@ -47,8 +47,11 @@ private: DataManager(); int32_t QueryDataCommon(const QueryOption &query, std::vector &dataSet, std::shared_ptr &store); int32_t ProcessingUri(const QueryOption &query, UnifiedData &unifiedData); + bool CheckPermissionInCache(const QueryOption &query); + StoreCache storeCache_; std::map authorizationMap_; + std::map privilegeCache_; }; } // namespace UDMF } // namespace OHOS diff --git a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h index 6f6ef638..45f8e63a 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h +++ b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h @@ -18,7 +18,7 @@ #include #include -#include "store/store_cache.h" +#include "store_cache.h" #include "unified_key.h" namespace OHOS { diff --git a/kv_store/BUILD.gn b/kv_store/BUILD.gn index 613ec6ea..75794e33 100644 --- a/kv_store/BUILD.gn +++ b/kv_store/BUILD.gn @@ -34,6 +34,7 @@ group("unittest") { testonly = true deps = [] deps += [ + "frameworks/common/test:unittest", "frameworks/innerkitsimpl/kvdb/test:unittest", "test/unittest/distributedKVStore:unittest", "test/unittest/distributeddata:unittest", diff --git a/kv_store/CMakeLists.txt b/kv_store/CMakeLists.txt index 1ce777ed..51b40866 100644 --- a/kv_store/CMakeLists.txt +++ b/kv_store/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(kv_store) add_subdirectory(frameworks/libs) diff --git a/kv_store/bundle.json b/kv_store/bundle.json index be74bfc0..0253ff77 100644 --- a/kv_store/bundle.json +++ b/kv_store/bundle.json @@ -182,6 +182,7 @@ "//foundation/distributeddatamgr/kv_store:fuzztest", "//foundation/distributeddatamgr/kv_store/test/unittest/distributeddata:unittest", "//foundation/distributeddatamgr/kv_store/test/unittest/distributedKVStore:unittest", + "//foundation/distributeddatamgr/kv_store/frameworks/common/test:unittest", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/test:unittest" ] } diff --git a/kv_store/frameworks/CMakeLists.txt b/kv_store/frameworks/CMakeLists.txt index b19a0511..52aa2a46 100644 --- a/kv_store/frameworks/CMakeLists.txt +++ b/kv_store/frameworks/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(kvdb) set(CMAKE_CXX_STANDARD 17) @@ -19,7 +19,6 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/common) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/distributeddatafwk/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/distributeddatafwk/src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/kvdb/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../interfaces/innerkits/distributeddata/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../frameworks/libs/distributeddb/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../frameworks/libs/distributeddb/interfaces/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../frameworks/libs/distributeddb/interfaces/include/relational) @@ -36,7 +35,6 @@ add_library(jsolddb SHARED ${jsDataSrc}) target_link_libraries(kvdb ${links}) target_link_libraries(jskvdb ${links} kvdb) target_link_libraries(jsolddb ${links} kvdb) -target_include_directories(jskvdb PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/jskitsimpl/distributedkvstore/include") -target_include_directories(jsolddb PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/jskitsimpl/distributeddata/include") \ No newline at end of file +target_include_directories(kvdb PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../interfaces/innerkits/distributeddata/include) +target_include_directories(jskvdb PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/jskitsimpl/distributedkvstore/include") +target_include_directories(jsolddb PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/jskitsimpl/distributeddata/include") \ No newline at end of file diff --git a/kv_store/frameworks/common/itypes_util.h b/kv_store/frameworks/common/itypes_util.h index 937e5a5f..dafdc8d3 100644 --- a/kv_store/frameworks/common/itypes_util.h +++ b/kv_store/frameworks/common/itypes_util.h @@ -36,6 +36,8 @@ template struct is_container> : std::true_type { }; namespace ITypesUtil { +static constexpr size_t MAX_COUNT = 100000; +static constexpr size_t MAX_SIZE = 1 * 1024 * 1024 * 1024; //1G static inline bool Marshal(MessageParcel &data) { return true; @@ -395,7 +397,7 @@ bool ITypesUtil::UnmarshalFromContainer(T &val, MessageParcel &parcel) template bool ITypesUtil::MarshalToBuffer(const T &input, int size, MessageParcel &data) { - if (!data.WriteInt32(size)) { + if (size < 0 || static_cast(size) > MAX_SIZE || !data.WriteInt32(size)) { return false; } if (size == 0) { @@ -417,7 +419,7 @@ bool ITypesUtil::MarshalToBuffer(const T &input, int size, MessageParcel &data) template bool ITypesUtil::MarshalToBuffer(const std::vector &input, int size, MessageParcel &data) { - if (!data.WriteInt32(size)) { + if (size < 0 || static_cast(size) > MAX_SIZE || input.size() > MAX_COUNT || !data.WriteInt32(size)) { return false; } if (size == 0) { @@ -449,6 +451,9 @@ bool ITypesUtil::UnmarshalFromBuffer(MessageParcel &data, T &output) if (size == 0) { return true; } + if (size < 0 || static_cast(size) > MAX_SIZE) { + return false; + } const uint8_t *buffer = reinterpret_cast(data.ReadRawData(size)); if (buffer == nullptr) { return false; @@ -463,10 +468,12 @@ bool ITypesUtil::UnmarshalFromBuffer(MessageParcel &data, std::vector &output if (size == 0) { return true; } - + if (size < 0 || static_cast(size) > MAX_SIZE) { + return false; + } int count = data.ReadInt32(); const uint8_t *buffer = reinterpret_cast(data.ReadRawData(size)); - if (count < 0 || buffer == nullptr) { + if (count < 0 || static_cast(count) > MAX_COUNT || buffer == nullptr) { return false; } diff --git a/kv_store/frameworks/common/test/BUILD.gn b/kv_store/frameworks/common/test/BUILD.gn new file mode 100644 index 00000000..08c9e2ba --- /dev/null +++ b/kv_store/frameworks/common/test/BUILD.gn @@ -0,0 +1,104 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") + +module_output_path = "kv_store/common" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ "../" ] +} + +############################################################################### +ohos_unittest("ConcurrentMapTest") { + module_out_path = module_output_path + + sources = [ "concurrent_map_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + deps = [ "//third_party/googletest:gtest" ] +} + +ohos_unittest("ExecutorPoolTest") { + module_out_path = module_output_path + + sources = [ "executor_pool_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ "c_utils:utils" ] + + deps = [ "//third_party/googletest:gtest" ] +} + +ohos_unittest("LruBucketTest") { + module_out_path = module_output_path + + sources = [ "lru_bucket_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ "c_utils:utils" ] + + deps = [ "//third_party/googletest:gtest" ] +} + +ohos_unittest("TaskSchedulerTest") { + module_out_path = module_output_path + + sources = [ "task_scheduler_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ "c_utils:utils" ] + + deps = [ "//third_party/googletest:gtest" ] +} + +ohos_unittest("TraitsTest") { + module_out_path = module_output_path + + sources = [ "traits_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ "c_utils:utils" ] + + deps = [ "//third_party/googletest:gtest" ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [] + deps += [ + ":ConcurrentMapTest", + ":ExecutorPoolTest", + ":LruBucketTest", + ":TaskSchedulerTest", + ":TraitsTest", + ] +} +############################################################################### diff --git a/kv_store/frameworks/common/test/executor_pool_test.cpp b/kv_store/frameworks/common/test/executor_pool_test.cpp index aca8d486..900b63ac 100644 --- a/kv_store/frameworks/common/test/executor_pool_test.cpp +++ b/kv_store/frameworks/common/test/executor_pool_test.cpp @@ -12,11 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "executor_pool.h" - #include #include "block_data.h" +#include "executor_pool.h" namespace OHOS::Test { using namespace testing::ext; @@ -110,10 +109,10 @@ HWTEST_F(ExecutorPoolTest, MultiSchedule, TestSize.Level0) std::set ids; for (int i = 0; i < 10; ++i) { auto id = executorPool_->Schedule(task, std::chrono::seconds(0), std::chrono::seconds(LONG_INTERVAL), 10); - ASSERT_NE(*(ids.end()), id); + ASSERT_EQ(ids.count(id), 0); ids.insert(id); } - std::this_thread::sleep_for(std::chrono::milliseconds(LONG_INTERVAL * 10)); + std::this_thread::sleep_for(std::chrono::seconds(LONG_INTERVAL * 10)); ASSERT_EQ(data->data, 100); for (auto id : ids) { executorPool_->Remove(id); @@ -158,7 +157,7 @@ HWTEST_F(ExecutorPoolTest, Reset, TestSize.Level0) std::this_thread::sleep_for(std::chrono::milliseconds(SHORT_INTERVAL)); ASSERT_EQ(data->data, 1); ASSERT_EQ(executorPool_->Reset(temp, std::chrono::milliseconds(expiredTime * 2)), temp); - std::this_thread::sleep_for(expiredTime * 4); + std::this_thread::sleep_for(std::chrono::milliseconds(expiredTime * 5)); ASSERT_EQ(data->data, 3); executorPool_->Remove(temp); } diff --git a/kv_store/frameworks/common/test/traits_test.cpp b/kv_store/frameworks/common/test/traits_test.cpp index c0d9844f..15c1d664 100644 --- a/kv_store/frameworks/common/test/traits_test.cpp +++ b/kv_store/frameworks/common/test/traits_test.cpp @@ -22,9 +22,6 @@ public: class From { public: From() {} - - private: - int64_t id_ = 0; }; class Convertible { public: @@ -40,8 +37,6 @@ public: { return From(); } - private: - int64_t id_ = 1; }; static void SetUpTestCase(void){}; static void TearDownTestCase(void){}; @@ -207,7 +202,6 @@ HWTEST_F(TraitsTest, get_if_convertible_type, TestSize.Level0) value = int64_t(1); auto *fVal = Traits::get_if(&value); ASSERT_EQ(fVal, nullptr); - ASSERT_EQ(*fVal, 1); value = "test case"; auto *strVal = Traits::get_if(&value); diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp index 896aad48..31b4b8f6 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/types_util_test.cpp @@ -198,3 +198,69 @@ HWTEST_F(TypesUtilTest, Variant, TestSize.Level0) ASSERT_EQ(std::get(valueUint64Out), 110); } +/** +* @tc.name: MarshalToBufferLimitTest001 +* @tc.desc: construct a invalid vector and check MarshalToBuffer function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: ht +*/ +HWTEST_F(TypesUtilTest, MarshalToBufferLimitTest001, TestSize.Level1) +{ + MessageParcel parcel; + std::vector exceedMaxCountInput(ITypesUtil::MAX_COUNT + 1); + ASSERT_FALSE(ITypesUtil::MarshalToBuffer(exceedMaxCountInput, sizeof(int) * exceedMaxCountInput.size(), parcel)); +} + +/** +* @tc.name: MarshalToBufferLimitTest002 +* @tc.desc: construct a invalid vector and check MarshalToBuffer function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: ht +*/ +HWTEST_F(TypesUtilTest, MarshalToBufferLimitTest002, TestSize.Level1) +{ + MessageParcel parcel; + std::vector inputNormal(10); + ASSERT_FALSE(ITypesUtil::MarshalToBuffer(inputNormal, ITypesUtil::MAX_SIZE + 1, parcel)); + ASSERT_FALSE(ITypesUtil::MarshalToBuffer(inputNormal, -1, parcel)); +} + +/** +* @tc.name: UnmarshalFromBufferLimitTest001 +* @tc.desc: construct a invalid parcel and check UnmarshalFromBuffer function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: ht +*/ +HWTEST_F(TypesUtilTest, UnmarshalFromBufferLimitTest001, TestSize.Level1) +{ + MessageParcel parcel; + int32_t normalSize = 100; + parcel.WriteInt32(normalSize); //normal size + parcel.WriteInt32(ITypesUtil::MAX_COUNT + 1); //exceed MAX_COUNT + std::vector input; + std::unique_ptr buffer = std::make_unique(normalSize); + parcel.WriteRawData(buffer.get(), normalSize); + + std::vector output; + ASSERT_FALSE(ITypesUtil::UnmarshalFromBuffer(parcel, output)); + ASSERT_TRUE(output.empty()); +} + +/** +* @tc.name: UnmarshalFromBufferLimitTest002 +* @tc.desc: construct a invalid parcel and check UnmarshalFromBuffer function. +* @tc.type: FUNC +* @tc.require: +* @tc.author: ht +*/ +HWTEST_F(TypesUtilTest, UnmarshalFromBufferLimitTest002, TestSize.Level1) +{ + MessageParcel parcel; + parcel.WriteInt32(ITypesUtil::MAX_SIZE + 1); //exceedMaxSize size + std::vector output; + ASSERT_FALSE(ITypesUtil::UnmarshalFromBuffer(parcel, output)); + ASSERT_TRUE(output.empty()); +} diff --git a/kv_store/frameworks/jskitsimpl/distributeddata/src/js_util.cpp b/kv_store/frameworks/jskitsimpl/distributeddata/src/js_util.cpp index 42579340..7d8debfb 100644 --- a/kv_store/frameworks/jskitsimpl/distributeddata/src/js_util.cpp +++ b/kv_store/frameworks/jskitsimpl/distributeddata/src/js_util.cpp @@ -1140,7 +1140,7 @@ napi_status JSUtil::GetValue(napi_env env, napi_value in, ContextParam ¶m) napi_value hapInfo = nullptr; GetNamedProperty(env, in, "currentHapModuleInfo", hapInfo); if (hapInfo != nullptr) { - status = GetNamedProperty(env, hapInfo, "moduleName", param.hapName); + status = GetNamedProperty(env, hapInfo, "name", param.hapName); CHECK_RETURN(status == napi_ok, "get hap name failed", napi_invalid_arg); } return napi_ok; diff --git a/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_util.cpp b/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_util.cpp index 6c00358c..c219469e 100644 --- a/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_util.cpp +++ b/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_util.cpp @@ -1026,11 +1026,10 @@ JSUtil::StatusMsg JSUtil::GetValue(napi_env env, napi_value in, DistributedKv::O int32_t level = 0; statusMsg = GetNamedProperty(env, in, "securityLevel", level); - if (statusMsg.status != napi_ok) { - return statusMsg; - } - - return GetLevel(level, options.securityLevel); + ASSERT(statusMsg.status == napi_ok, "get securityLevel failed", statusMsg); + statusMsg = GetLevel(level, options.securityLevel); + ASSERT(statusMsg.status == napi_ok, "invalid securityLevel", statusMsg); + return napi_ok; } napi_status JSUtil::GetLevel(int32_t level, int32_t &out) diff --git a/kv_store/frameworks/libs/distributeddb/common/include/db_common.h b/kv_store/frameworks/libs/distributeddb/common/include/db_common.h index 45862581..2cdb848c 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/db_common.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/db_common.h @@ -33,7 +33,7 @@ public: static inline std::string GetLogTableName(const std::string &tableName) { - return DBConstant::RELATIONAL_PREFIX + tableName + "_log"; + return DBConstant::RELATIONAL_PREFIX + tableName + DBConstant::LOG_POSTFIX; } static std::string VectorToHexString(const std::vector &inVec, const std::string &separator = ""); diff --git a/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h b/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h index ac83b98b..aab366fd 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h @@ -145,6 +145,7 @@ public: // For relational static const std::string RELATIONAL_PREFIX; static const std::string TIMESTAMP_ALIAS; + static const std::string LOG_POSTFIX; static const std::string LOG_TABLE_VERSION_1; static const std::string LOG_TABLE_VERSION_2; diff --git a/kv_store/frameworks/libs/distributeddb/common/include/db_types.h b/kv_store/frameworks/libs/distributeddb/common/include/db_types.h index 02706faa..ab8f2b82 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/db_types.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/db_types.h @@ -28,8 +28,6 @@ namespace DistributedDB { using TableName = std::string; using Timestamp = uint64_t; -using LocalWaterMark = Timestamp; -using CloudWaterMark = std::string; using ContinueToken = void *; using DeviceID = std::string; using TimeOffset = int64_t; diff --git a/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp b/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp index e19c6683..eb7a24d0 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp @@ -68,9 +68,11 @@ const std::string DBConstant::UPDATE_META_FUNC = "update_meta_within_trigger"; const std::string DBConstant::SYSTEM_TABLE_PREFIX = "naturalbase_rdb_"; const std::string DBConstant::RELATIONAL_PREFIX = "naturalbase_rdb_aux_"; const std::string DBConstant::TIMESTAMP_ALIAS = "naturalbase_rdb_aux_timestamp"; +const std::string DBConstant::LOG_POSTFIX = "_log"; const std::string DBConstant::LOG_TABLE_VERSION_1 = "1.0"; const std::string DBConstant::LOG_TABLE_VERSION_2 = "2.0"; +const char *LOG_TABLE_VERSION_3 = "3.0"; const std::string DBConstant::LOG_TABLE_VERSION_CURRENT = "3.0"; const std::string DBConstant::LOG_TABLE_VERSION_KEY = "log_table_version"; diff --git a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp index 40b66cb3..880edecb 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp @@ -185,21 +185,27 @@ Task TaskPoolImpl::ReapTask(TaskQueue *&queue) return nullptr; } -int TaskPoolImpl::GetTask(Task &task, TaskQueue *&queue) +void TaskPoolImpl::GetTask(Task &task, TaskQueue *&queue) { std::unique_lock lock(tasksMutex_); while (true) { task = ReapTask(queue); if (task != nullptr) { - return E_OK; + return; } if (IdleExit(lock)) { break; } } - return E_OK; + if (task == nullptr) { + // Idle thread exit. + if (IsGenericWorker()) { + genericThread_ = std::thread::id(); + } + --curThreads_; + } } int TaskPoolImpl::SpawnThreads(bool isStart) @@ -241,10 +247,6 @@ void TaskPoolImpl::BecomeGenericWorker() void TaskPoolImpl::ExitWorker() { std::lock_guard guard(tasksMutex_); - if (IsGenericWorker()) { - genericThread_ = std::thread::id(); - } - --curThreads_; allThreadsExited_.notify_all(); LOGI("Task pool thread exit, cur:%d idle:%d, genericTaskCount:%d, queuedTaskCount:%d.", curThreads_, idleThreads_, genericTaskCount_, queuedTaskCount_); @@ -258,11 +260,7 @@ void TaskPoolImpl::TaskWorker() TaskQueue *taskQueue = nullptr; Task task = nullptr; - int errCode = GetTask(task, taskQueue); - if (errCode != E_OK) { - LOGE("Thread worker gets task failed, err:'%d'.", errCode); - break; - } + GetTask(task, taskQueue); if (task == nullptr) { // Idle thread exit. break; diff --git a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h index 97440afc..ed998892 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h +++ b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h @@ -54,7 +54,7 @@ private: bool IdleExit(std::unique_lock &lock); void SetThreadFree(); Task ReapTask(TaskQueue *&queue); - int GetTask(Task &task, TaskQueue *&queue); + void GetTask(Task &task, TaskQueue *&queue); bool IsGenericWorker() const; void BecomeGenericWorker(); void ExitWorker(); diff --git a/kv_store/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h b/kv_store/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h index 6a641864..ed30b0d6 100644 --- a/kv_store/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h +++ b/kv_store/frameworks/libs/distributeddb/communicator/include/communicator_aggregator.h @@ -141,7 +141,7 @@ private: void TriggerSendData(); - void ResetFrameRecordIfNeed(uint32_t frameId, uint32_t mtu); + void ResetFrameRecordIfNeed(const uint32_t frameId, const uint32_t mtu); DECLARE_OBJECT_TAG(CommunicatorAggregator); diff --git a/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp b/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp index c1579be1..0b1efd0a 100644 --- a/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp +++ b/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_aggregator.cpp @@ -959,7 +959,7 @@ void CommunicatorAggregator::TriggerSendData() } } -void CommunicatorAggregator::ResetFrameRecordIfNeed(uint32_t frameId, uint32_t mtu) +void CommunicatorAggregator::ResetFrameRecordIfNeed(const uint32_t frameId, const uint32_t mtu) { std::lock_guard autoLock(sendRecordMutex_); if (sendRecord_[frameId].splitMtu == 0u || sendRecord_[frameId].splitMtu != mtu) { diff --git a/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp b/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp index ede623f0..42a232f7 100644 --- a/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp +++ b/kv_store/frameworks/libs/distributeddb/communicator/src/communicator_linker.cpp @@ -239,14 +239,15 @@ void CommunicatorLinker::SuspendByOnceTimer(const std::function &inA inAction(); return -E_END_TIMER; }, nullptr, thisTimerId); - if (errCode != E_OK) { - std::thread timerThread([inAction, inCountDown]() { - // Note: inAction and inCountDown should be captured by value (must not by reference) - std::this_thread::sleep_for(std::chrono::milliseconds(inCountDown)); - inAction(); - }); - timerThread.detach(); + if (errCode == E_OK) { + return; } + std::thread timerThread([inAction, inCountDown]() { + // Note: inAction and inCountDown should be captured by value (must not by reference) + std::this_thread::sleep_for(std::chrono::milliseconds(inCountDown)); + inAction(); + }); + timerThread.detach(); } // This function should be called under protection of entireInfoMutex_ diff --git a/kv_store/frameworks/libs/distributeddb/distributeddb.gni b/kv_store/frameworks/libs/distributeddb/distributeddb.gni index eb9ef3d5..33a4b990 100644 --- a/kv_store/frameworks/libs/distributeddb/distributeddb.gni +++ b/kv_store/frameworks/libs/distributeddb/distributeddb.gni @@ -185,7 +185,9 @@ distributeddb_src = [ "${distributeddb_path}/syncer/src/cloud/cloud_merge_strategy.cpp", "${distributeddb_path}/syncer/src/cloud/cloud_db_proxy.cpp", "${distributeddb_path}/syncer/src/cloud/cloud_syncer.cpp", + "${distributeddb_path}/syncer/src/cloud/cloud_sync_tag_assets.cpp", "${distributeddb_path}/syncer/src/cloud/cloud_sync_utils.cpp", + "${distributeddb_path}/syncer/src/cloud/process_notifier.cpp", "${distributeddb_path}/syncer/src/cloud/strategy_factory.cpp", "${distributeddb_path}/syncer/src/commit_history_sync.cpp", "${distributeddb_path}/syncer/src/communicator_proxy.cpp", diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/include/cloud/icloud_data_translate.h b/kv_store/frameworks/libs/distributeddb/interfaces/include/cloud/icloud_data_translate.h index e0ff7a05..09d75d13 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/include/cloud/icloud_data_translate.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/include/cloud/icloud_data_translate.h @@ -30,7 +30,7 @@ public: virtual std::vector AssetToBlob(const Asset &asset) = 0; virtual std::vector AssetsToBlob(const Assets &assets) = 0; virtual Asset BlobToAsset(const std::vector &blob) = 0; - virtual Assets BlobToAssets(std::vector &blob) = 0; + virtual Assets BlobToAssets(const std::vector &blob) = 0; }; } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/include/store_observer.h b/kv_store/frameworks/libs/distributeddb/interfaces/include/store_observer.h index 42af4362..2d8e5c5a 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/include/store_observer.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/include/store_observer.h @@ -37,7 +37,7 @@ struct ChangedData { std::string tableName; ChangedDataType type; // CLOUD_COOPERATION mode, primaryData store primary keys - // primayData store row id if have no data + // primaryData store row id if have no data std::vector> primaryData[OP_BUTT]; std::vector field; }; diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp index 21a773a8..e1d132a5 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.cpp @@ -18,11 +18,12 @@ #include "cloud/cloud_db_constant.h" #include "db_common.h" #include "db_errno.h" +#include "cloud/cloud_db_constant.h" #include "kv_store_errno.h" #include "log_print.h" #include "param_check_utils.h" -#include "relational_store_instance.h" #include "relational_store_changed_data_impl.h" +#include "relational_store_instance.h" #include "sync_operation.h" namespace DistributedDB { @@ -79,12 +80,12 @@ int32_t RelationalStoreDelegateImpl::GetCloudSyncTaskCount() DBStatus RelationalStoreDelegateImpl::CreateDistributedTableInner(const std::string &tableName, TableSyncType type) { if (!ParamCheckUtils::CheckRelationalTableName(tableName)) { - LOGE("invalid table name."); + LOGE("[RelationalStore Delegate] Invalid table name."); return INVALID_ARGS; } if (!(type == DEVICE_COOPERATION || type == CLOUD_COOPERATION)) { - LOGE("invalid table sync type."); + LOGE("[RelationalStore Delegate] Invalid table sync type."); return INVALID_ARGS; } diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp index 584735a5..ab61b004 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp @@ -23,15 +23,15 @@ #include "relational_store_instance.h" #include "db_common.h" #include "db_dfx_adapter.h" -#include "param_check_utils.h" -#include "log_print.h" #include "db_errno.h" #include "kv_store_errno.h" +#include "log_print.h" +#include "param_check_utils.h" +#include "platform_specific.h" #include "relational_store_changed_data_impl.h" #include "relational_store_delegate_impl.h" #include "runtime_config.h" #include "runtime_context.h" -#include "platform_specific.h" namespace DistributedDB { namespace { @@ -162,7 +162,6 @@ DB_API std::vector RelationalStoreManager::CalcPrimaryKeyHash(const std if (errCode != E_OK) { // never happen LOGE("calc hash fail when there is one primary key errCode = %d", errCode); - return result; } } else { std::vector tempRes; @@ -180,7 +179,6 @@ DB_API std::vector RelationalStoreManager::CalcPrimaryKeyHash(const std errCode = DBCommon::CalcValueHash(tempRes, result); if (errCode != E_OK) { LOGE("calc hash fail when calc the composite primary key errCode = %d", errCode); - return result; } } return result; diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp index 7607b849..d338faf3 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp @@ -30,6 +30,9 @@ namespace { constexpr int E_OK = 0; constexpr int E_ERROR = 1; constexpr int BUSY_TIMEOUT = 2000; // 2s. +const int MAX_BLOB_READ_SIZE = 5 * 1024 * 1024; // 5M limit +const std::string DEVICE_TYPE = "device"; +const std::string SYNC_TABLE_TYPE = "sync_table_type_"; class ValueHashCalc { public: ValueHashCalc() {}; @@ -405,18 +408,101 @@ int GetCurrentMaxTimestamp(sqlite3 *db, Timestamp &maxTimestamp) return E_OK; } +int GetColumnBlobValue(sqlite3_stmt *stmt, int index, std::vector &value) +{ + if (stmt == nullptr) { + return -E_ERROR; + } + + int keySize = sqlite3_column_bytes(stmt, index); + if (keySize < 0) { + value.resize(0); + return E_OK; + } + auto keyRead = static_cast(sqlite3_column_blob(stmt, index)); + if (keySize == 0 || keyRead == nullptr) { + value.resize(0); + } else { + if (keySize > MAX_BLOB_READ_SIZE) { + keySize = MAX_BLOB_READ_SIZE + 1; + } + value.resize(keySize); + value.assign(keyRead, keyRead + keySize); + } + return E_OK; +} + +int GetTableSyncType(sqlite3 *db, const std::string &tableName, std::string &tableType) +{ + const char *selectSql = "SELECT value FROM naturalbase_rdb_aux_metadata WHERE key=?;"; + sqlite3_stmt *statement = nullptr; + int errCode = sqlite3_prepare_v2(db, selectSql, -1, &statement, nullptr); + if (errCode != SQLITE_OK) { + (void)sqlite3_finalize(statement); + return -E_ERROR; + } + + std::string keyStr = SYNC_TABLE_TYPE + tableName; + std::vector key(keyStr.begin(), keyStr.end()); + if (sqlite3_bind_blob(statement, 1, static_cast(key.data()), key.size(), + SQLITE_TRANSIENT) != SQLITE_OK) { + return -E_ERROR; + } + + if (sqlite3_step(statement) == SQLITE_ROW) { + std::vector value; + if (GetColumnBlobValue(statement, 0, value) == E_OK) { + tableType.assign(value.begin(), value.end()); + (void)sqlite3_finalize(statement); + return E_OK; + } else { + (void)sqlite3_finalize(statement); + return -E_ERROR; + } + } else if (sqlite3_step(statement) != SQLITE_DONE) { + (void)sqlite3_finalize(statement); + return -E_ERROR; + } + (void)sqlite3_finalize(statement); + tableType = DEVICE_TYPE; + return E_OK; +} + +void HandleDropCloudSyncTable(sqlite3 *db, const std::string &tableName) +{ + std::string logTblName = "naturalbase_rdb_aux_" + tableName + "_log"; + std::string sql = "UPDATE " + logTblName + " SET data_key=-1, flag=0x03, timestamp=get_raw_sys_time();"; + (void)sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr); + std::string keyStr = SYNC_TABLE_TYPE + tableName; + std::vector key(keyStr.begin(), keyStr.end()); + sql = "delete from naturalbase_rdb_aux_metadata where key = ?;"; + sqlite3_stmt *statement = nullptr; + int errCode = sqlite3_prepare_v2(db, sql.c_str(), -1, &statement, nullptr); + if (errCode != SQLITE_OK) { + (void)sqlite3_finalize(statement); + return; + } + + if (sqlite3_bind_blob(statement, 1, static_cast(key.data()), key.size(), + SQLITE_TRANSIENT) != SQLITE_OK) { + return; + } + (void)sqlite3_step(statement); + (void)sqlite3_finalize(statement); +} + void ClearTheLogAfterDropTable(sqlite3 *db, const char *tableName, const char *schemaName) { if (db == nullptr || tableName == nullptr || schemaName == nullptr) { return; } sqlite3_stmt *stmt = nullptr; - std::string logTblName = "naturalbase_rdb_aux_" + std::string(tableName) + "_log"; + std::string tableStr = std::string(tableName); + std::string logTblName = "naturalbase_rdb_aux_" + tableStr + "_log"; Timestamp dropTimeStamp = TimeHelper::GetTime(0); std::string sql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='" + logTblName + "';"; if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr) != SQLITE_OK) { (void)sqlite3_finalize(stmt); - sqlite3_close(db); return; } @@ -428,13 +514,20 @@ void ClearTheLogAfterDropTable(sqlite3 *db, const char *tableName, const char *s stmt = nullptr; if (isLogTblExists) { - RegisterGetSysTime(db); - RegisterGetLastTime(db); - sql = "UPDATE " + logTblName + " SET flag=0x03, timestamp=get_sys_time(0) " + std::string tableType = DEVICE_TYPE; + if (GetTableSyncType(db, tableStr, tableType) != E_OK) { + return; + } + if (tableType == DEVICE_TYPE) { + RegisterGetSysTime(db); + RegisterGetLastTime(db); + sql = "UPDATE " + logTblName + " SET flag=0x03, timestamp=get_sys_time(0) " "WHERE flag&0x03=0x02 AND timestamp<" + std::to_string(dropTimeStamp); - (void)sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr); + (void)sqlite3_exec(db, sql.c_str(), nullptr, nullptr, nullptr); + } else { + HandleDropCloudSyncTable(db, tableStr); + } } - return; } void PostHandle(sqlite3 *db) diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h index 10502737..e50d00e7 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h @@ -160,9 +160,11 @@ public: int CleanCloudData(ClearMode mode, const std::vector &tableNameList, const RelationalSchemaObject &localSchema, std::vector &assets) override; - int FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isFullReplace) override; + int FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isDownloadSuccess) override; - int FillCloudGidAndAsset(const OpType &opType, const CloudSyncData &data) override; + int SetLogTriggerStatus(bool status) override; + + int FillCloudGidAndAsset(OpType opType, const CloudSyncData &data) override; void SetSyncAbleEngine(std::shared_ptr syncAbleEngine); @@ -170,6 +172,8 @@ public: void EraseDataChangeCallback(uint64_t connectionId); + void ReleaseContinueToken(ContinueToken &continueStmtToken) const override; + private: SQLiteSingleVerRelationalStorageExecutor *GetHandle(bool isWrite, int &errCode, OperatePerm perm = OperatePerm::NORMAL_PERM) const; diff --git a/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h b/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h index 1e3cc8ef..48ae1837 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h +++ b/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h @@ -32,23 +32,23 @@ public: explicit CloudMetaData(ICloudSyncStorageInterface *store); ~CloudMetaData() = default; - int GetLocalWaterMark(TableName tableName, LocalWaterMark &localMark); - int GetCloudWaterMark(TableName tableName, CloudWaterMark &cloudMark); + int GetLocalWaterMark(const TableName &tableName, Timestamp &localMark); + int GetCloudWaterMark(const TableName &tableName, std::string &cloudMark); - int SetLocalWaterMark(TableName tableName, LocalWaterMark localMark); - int SetCloudWaterMark(TableName tableName, CloudWaterMark &cloudMark); + int SetLocalWaterMark(const TableName &tableName, Timestamp localMark); + int SetCloudWaterMark(const TableName &tableName, std::string &cloudMark); private: typedef struct CloudMetaValue { - LocalWaterMark localMark; - CloudWaterMark cloudMark; + Timestamp localMark; + std::string cloudMark; } CloudMetaValue; int ReadMarkFromMeta(const TableName &tableName); - int WriteMarkToMeta(TableName &tableName, LocalWaterMark localmark, CloudWaterMark &cloudMark); - int SerializeMark(TableName tableName, LocalWaterMark localMark, CloudWaterMark &cloudMark, Value &blobMeta); + int WriteMarkToMeta(const TableName &tableName, Timestamp localmark, std::string &cloudMark); + int SerializeMark(Timestamp localMark, std::string &cloudMark, Value &blobMeta); int DeserializeMark(Value &blobMark, CloudMetaValue &cloudMetaValue); - Key PrefixTableName(const TableName &tableName); + Key GetPrefixTableName(const TableName &tableName); mutable std::mutex cloudMetaMutex_; std::unordered_map cloudMetaVals_; diff --git a/kv_store/frameworks/libs/distributeddb/storage/include/icloud_sync_storage_interface.h b/kv_store/frameworks/libs/distributeddb/storage/include/icloud_sync_storage_interface.h index 4754089a..efb597d6 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/include/icloud_sync_storage_interface.h +++ b/kv_store/frameworks/libs/distributeddb/storage/include/icloud_sync_storage_interface.h @@ -87,9 +87,11 @@ public: virtual void TriggerObserverAction(const std::string &deviceName, ChangedData &&changedData, bool isChangedData) = 0; - virtual int FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isFullReplace) = 0; + virtual int FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isDownloadSuccess) = 0; - virtual int FillCloudGidAndAsset(const OpType &opType, const CloudSyncData &data) = 0; + virtual int SetLogTriggerStatus(bool status) = 0; + + virtual int FillCloudGidAndAsset(OpType opType, const CloudSyncData &data) = 0; virtual std::string GetIdentify() const = 0; }; diff --git a/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h b/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h index cf03244a..4027fee8 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h +++ b/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h @@ -37,13 +37,13 @@ public: int Close(); - int GetLocalWaterMark(const std::string &tableName, LocalWaterMark &localMark); + int GetLocalWaterMark(const std::string &tableName, Timestamp &localMark); - int PutLocalWaterMark(const std::string &tableName, LocalWaterMark &localMark); + int PutLocalWaterMark(const std::string &tableName, Timestamp &localMark); - int GetCloudWaterMark(const std::string &tableName, CloudWaterMark &cloudMark); + int GetCloudWaterMark(const std::string &tableName, std::string &cloudMark); - int SetCloudWaterMark(const std::string &tableName, CloudWaterMark &cloudMark); + int SetCloudWaterMark(const std::string &tableName, std::string &cloudMark); int StartTransaction(TransactType type = TransactType::DEFERRED); @@ -51,7 +51,7 @@ public: int Rollback(); - int GetUploadCount(const std::string &tableName, const LocalWaterMark ×tamp, const bool isCloudForcePush, + int GetUploadCount(const std::string &tableName, const Timestamp ×tamp, const bool isCloudForcePush, int64_t &count); int FillCloudGid(const CloudSyncData &data); @@ -80,14 +80,18 @@ public: int ReleaseContinueToken(ContinueToken &continueStmtToken); - int FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isFullReplace); + int FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isDownloadSuccess); - int FillCloudGidAndAsset(const OpType &opType, const CloudSyncData &data); + int SetLogTriggerStatus(bool status); + + int FillCloudGidAndAsset(OpType opType, const CloudSyncData &data); std::string GetIdentify() const; protected: void Init(); + + static Timestamp EraseNanoTime(Timestamp localTime); private: ICloudSyncStorageInterface *store_; mutable std::shared_mutex storeMutex_; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp index e7db3f79..decfb300 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp @@ -25,14 +25,14 @@ CloudMetaData::CloudMetaData(ICloudSyncStorageInterface *store) { } -Key CloudMetaData::PrefixTableName(const TableName &tableName) +Key CloudMetaData::GetPrefixTableName(const TableName &tableName) { TableName newName = CloudDbConstant::CLOUD_META_TABLE_PREFIX + tableName; Key prefixedTableName(newName.begin(), newName.end()); return prefixedTableName; } -int CloudMetaData::GetLocalWaterMark(TableName tableName, LocalWaterMark &localMark) +int CloudMetaData::GetLocalWaterMark(const TableName &tableName, Timestamp &localMark) { std::lock_guard lock(cloudMetaMutex_); if (cloudMetaVals_.count(tableName) == 0) { @@ -45,7 +45,7 @@ int CloudMetaData::GetLocalWaterMark(TableName tableName, LocalWaterMark &localM return E_OK; } -int CloudMetaData::GetCloudWaterMark(TableName tableName, CloudWaterMark &cloudMark) +int CloudMetaData::GetCloudWaterMark(const TableName &tableName, std::string &cloudMark) { std::lock_guard lock(cloudMetaMutex_); if (cloudMetaVals_.count(tableName) == 0) { @@ -59,10 +59,10 @@ int CloudMetaData::GetCloudWaterMark(TableName tableName, CloudWaterMark &cloudM return E_OK; } -int CloudMetaData::SetLocalWaterMark(TableName tableName, LocalWaterMark localMark) +int CloudMetaData::SetLocalWaterMark(const TableName &tableName, Timestamp localMark) { std::lock_guard lock(cloudMetaMutex_); - CloudWaterMark cloudMark = ""; + std::string cloudMark = ""; auto iter = cloudMetaVals_.find(tableName); if (iter != cloudMetaVals_.end()) { cloudMark = iter->second.cloudMark; @@ -80,10 +80,10 @@ int CloudMetaData::SetLocalWaterMark(TableName tableName, LocalWaterMark localMa return E_OK; } -int CloudMetaData::SetCloudWaterMark(TableName tableName, CloudWaterMark &cloudMark) +int CloudMetaData::SetCloudWaterMark(const TableName &tableName, std::string &cloudMark) { std::lock_guard lock(cloudMetaMutex_); - LocalWaterMark localMark = 0; + Timestamp localMark = 0; auto iter = cloudMetaVals_.find(tableName); if (iter != cloudMetaVals_.end()) { localMark = iter->second.localMark; @@ -108,7 +108,7 @@ int CloudMetaData::ReadMarkFromMeta(const TableName &tableName) return -E_INVALID_DB; } Value blobMetaVal; - int ret = store_->GetMetaData(PrefixTableName(tableName), blobMetaVal); + int ret = store_->GetMetaData(GetPrefixTableName(tableName), blobMetaVal); if (ret != -E_NOT_FOUND && ret != E_OK) { return ret; } @@ -121,21 +121,20 @@ int CloudMetaData::ReadMarkFromMeta(const TableName &tableName) return E_OK; } -int CloudMetaData::WriteMarkToMeta(TableName &tableName, LocalWaterMark localmark, CloudWaterMark &cloudMark) +int CloudMetaData::WriteMarkToMeta(const TableName &tableName, Timestamp localmark, std::string &cloudMark) { Value blobMetaVal; - int ret = SerializeMark(tableName, localmark, cloudMark, blobMetaVal); + int ret = SerializeMark(localmark, cloudMark, blobMetaVal); if (ret != E_OK) { return ret; } if (store_ == nullptr) { return -E_INVALID_DB; } - return store_->PutMetaData(PrefixTableName(tableName), blobMetaVal); + return store_->PutMetaData(GetPrefixTableName(tableName), blobMetaVal); } -int CloudMetaData::SerializeMark( - TableName tableName, LocalWaterMark localMark, CloudWaterMark &cloudMark, Value &blobMeta) +int CloudMetaData::SerializeMark(Timestamp localMark, std::string &cloudMark, Value &blobMeta) { uint64_t length = Parcel::GetUInt64Len() + Parcel::GetStringLen(cloudMark); blobMeta.resize(length); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp index ff291ec3..7f030927 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp @@ -12,12 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#include "cloud/cloud_storage_utils.h" #include #include "cloud/cloud_db_types.h" #include "db_common.h" #include "runtime_context.h" -#include "cloud/cloud_storage_utils.h" namespace DistributedDB { int CloudStorageUtils::BindInt64(int index, const VBucket &vBucket, const Field &field, @@ -551,18 +552,12 @@ void CloudStorageUtils::FillAssetFromVBucketFinish(VBucket &vBucket, std::functi bool CloudStorageUtils::IsAsset(const Type &type) { - if (type.index() == TYPE_INDEX) { - return true; - } - return false; + return type.index() == TYPE_INDEX; } bool CloudStorageUtils::IsAssets(const Type &type) { - if (type.index() == TYPE_INDEX) { - return true; - } - return false; + return type.index() == TYPE_INDEX; } int CloudStorageUtils::CalculateHashKeyForOneField(const Field &field, const VBucket &vBucket, bool allowEmpty, @@ -572,13 +567,13 @@ int CloudStorageUtils::CalculateHashKeyForOneField(const Field &field, const VBu return E_OK; // if vBucket from cloud doesn't contain primary key and allowEmpty, no need to calculate hash } static std::map &)>> toVecFunc = { - {TYPE_INDEX, &CloudStorageUtils::Int64ToVector}, - {TYPE_INDEX, &CloudStorageUtils::BoolToVector}, - {TYPE_INDEX, &CloudStorageUtils::DoubleToVector}, - {TYPE_INDEX, &CloudStorageUtils::TextToVector}, - {TYPE_INDEX, &CloudStorageUtils::BlobToVector}, - {TYPE_INDEX, &CloudStorageUtils::BlobToVector}, - {TYPE_INDEX, &CloudStorageUtils::BlobToVector}, + { TYPE_INDEX, &CloudStorageUtils::Int64ToVector }, + { TYPE_INDEX, &CloudStorageUtils::BoolToVector }, + { TYPE_INDEX, &CloudStorageUtils::DoubleToVector }, + { TYPE_INDEX, &CloudStorageUtils::TextToVector }, + { TYPE_INDEX, &CloudStorageUtils::BlobToVector }, + { TYPE_INDEX, &CloudStorageUtils::BlobToVector }, + { TYPE_INDEX, &CloudStorageUtils::BlobToVector }, }; auto it = toVecFunc.find(field.type); if (it == toVecFunc.end()) { diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp index c6be15ec..1197b1ab 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp @@ -106,8 +106,8 @@ bool SchemaMgr::CompareType(const FieldInfo &localField, const Field &cloudField switch (cloudField.type) { case TYPE_INDEX: case TYPE_INDEX: - // BOOL type should be stored as NUMERIC type, - // but we regard it as NULL type for historic reason + // BOOL type should be stored as NUMERIC type, + // but we regard it as NULL type for historic reason return localType == StorageType::STORAGE_TYPE_NULL; case TYPE_INDEX: return localType == StorageType::STORAGE_TYPE_INTEGER; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/operation/local_database_oper.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/operation/local_database_oper.cpp index 2f2426ab..373b26e6 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/operation/local_database_oper.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/operation/local_database_oper.cpp @@ -213,4 +213,4 @@ int LocalDatabaseOper::ImportPostHandle() const return localKvDb_->InitDatabaseContext(localKvDb_->GetDbProperties()); } } // namespace DistributedDB -#endif +#endif // OMIT_MULTI_VER diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp index 68060b3b..99cdcd47 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp @@ -17,6 +17,7 @@ #include +#include "cloud/cloud_db_constant.h" #include "data_compression.h" #include "db_common.h" #include "db_dfx_adapter.h" @@ -26,7 +27,6 @@ #include "relational_sync_data_inserter.h" #include "res_finalizer.h" #include "runtime_context.h" -#include "cloud/cloud_db_constant.h" namespace DistributedDB { namespace { @@ -889,6 +889,7 @@ void RelationalSyncAbleStorage::ReleaseRemoteQueryContinueToken(ContinueToken &t int RelationalSyncAbleStorage::StartTransaction(TransactType type) { + CHECK_STORAGE_ENGINE; std::unique_lock lock(transactionMutex_); if (transactionHandle_ != nullptr) { LOGD("Transaction started already."); @@ -961,7 +962,7 @@ int RelationalSyncAbleStorage::FillCloudGid(const CloudSyncData &data) } int errCode = E_OK; auto writeHandle = static_cast( - storageEngine_->FindExecutor(true, OperatePerm::NORMAL_PERM, errCode, 0)); + storageEngine_->FindExecutor(true, OperatePerm::NORMAL_PERM, errCode)); if (writeHandle == nullptr) { return errCode; } @@ -1112,50 +1113,51 @@ int RelationalSyncAbleStorage::GetCloudTableSchema(const TableName &tableName, T } int RelationalSyncAbleStorage::FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, - bool isFullReplace) + bool isDownloadSuccess) { if (storageEngine_ == nullptr) { return -E_INVALID_DB; } - int errCode = E_OK; - auto writeHandle = static_cast( - storageEngine_->FindExecutor(true, OperatePerm::NORMAL_PERM, errCode, 0)); - if (writeHandle == nullptr) { - return errCode; - } - errCode = writeHandle->StartTransaction(TransactType::IMMEDIATE); - if (errCode != E_OK) { - ReleaseHandle(writeHandle); - return errCode; + if (transactionHandle_ == nullptr) { + LOGE("the transaction has not been started when fill asset for download."); + return -E_INVALID_DB; } TableSchema tableSchema; - errCode = GetCloudTableSchema(tableName, tableSchema); + int errCode = GetCloudTableSchema(tableName, tableSchema); if (errCode != E_OK) { LOGE("Get cloud schema failed when fill cloud asset, %d", errCode); return errCode; } - errCode = writeHandle->FillCloudAssetForDownload(tableSchema, asset, isFullReplace); + errCode = transactionHandle_->FillCloudAssetForDownload(tableSchema, asset, isDownloadSuccess); if (errCode != E_OK) { - writeHandle->Rollback(); - ReleaseHandle(writeHandle); - return errCode; + LOGE("fill cloud asset for download failed.%d", errCode); } - errCode = writeHandle->Commit(); - ReleaseHandle(writeHandle); return errCode; } -int RelationalSyncAbleStorage::FillCloudGidAndAsset(const OpType &opType, const CloudSyncData &data) +int RelationalSyncAbleStorage::SetLogTriggerStatus(bool status) { - if (storageEngine_ == nullptr) { - return -E_INVALID_DB; + int errCode = E_OK; + auto *handle = GetHandleExpectTransaction(false, errCode); + if (handle == nullptr) { + return errCode; } + errCode = handle->SetLogTriggerStatus(status); + if (transactionHandle_ == nullptr) { + ReleaseHandle(handle); + } + return errCode; +} + +int RelationalSyncAbleStorage::FillCloudGidAndAsset(const OpType opType, const CloudSyncData &data) +{ + CHECK_STORAGE_ENGINE; if (opType == OpType::UPDATE && data.updData.assets.empty()) { return E_OK; } int errCode = E_OK; auto writeHandle = static_cast( - storageEngine_->FindExecutor(true, OperatePerm::NORMAL_PERM, errCode, 0)); + storageEngine_->FindExecutor(true, OperatePerm::NORMAL_PERM, errCode)); if (writeHandle == nullptr) { return errCode; } @@ -1202,6 +1204,7 @@ std::string RelationalSyncAbleStorage::GetIdentify() const } return storageEngine_->GetIdentifier(); } + void RelationalSyncAbleStorage::EraseDataChangeCallback(uint64_t connectionId) { std::lock_guard lock(dataChangeDeviceMutex_); @@ -1210,5 +1213,16 @@ void RelationalSyncAbleStorage::EraseDataChangeCallback(uint64_t connectionId) dataChangeCallbackMap_.erase(it); } } + +void RelationalSyncAbleStorage::ReleaseContinueToken(ContinueToken &continueStmtToken) const +{ + auto token = static_cast(continueStmtToken); + if (token == nullptr || !(token->CheckValid())) { + LOGW("[RelationalSyncAbleStorage][ReleaseContinueToken] Input is not a continue token."); + return; + } + delete token; + continueStmtToken = nullptr; +} } #endif \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp index 159a5bc8..10085da3 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp @@ -45,7 +45,10 @@ void CloudSyncLogTableManager::GetIndexSql(const TableInfo &table, std::vector DBConstant::LOG_TABLE_VERSION_2; +} + int SqliteRelationalDatabaseUpgrader::UpgradeLogTable(const std::string &logTableVersion) { - if (IsNewestVersion(logTableVersion)) { + if (NoNeedUpdateLogTable(logTableVersion)) { LOGD("[Relational][Upgrade] No need upgrade log table."); return E_OK; } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp index 4540da73..9006091c 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp @@ -447,6 +447,7 @@ int SQLiteRelationalStore::CreateDistributedTable(const std::string &tableName, } return errCode; } + int32_t SQLiteRelationalStore::GetCloudSyncTaskCount() { if (cloudSyncer_ == nullptr) { @@ -455,6 +456,7 @@ int32_t SQLiteRelationalStore::GetCloudSyncTaskCount() } return cloudSyncer_->GetCloudSyncTaskCount(); } + int SQLiteRelationalStore::CleanCloudData(ClearMode mode) { auto tableMode = static_cast(sqliteStorageEngine_->GetProperties().GetIntProp( @@ -549,8 +551,8 @@ int SQLiteRelationalStore::RemoveDeviceData(const std::string &device, const std TableInfoMap tables = sqliteStorageEngine_->GetSchema().GetTables(); // TableInfoMap auto iter = tables.find(tableName); if (tables.empty() || (!tableName.empty() && iter == tables.end())) { - LOGI("Remove device data with table name which is not a distributed table or no distributed table found."); - return E_OK; + LOGE("Remove device data with table name which is not a distributed table or no distributed table found."); + return -E_DISTRIBUTED_SCHEMA_NOT_FOUND; } // cloud mode is not permit if (iter->second.GetTableSyncType() == CLOUD_COOPERATION) { @@ -906,7 +908,8 @@ int SQLiteRelationalStore::SetCloudDB(const std::shared_ptr &cloudDb) LOGE("[RelationalStore][SetCloudDB] cloudSyncer was not initialized"); return -E_INVALID_DB; } - return cloudSyncer_->SetCloudDB(cloudDb); + cloudSyncer_->SetCloudDB(cloudDb); + return E_OK; } int SQLiteRelationalStore::SetCloudDbSchema(const DataBaseSchema &schema) @@ -924,7 +927,8 @@ int SQLiteRelationalStore::SetIAssetLoader(const std::shared_ptr & LOGE("[RelationalStore][SetIAssetLoader] cloudSyncer was not initialized"); return -E_INVALID_DB; } - return cloudSyncer_->SetIAssetLoader(loader); + cloudSyncer_->SetIAssetLoader(loader); + return E_OK; } int SQLiteRelationalStore::ChkSchema(const TableName &tableName) diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp index d41fc5b9..78d3bfd1 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store_connection.cpp @@ -300,11 +300,7 @@ int SQLiteRelationalStoreConnection::SetCloudDB(const std::shared_ptr return -E_INVALID_CONNECTION; } - int ret = store->SetCloudDB(cloudDb); - if (ret != E_OK) { - LOGE("[RelationalConnection] SetCloudDB failed. %d", ret); - } - return ret; + return store->SetCloudDB(cloudDb); } int SQLiteRelationalStoreConnection::SetCloudDbSchema(const DataBaseSchema &schema) diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp index 08ece26e..341f258e 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp @@ -67,6 +67,7 @@ int SQLiteSingleRelationalStorageEngine::RegisterFunction(sqlite3 *db) const errCode = SQLiteUtils::RegisterGetSysTime(db); if (errCode != E_OK) { LOGE("[engine] register get sys time failed!"); + return errCode; } errCode = SQLiteUtils::RegisterGetRawSysTime(db); @@ -74,7 +75,7 @@ int SQLiteSingleRelationalStorageEngine::RegisterFunction(sqlite3 *db) const LOGE("[engine] register get raw sys time failed!"); } - return E_OK; + return errCode; } int SQLiteSingleRelationalStorageEngine::CreateNewExecutor(bool isWrite, StorageExecutor *&handle) @@ -133,6 +134,10 @@ RelationalSchemaObject SQLiteSingleRelationalStorageEngine::GetSchema() const } namespace { +const std::string DEVICE_TYPE = "device"; +const std::string CLOUD_TYPE = "cloud"; +const std::string SYNC_TABLE_TYPE = "sync_table_type_"; + int SaveSchemaToMetaTable(SQLiteSingleVerRelationalStorageExecutor *handle, const RelationalSchemaObject &schema) { const Key schemaKey(DBConstant::RELATIONAL_SCHEMA_KEY.begin(), DBConstant::RELATIONAL_SCHEMA_KEY.end()); @@ -144,6 +149,20 @@ int SaveSchemaToMetaTable(SQLiteSingleVerRelationalStorageExecutor *handle, cons } return errCode; } + +int SaveSyncTableTypeToMeta(SQLiteSingleVerRelationalStorageExecutor *handle, const std::string &tableName, + TableSyncType syncType) +{ + Key key; + DBCommon::StringToVector(SYNC_TABLE_TYPE + tableName, key); + Value value; + DBCommon::StringToVector(syncType == DEVICE_COOPERATION ? DEVICE_TYPE : CLOUD_TYPE, value); + int errCode = handle->PutKvData(key, value); + if (errCode != E_OK) { + LOGE("Save sync table type to meta table failed. %d", errCode); + } + return errCode; +} } int SQLiteSingleRelationalStorageEngine::CreateDistributedTable(const std::string &tableName, @@ -213,6 +232,12 @@ int SQLiteSingleRelationalStorageEngine::CreateDistributedTable(const std::strin return errCode; } + errCode = SaveSyncTableTypeToMeta(handle, tableName, tableSyncType); + if (errCode != E_OK) { + (void)handle->Rollback(); + return errCode; + } + errCode = handle->Commit(); if (errCode == E_OK) { schema_ = schema; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp index 37874142..fe7ee9f5 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp @@ -162,6 +162,7 @@ namespace { SQLiteSingleVerNaturalStore::SQLiteSingleVerNaturalStore() : currentMaxTimestamp_(0), + migrateCount_(0), storageEngine_(nullptr), notificationEventsRegistered_(false), notificationConflictEventsRegistered_(false), diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.h b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.h index 864cf0ed..5b4223f4 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.h +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.h @@ -295,7 +295,7 @@ private: mutable std::shared_mutex engineMutex_; mutable std::mutex migrateMutex_; mutable std::condition_variable migrateCv_; - mutable int migrateCount_ = 0; + mutable int migrateCount_; SQLiteSingleVerStorageEngine *storageEngine_; bool notificationEventsRegistered_; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp index 561a630d..3ae06554 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp @@ -43,6 +43,11 @@ static constexpr const char* SET_FLAG_LOCAL = "FLAG | 0x02"; // set 1th bit o static constexpr const int SET_FLAG_ZERO_MASK = 0x03; // clear 2th bit of flag static constexpr const int SET_FLAG_ONE_MASK = 0x04; // set 2th bit of flag static constexpr const int SET_CLOUD_FLAG = 0x05; // set 1th bit of flag to 0 +static constexpr const int DATA_KEY_INDEX = 0; +static constexpr const int TIMESTAMP_INDEX = 3; +static constexpr const int W_TIMESTAMP_INDEX = 4; +static constexpr const int FLAG_INDEX = 5; +static constexpr const int CLOUD_GID_INDEX = 7; int PermitSelect(void *a, int b, const char *c, const char *d, const char *e, const char *f) { @@ -499,13 +504,13 @@ namespace { void GetCloudLog(sqlite3_stmt *logStatement, VBucket &logInfo, uint32_t &totalSize) { logInfo.insert_or_assign(CloudDbConstant::MODIFY_FIELD, - static_cast(sqlite3_column_int64(logStatement, 3))); // 3 means timestamp index + static_cast(sqlite3_column_int64(logStatement, TIMESTAMP_INDEX))); logInfo.insert_or_assign(CloudDbConstant::CREATE_FIELD, - static_cast(sqlite3_column_int64(logStatement, 4))); // 4 means w_timestamp index + static_cast(sqlite3_column_int64(logStatement, W_TIMESTAMP_INDEX))); totalSize += sizeof(int64_t) + sizeof(int64_t); - if (sqlite3_column_text(logStatement, 7) != nullptr) { // 7 means cloudGid index + if (sqlite3_column_text(logStatement, CLOUD_GID_INDEX) != nullptr) { std::string cloudGid = reinterpret_cast( - sqlite3_column_text(logStatement, 7)); // 7 means cloudGid index + sqlite3_column_text(logStatement, CLOUD_GID_INDEX)); if (!cloudGid.empty()) { logInfo.insert_or_assign(CloudDbConstant::GID_FIELD, cloudGid); totalSize += cloudGid.size(); @@ -516,11 +521,11 @@ void GetCloudLog(sqlite3_stmt *logStatement, VBucket &logInfo, uint32_t &totalSi void GetCloudExtraLog(sqlite3_stmt *logStatement, VBucket &flags) { flags.insert_or_assign(ROWID, - static_cast(sqlite3_column_int64(logStatement, 0))); // 0 means data_key index + static_cast(sqlite3_column_int64(logStatement, DATA_KEY_INDEX))); flags.insert_or_assign(TIMESTAMP, - static_cast(sqlite3_column_int64(logStatement, 3))); // 3 means timestamp index + static_cast(sqlite3_column_int64(logStatement, TIMESTAMP_INDEX))); flags.insert_or_assign(FLAG, - static_cast(sqlite3_column_int64(logStatement, 5))); // 5 means flag index + static_cast(sqlite3_column_int64(logStatement, FLAG_INDEX))); } int IdentifyCloudType(CloudSyncData &cloudSyncData, VBucket &data, VBucket &log, VBucket &flags) @@ -535,25 +540,29 @@ int IdentifyCloudType(CloudSyncData &cloudSyncData, VBucket &data, VBucket &log, cloudSyncData.delData.record.push_back(data); cloudSyncData.delData.extend.push_back(log); } else if (log.find(CloudDbConstant::GID_FIELD) == log.end()) { - if (!data.empty()) { - cloudSyncData.insData.record.push_back(data); - cloudSyncData.insData.rowid.push_back(*rowid); - VBucket asset; - CloudStorageUtils::ObtainAssetFromVBucket(data, asset); - cloudSyncData.insData.timestamp.push_back(*timeStamp); - cloudSyncData.insData.assets.push_back(asset); - } + if (data.empty()) { + LOGE("The cloud data to be inserted is empty."); + return -E_INVALID_DATA; + } + cloudSyncData.insData.record.push_back(data); + cloudSyncData.insData.rowid.push_back(*rowid); + VBucket asset; + CloudStorageUtils::ObtainAssetFromVBucket(data, asset); + cloudSyncData.insData.timestamp.push_back(*timeStamp); + cloudSyncData.insData.assets.push_back(asset); cloudSyncData.insData.extend.push_back(log); } else { - if (!data.empty()) { - cloudSyncData.updData.record.push_back(data); - VBucket asset; - CloudStorageUtils::ObtainAssetFromVBucket(data, asset); - if (!asset.empty()) { - cloudSyncData.updData.rowid.push_back(*rowid); - cloudSyncData.updData.timestamp.push_back(*timeStamp); - cloudSyncData.updData.assets.push_back(asset); - } + if (data.empty()) { + LOGE("The cloud data to be updated is empty."); + return -E_INVALID_DATA; + } + cloudSyncData.updData.record.push_back(data); + VBucket asset; + CloudStorageUtils::ObtainAssetFromVBucket(data, asset); + if (!asset.empty()) { + cloudSyncData.updData.rowid.push_back(*rowid); + cloudSyncData.updData.timestamp.push_back(*timeStamp); + cloudSyncData.updData.assets.push_back(asset); } cloudSyncData.updData.extend.push_back(log); } @@ -1028,6 +1037,20 @@ int StepNext(bool isMemDB, sqlite3_stmt *stmt, Timestamp ×tamp) return errCode; } +int StepNext(bool isMemDB, sqlite3_stmt *stmt) +{ + if (stmt == nullptr) { + return -E_INVALID_ARGS; + } + int errCode = SQLiteUtils::StepWithRetry(stmt, isMemDB); + if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { + errCode = -E_FINISHED; + } else if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) { + errCode = E_OK; + } + return errCode; +} + int AppendData(const DataSizeSpecInfo &sizeInfo, size_t appendLength, size_t &overLongSize, size_t &dataTotalSize, std::vector &dataItems, DataItem &&item) { @@ -1485,8 +1508,7 @@ int SQLiteSingleVerRelationalStorageExecutor::GetUploadCount(const std::string & LOGE("Failed to get the count to be uploaded. %d", errCode); } SQLiteUtils::ResetStatement(stmt, true, errCode); - LOGW("upload count is %d, isCloudForcePush is %d", count, isCloudForcePush); - + LOGD("upload count is %d, isCloudForcePush is %d", count, isCloudForcePush); return errCode; } @@ -1545,7 +1567,6 @@ int SQLiteSingleVerRelationalStorageExecutor::GetSyncCloudData(CloudSyncData &cl const uint32_t &maxSize, SQLiteSingleVerRelationalContinueToken &token) { token.GetCloudTableSchema(tableSchema_); - baseTblName_ = tableSchema_.name; sqlite3_stmt *queryStmt = nullptr; bool isStepNext = false; int errCode = token.GetCloudStatement(dbHandle_, cloudDataResult.isCloudForcePushStrategy, queryStmt, isStepNext); @@ -1553,19 +1574,21 @@ int SQLiteSingleVerRelationalStorageExecutor::GetSyncCloudData(CloudSyncData &cl (void)token.ReleaseCloudStatement(); return errCode; } - Timestamp queryTime = 0; uint32_t totalSize = 0; uint32_t stepNum = 0; do { if (isStepNext) { - errCode = StepNext(isMemDb_, queryStmt, queryTime); - if (errCode != E_OK || queryTime == INT64_MAX) { + errCode = StepNext(isMemDb_, queryStmt); + if (errCode != E_OK) { + errCode = (errCode == -E_FINISHED ? E_OK : errCode); break; } } isStepNext = true; errCode = GetCloudDataForSync(queryStmt, cloudDataResult, stepNum++, totalSize, maxSize); } while (errCode == E_OK); + LOGD("Get cloud sync data, insData:%u, upData:%u, delLog:%u", cloudDataResult.insData.record.size(), + cloudDataResult.updData.record.size(), cloudDataResult.delData.extend.size()); if (errCode != -E_UNFINISHED) { (void)token.ReleaseCloudStatement(); } @@ -2077,8 +2100,8 @@ int SQLiteSingleVerRelationalStorageExecutor::GetCloudAssetsOnTable(const std::s int ret = E_OK; sqlite3_stmt *selectStmt = nullptr; for (const auto &rowId : dataKeys) { - std::string queryAssetsSql = "SELECT " + fieldName + " FROM " + tableName + - " WHERE " + ROWID + " = " + std::to_string(rowId) + ";"; + std::string queryAssetsSql = "SELECT " + fieldName + " FROM '" + tableName + + "' WHERE " + ROWID + " = " + std::to_string(rowId) + ";"; errCode = SQLiteUtils::GetStatement(dbHandle_, queryAssetsSql, selectStmt); if (errCode != E_OK) { LOGE("Get select assets statement failed, %d", errCode); @@ -2145,7 +2168,7 @@ int SQLiteSingleVerRelationalStorageExecutor::PutCloudSyncData(const std::string return errCode; } - std::map statisticMap; + std::map statisticMap = {}; errCode = ExecutePutCloudData(tableName, tableSchema, downloadData, statisticMap); int ret = SetLogTriggerStatus(true); if (ret != E_OK) { @@ -2393,6 +2416,14 @@ int SQLiteSingleVerRelationalStorageExecutor::GetUpdateSqlForCloudSync(const Tab return E_OK; } +static bool IsGidValid(const std::string &gidStr) +{ + if (!gidStr.empty()) { + return gidStr.find("'") == std::string::npos; + } + return true; +} + int SQLiteSingleVerRelationalStorageExecutor::GetUpdateDataTableStatement(const VBucket &vBucket, const TableSchema &tableSchema, sqlite3_stmt *&updateStmt) { @@ -2402,7 +2433,7 @@ int SQLiteSingleVerRelationalStorageExecutor::GetUpdateDataTableStatement(const LOGE("Get gid from cloud data fail when construct update data sql, errCode = %d", errCode); return errCode; } - if (!gidStr.empty() && gidStr.find("'") != std::string::npos) { + if (!IsGidValid(gidStr)) { LOGE("invalid char in cloud gid"); return -E_CLOUD_ERROR; } @@ -2616,7 +2647,7 @@ int SQLiteSingleVerRelationalStorageExecutor::GetDeleteStatementForCloudSync(con deleteSql += GetWhereConditionForDataTable(gidStr, pkSet, tableSchema.name, queryByPk); errCode = SQLiteUtils::GetStatement(dbHandle_, deleteSql, deleteStmt); if (errCode != E_OK) { - LOGE("Get delete statement failed when delete data, %d, deleteSql = %s", errCode, deleteSql.c_str()); + LOGE("Get delete statement failed when delete data, %d", errCode); return errCode; } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.h b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.h index 5f26987b..9498299b 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.h +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.h @@ -105,12 +105,14 @@ public: int PutCloudSyncData(const std::string &tableName, const TableSchema &tableSchema, DownloadData &downloadData); - int FillCloudAssetForDownload(const TableSchema &tableSchema, VBucket &vBucket, bool isFullReplace); + int FillCloudAssetForDownload(const TableSchema &tableSchema, VBucket &vBucket, bool isDownloadSuccess); int DoCleanInner(ClearMode mode, const std::vector &tableNameList, const RelationalSchemaObject &localSchema, std::vector &assets); int FillCloudAssetForUpload(const std::string &tableName, const CloudSyncBatch &data); + int SetLogTriggerStatus(bool status); + private: int DoCleanLogs(const std::vector &tableNameList); @@ -159,8 +161,6 @@ private: Timestamp &queryTime); int GetMissQueryDataAndStepNext(sqlite3_stmt *fullStmt, DataItem &item, Timestamp &missQueryTime); - int SetLogTriggerStatus(bool status); - void SetTableInfo(const TableInfo &tableInfo); // When put or get sync data, must call the func first. int GeneLogInfoForExistedData(sqlite3 *db, const std::string &tableName, const TableInfo &table, @@ -188,8 +188,6 @@ private: int GetQueryInfoSql(const std::string &tableName, const VBucket &vBucket, std::set &pkSet, std::vector &assetFields, std::string &querySql); - int GetQueryLogRowid(const std::string &tableName, const VBucket &vBucket, int64_t &rowId); - int GetFillDownloadAssetStatement(const std::string &tableName, const VBucket &vBucket, const std::vector &fields, sqlite3_stmt *&statement); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_extend_executor.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_extend_executor.cpp index 1fdc6414..92d592b0 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_extend_executor.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_extend_executor.cpp @@ -20,6 +20,9 @@ #include "db_common.h" namespace DistributedDB { +static constexpr const int ROW_ID_INDEX = 1; +static constexpr const int TIMESTAMP_INDEX = 2; + int SQLiteSingleVerRelationalStorageExecutor::GetQueryInfoSql(const std::string &tableName, const VBucket &vBucket, std::set &pkSet, std::vector &assetFields, std::string &querySql) { @@ -55,42 +58,6 @@ int SQLiteSingleVerRelationalStorageExecutor::GetQueryInfoSql(const std::string return E_OK; } -int SQLiteSingleVerRelationalStorageExecutor::GetQueryLogRowid(const std::string &tableName, - const VBucket &vBucket, int64_t &rowId) -{ - std::string cloudGid; - int errCode = CloudStorageUtils::GetValueFromVBucket(CloudDbConstant::GID_FIELD, vBucket, cloudGid); - if (errCode != E_OK) { - LOGE("Miss gid when fill Asset"); - return errCode; - } - std::string sql = "SELECT data_key FROM " + DBCommon::GetLogTableName(tableName) + " where cloud_gid = ?;"; - sqlite3_stmt *stmt = nullptr; - errCode = SQLiteUtils::GetStatement(dbHandle_, sql, stmt); - if (errCode != E_OK) { - LOGE("Get select rowid statement failed, %d", errCode); - return errCode; - } - - int index = 1; - errCode = SQLiteUtils::BindTextToStatement(stmt, index, cloudGid); - if (errCode != E_OK) { - LOGE("Bind cloud gid to query log rowid statement failed. %d", errCode); - SQLiteUtils::ResetStatement(stmt, true, errCode); - return errCode; - } - errCode = SQLiteUtils::StepWithRetry(stmt); - if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { - LOGE("Not find rowid from log by cloud gid. %d", errCode); - errCode = -E_NOT_FOUND; - } else if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) { - rowId = static_cast(sqlite3_column_int64(stmt, 0)); - errCode = E_OK; - } - SQLiteUtils::ResetStatement(stmt, true, errCode); - return errCode; -} - int SQLiteSingleVerRelationalStorageExecutor::GetFillDownloadAssetStatement(const std::string &tableName, const VBucket &vBucket, const std::vector &fields, sqlite3_stmt *&statement) { @@ -99,7 +66,8 @@ int SQLiteSingleVerRelationalStorageExecutor::GetFillDownloadAssetStatement(cons sql += field.colName + " = ?,"; } sql.pop_back(); - sql += " WHERE rowid = ?;"; + sql += " WHERE rowid = ("; + sql += "SELECT data_key FROM " + DBCommon::GetLogTableName(tableName) + " where cloud_gid = ?);"; sqlite3_stmt *stmt = nullptr; int errCode = SQLiteUtils::GetStatement(dbHandle_, sql, stmt); if (errCode != E_OK) { @@ -118,28 +86,24 @@ int SQLiteSingleVerRelationalStorageExecutor::GetFillDownloadAssetStatement(cons } int SQLiteSingleVerRelationalStorageExecutor::FillCloudAssetForDownload(const TableSchema &tableSchema, - VBucket &vBucket, bool isFullReplace) + VBucket &vBucket, bool isDownloadSuccess) { - sqlite3_stmt *stmt = nullptr; - int errCode = SetLogTriggerStatus(false); + std::string cloudGid; + int errCode = CloudStorageUtils::GetValueFromVBucket(CloudDbConstant::GID_FIELD, vBucket, cloudGid); if (errCode != E_OK) { - LOGE("Fail to set log trigger off, %d", errCode); + LOGE("Miss gid when fill Asset"); return errCode; } + sqlite3_stmt *stmt = nullptr; std::vector assetsField; errCode = CloudStorageUtils::GetAssetFieldsFromSchema(tableSchema, vBucket, assetsField); if (errCode != E_OK) { LOGE("No assets need to be filled."); - goto END; + return errCode; } CloudStorageUtils::ChangeAssetsOnVBucketToAsset(vBucket, assetsField); - int64_t rowId; - errCode = GetQueryLogRowid(tableSchema.name, vBucket, rowId); - if (errCode != E_OK) { - goto END; - } - if (isFullReplace) { + if (isDownloadSuccess) { CloudStorageUtils::FillAssetFromVBucketFinish(vBucket, CloudStorageUtils::FillAssetAfterDownload, CloudStorageUtils::FillAssetsAfterDownload); } else { @@ -147,12 +111,14 @@ int SQLiteSingleVerRelationalStorageExecutor::FillCloudAssetForDownload(const Ta } errCode = GetFillDownloadAssetStatement(tableSchema.name, vBucket, assetsField, stmt); if (errCode != E_OK) { - goto END; + return errCode; } - errCode = SQLiteUtils::BindInt64ToStatement(stmt, assetsField.size() + 1, rowId); + errCode = SQLiteUtils::BindTextToStatement(stmt, assetsField.size() + 1, cloudGid); if (errCode != E_OK) { - SQLiteUtils::ResetStatement(stmt, true, errCode); - goto END; + LOGE("Bind cloud gid to statement failed. %d", errCode); + int ret = E_OK; + SQLiteUtils::ResetStatement(stmt, true, ret); + return errCode; } errCode = SQLiteUtils::StepWithRetry(stmt); if (errCode == SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { @@ -160,14 +126,9 @@ int SQLiteSingleVerRelationalStorageExecutor::FillCloudAssetForDownload(const Ta } else { LOGE("Fill cloud asset failed:%d", errCode); } - SQLiteUtils::ResetStatement(stmt, true, errCode); - -END: - errCode = SetLogTriggerStatus(true); - if (errCode != E_OK) { - LOGE("Fail to set log trigger off, %d", errCode); - } - return errCode; + int ret = E_OK; + SQLiteUtils::ResetStatement(stmt, true, ret); + return errCode != E_OK ? errCode : ret; } int SQLiteSingleVerRelationalStorageExecutor::FillCloudAssetForUpload(const std::string &tableName, @@ -243,12 +204,12 @@ int SQLiteSingleVerRelationalStorageExecutor::InitFillUploadAssetStatement(const } } int64_t rowid = data.rowid[index]; - errCode = SQLiteUtils::BindInt64ToStatement(statement, vBucket.size() + 1, rowid); + errCode = SQLiteUtils::BindInt64ToStatement(statement, vBucket.size() + ROW_ID_INDEX, rowid); if (errCode != E_OK) { return errCode; } int64_t timeStamp = data.timestamp[index]; - return SQLiteUtils::BindInt64ToStatement(statement, vBucket.size() + 2, timeStamp); // 2 is index; + return SQLiteUtils::BindInt64ToStatement(statement, vBucket.size() + TIMESTAMP_INDEX, timeStamp); } bool SQLiteSingleVerRelationalStorageExecutor::IsGetCloudDataContinue(uint32_t curNum, uint32_t curSize, diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp index 59dfe0b1..6da9958a 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.cpp @@ -164,6 +164,8 @@ int SQLiteUtils::OpenDatabase(const OpenDbProperties &properties, sqlite3 *&db, std::lock_guard lock(logMutex_); if (!g_configLog) { sqlite3_config(SQLITE_CONFIG_LOG, &SqliteLogCallback, &properties.createIfNecessary); + sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0); + LOGW("close look aside config"); g_configLog = true; } } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp index 558ecc4a..833be3c1 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp @@ -220,7 +220,6 @@ void StorageEngine::Recycle(StorageExecutor *&handle) if (iter != writeUsingList_.end()) { writeUsingList_.remove(handle); if (writeIdleList_.size() >= 1) { - LOGD("[Recycle] delete handle"); delete handle; handle = nullptr; return; @@ -391,7 +390,6 @@ void StorageEngine::CloseExecutor() std::lock_guard lock(writeMutex_); for (auto &item : writeIdleList_) { if (item != nullptr) { - LOGD("[CloseExecutor] delete item"); delete item; item = nullptr; } @@ -459,7 +457,7 @@ void StorageEngine::WaitWriteHandleIdle() LOGD("Wait wHandle release id[%s]. write[%zu-%zu-%" PRIu32 "]", DBCommon::TransferStringToHex(identifier_).c_str(), writeIdleList_.size(), writeUsingList_.size(), engineAttr_.maxWriteNum); idleCondition_.wait(autoLock, [this]() { - return writeUsingList_.size() == 0; + return writeUsingList_.empty(); }); LOGD("Wait wHandle release finish id[%s]. write[%zu-%zu-%" PRIu32 "]", DBCommon::TransferStringToHex(identifier_).c_str(), writeIdleList_.size(), writeUsingList_.size(), diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp index 2011404d..0f61210d 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp @@ -50,7 +50,7 @@ int StorageProxy::Close() return E_OK; } -int StorageProxy::GetLocalWaterMark(const std::string &tableName, LocalWaterMark &localMark) +int StorageProxy::GetLocalWaterMark(const std::string &tableName, Timestamp &localMark) { std::shared_lock readLock(storeMutex_); if (cloudMetaData_ == nullptr) { @@ -63,7 +63,7 @@ int StorageProxy::GetLocalWaterMark(const std::string &tableName, LocalWaterMark return cloudMetaData_->GetLocalWaterMark(tableName, localMark); } -int StorageProxy::PutLocalWaterMark(const std::string &tableName, LocalWaterMark &localMark) +int StorageProxy::PutLocalWaterMark(const std::string &tableName, Timestamp &localMark) { std::shared_lock readLock(storeMutex_); if (cloudMetaData_ == nullptr) { @@ -76,7 +76,7 @@ int StorageProxy::PutLocalWaterMark(const std::string &tableName, LocalWaterMark return cloudMetaData_->SetLocalWaterMark(tableName, localMark); } -int StorageProxy::GetCloudWaterMark(const std::string &tableName, CloudWaterMark &cloudMark) +int StorageProxy::GetCloudWaterMark(const std::string &tableName, std::string &cloudMark) { std::shared_lock readLock(storeMutex_); if (cloudMetaData_ == nullptr) { @@ -85,7 +85,7 @@ int StorageProxy::GetCloudWaterMark(const std::string &tableName, CloudWaterMark return cloudMetaData_->GetCloudWaterMark(tableName, cloudMark); } -int StorageProxy::SetCloudWaterMark(const std::string &tableName, CloudWaterMark &cloudMark) +int StorageProxy::SetCloudWaterMark(const std::string &tableName, std::string &cloudMark) { std::shared_lock readLock(storeMutex_); if (cloudMetaData_ == nullptr) { @@ -134,7 +134,7 @@ int StorageProxy::Rollback() return errCode; } -int StorageProxy::GetUploadCount(const std::string &tableName, const LocalWaterMark &localMark, +int StorageProxy::GetUploadCount(const std::string &tableName, const Timestamp &localMark, const bool isCloudForcePush, int64_t &count) { std::shared_lock readLock(storeMutex_); @@ -205,7 +205,12 @@ int StorageProxy::GetInfoByPrimaryKeyOrGid(const std::string &tableName, const V return -E_TRANSACT_STATE; } - return store_->GetInfoByPrimaryKeyOrGid(tableName, vBucket, dataInfoWithLog, assetInfo); + int errCode = store_->GetInfoByPrimaryKeyOrGid(tableName, vBucket, dataInfoWithLog, assetInfo); + if (errCode == E_OK) { + dataInfoWithLog.logInfo.timestamp = EraseNanoTime(dataInfoWithLog.logInfo.timestamp); + dataInfoWithLog.logInfo.wTimestamp = EraseNanoTime(dataInfoWithLog.logInfo.wTimestamp); + } + return errCode; } int StorageProxy::PutCloudSyncData(const std::string &tableName, DownloadData &downloadData) @@ -295,8 +300,8 @@ int StorageProxy::GetPrimaryColNamesWithAssetsFields(const TableName &tableName, assetFields.push_back(field); } } - if (colNames.empty()) { - colNames.push_back(CloudDbConstant::ROW_ID_FIELD_NAME); + if (colNames.empty() || colNames.size() > 1) { + (void)colNames.insert(colNames.begin(), CloudDbConstant::ROW_ID_FIELD_NAME); } return E_OK; } @@ -311,16 +316,29 @@ int StorageProxy::NotifyChangedData(const std::string deviceName, ChangedData && return E_OK; } -int StorageProxy::FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isFullReplace) +int StorageProxy::FillCloudAssetForDownload(const std::string &tableName, VBucket &asset, bool isDownloadSuccess) { std::shared_lock readLock(storeMutex_); if (store_ == nullptr) { return -E_INVALID_DB; } - return store_->FillCloudAssetForDownload(tableName, asset, isFullReplace); + if (!transactionExeFlag_.load() || !isWrite_.load()) { + LOGE("the write transaction has not started before fill download assets"); + return -E_TRANSACT_STATE; + } + return store_->FillCloudAssetForDownload(tableName, asset, isDownloadSuccess); } -int StorageProxy::FillCloudGidAndAsset(const OpType &opType, const CloudSyncData &data) +int StorageProxy::SetLogTriggerStatus(bool status) +{ + std::shared_lock readLock(storeMutex_); + if (store_ == nullptr) { + return -E_INVALID_DB; + } + return store_->SetLogTriggerStatus(status); +} + +int StorageProxy::FillCloudGidAndAsset(OpType opType, const CloudSyncData &data) { std::shared_lock readLock(storeMutex_); if (store_ == nullptr) { @@ -342,4 +360,9 @@ std::string StorageProxy::GetIdentify() const } return store_->GetIdentify(); } + +Timestamp StorageProxy::EraseNanoTime(DistributedDB::Timestamp localTime) +{ + return localTime / CloudDbConstant::TEN_THOUSAND * CloudDbConstant::TEN_THOUSAND; +} } diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp index 21f53179..ea2324cc 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp @@ -24,13 +24,12 @@ CloudDBProxy::CloudDBProxy() { } -int CloudDBProxy::SetCloudDB(const std::shared_ptr &cloudDB) +void CloudDBProxy::SetCloudDB(const std::shared_ptr &cloudDB) { std::unique_lock writeLock(cloudMutex_); if (!iCloudDb_) { iCloudDb_ = cloudDB; } - return E_OK; } void CloudDBProxy::SetIAssetLoader(const std::shared_ptr &loader) diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h index 70baed2e..da1eaee5 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h @@ -28,7 +28,7 @@ public: CloudDBProxy(); ~CloudDBProxy() = default; - int SetCloudDB(const std::shared_ptr &cloudDB); + void SetCloudDB(const std::shared_ptr &cloudDB); void SetIAssetLoader(const std::shared_ptr &loader); diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp index 7e067e37..bbbce725 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp @@ -25,21 +25,17 @@ OpType CloudForcePullStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &loc return OpType::DELETE; } else if (IsDelete(cloudInfo)) { return OpType::UPDATE_TIMESTAMP; - } else { - if (IsDelete(localInfo) || deletePrimaryKeySet.find(localInfo.hashKey) != deletePrimaryKeySet.end()) { - return OpType::INSERT; - } else { - return OpType::UPDATE; - } } - } else { - bool gidEmpty = localInfo.cloudGid.empty(); - if (IsDelete(cloudInfo)) { - return gidEmpty ? OpType::NOT_HANDLE : OpType::DELETE; - } else { - return gidEmpty ? OpType::INSERT : OpType::UPDATE; + if (IsDelete(localInfo) || deletePrimaryKeySet.find(localInfo.hashKey) != deletePrimaryKeySet.end()) { + return OpType::INSERT; } + return OpType::UPDATE; } + bool gidEmpty = localInfo.cloudGid.empty(); + if (IsDelete(cloudInfo)) { + return gidEmpty ? OpType::NOT_HANDLE : OpType::DELETE; + } + return gidEmpty ? OpType::INSERT : OpType::UPDATE; } bool CloudForcePullStrategy::JudgeUpdateCursor() diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.cpp new file mode 100644 index 00000000..385f150d --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.cpp @@ -0,0 +1,213 @@ +/* + * 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 "cloud/cloud_sync_tag_assets.h" + +namespace DistributedDB { +namespace { + +void TagSingleAsset(AssetOpType flag, AssetStatus status, Asset &asset, Assets &res, int &errCode) +{ + if (asset.status == static_cast(AssetStatus::DELETE)) { + asset.flag = static_cast(AssetOpType::DELETE); + } else { + asset.flag = static_cast(flag); + } + asset.status = static_cast(status); + + Timestamp timestamp; + errCode = OS::GetCurrentSysTimeInMicrosecond(timestamp); + if (errCode != E_OK) { + LOGE("Can not get current timestamp."); + return; + } + asset.timestamp = static_cast(timestamp / CloudDbConstant::TEN_THOUSAND); + asset.status = asset.flag == static_cast(AssetOpType::NO_CHANGE) ? + static_cast(AssetStatus::NORMAL) : asset.status; + res.push_back(asset); +} + +void TagAssetWithNormalStatus(const bool isNormalStatus, AssetOpType flag, + Asset &asset, Assets &res, int &errCode) +{ + if (isNormalStatus) { + TagSingleAsset(flag, AssetStatus::NORMAL, asset, res, errCode); + return; + } + TagSingleAsset(flag, AssetStatus::DOWNLOADING, asset, res, errCode); +} + +void TagAssetsWithNormalStatus(const bool isNormalStatus, AssetOpType flag, + Assets &assets, Assets &res, int &errCode) +{ + for (Asset &asset : assets) { + TagAssetWithNormalStatus(isNormalStatus, flag, asset, res, errCode); + if (errCode != E_OK) { + break; + } + } +} + +template +bool IsDataContainField(const std::string &assetFieldName, const VBucket &data) +{ + auto assetIter = data.find(assetFieldName); + if (assetIter == data.end()) { + return false; + } + // When type of Assets is not Nil but a vector which size is 0, we think data is not contain this field. + if (assetIter->second.index() == TYPE_INDEX) { + if (std::get(assetIter->second).empty()) { + return false; + } + } + if (assetIter->second.index() != TYPE_INDEX) { + return false; + } + return true; +} + +// AssetOpType and AssetStatus will be tagged, assets to be changed will be returned +// use VBucket rather than Type because we need to check whether it is empty +Assets TagAssets(const std::string &assetFieldName, VBucket &coveredData, VBucket &beCoveredData, + bool setNormalStatus, int &errCode) +{ + Assets res = {}; + bool beCoveredHasAssets = IsDataContainField(assetFieldName, beCoveredData); + bool coveredHasAssets = IsDataContainField(assetFieldName, coveredData); + if (!beCoveredHasAssets) { + if (!coveredHasAssets) { + return res; + } + // all the element in assets will be set to INSERT + TagAssetsWithNormalStatus(setNormalStatus, + AssetOpType::INSERT, std::get(coveredData[assetFieldName]), res, errCode); + return res; + } + if (!coveredHasAssets) { + // all the element in assets will be set to DELETE + TagAssetsWithNormalStatus(setNormalStatus, + AssetOpType::DELETE, std::get(beCoveredData[assetFieldName]), res, errCode); + coveredData[assetFieldName] = res; + return res; + } + Assets &covered = std::get(coveredData[assetFieldName]); + Assets &beCovered = std::get(beCoveredData[assetFieldName]); + std::map coveredAssetsIndexMap = CloudStorageUtils::GenAssetsIndexMap(covered); + for (Asset &beCoveredAsset : beCovered) { + auto it = coveredAssetsIndexMap.find(beCoveredAsset.name); + if (it == coveredAssetsIndexMap.end()) { + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::DELETE, beCoveredAsset, res, errCode); + std::get(coveredData[assetFieldName]).push_back(beCoveredAsset); + continue; + } + Asset &coveredAsset = covered[it->second]; + if (beCoveredAsset.hash != coveredAsset.hash) { + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::UPDATE, coveredAsset, res, errCode); + } else { + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::NO_CHANGE, coveredAsset, res, errCode); + } + // Erase element which has been handled, remaining element will be set to Insert + coveredAssetsIndexMap.erase(it); + if (errCode != E_OK) { + LOGE("Tag assets UPDATE or NO_CHANGE fail!"); + break; + } + } + for (const auto &noHandledAssetKvPair : coveredAssetsIndexMap) { + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::INSERT, + covered[noHandledAssetKvPair.second], res, errCode); + if (errCode != E_OK) { + LOGE("Tag assets INSERT fail!"); + break; + } + } + return res; +} + +// AssetOpType and AssetStatus will be tagged, assets to be changed will be returned +Assets TagAsset(const std::string &assetFieldName, VBucket &coveredData, VBucket &beCoveredData, + bool setNormalStatus, int &errCode) +{ + Assets res = {}; + bool beCoveredHasAsset = IsDataContainField(assetFieldName, beCoveredData) || + IsDataContainField(assetFieldName, beCoveredData); + bool coveredHasAsset = IsDataContainField(assetFieldName, coveredData); + if (!beCoveredHasAsset) { + if (!coveredHasAsset) { + LOGD("[CloudSyncer] Both data do not contain certain asset field"); + return res; + } + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::INSERT, + std::get(coveredData[assetFieldName]), res, errCode); + return res; + } + if (!coveredHasAsset) { + if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::DELETE, + std::get(beCoveredData[assetFieldName]), res, errCode); + } else if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { + TagAssetsWithNormalStatus(setNormalStatus, AssetOpType::DELETE, + std::get(beCoveredData[assetFieldName]), res, errCode); + } + return res; + } + Asset &covered = std::get(coveredData[assetFieldName]); + Asset beCovered; + if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { + // This indicates that asset in cloudData is stored as Asset + beCovered = std::get(beCoveredData[assetFieldName]); + } else if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { + // Stored as ASSETS, first element in assets will be the target asset + beCovered = (std::get(beCoveredData[assetFieldName]))[0]; + } else { + LOGE("The type of data is neither Asset nor Assets"); + return res; + } + if (covered.name != beCovered.name) { + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::INSERT, covered, res, errCode); + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::DELETE, beCovered, res, errCode); + return res; + } + if (covered.hash != beCovered.hash) { + TagAssetWithNormalStatus(setNormalStatus, AssetOpType::UPDATE, covered, res, errCode); + } else { + Assets tmpAssets; + TagAssetWithNormalStatus(true, AssetOpType::NO_CHANGE, covered, tmpAssets, errCode); + } + return res; +} +} // namespace + +Assets TagAssetsInSingleCol( + VBucket &coveredData, VBucket &beCoveredData, const Field &assetField, bool setNormalStatus, int &errCode) +{ + // Define a list to store the tagged result + Assets assets = {}; + switch (assetField.type) { + case TYPE_INDEX: { + assets = TagAssets(assetField.colName, coveredData, beCoveredData, setNormalStatus, errCode); + break; + } + case TYPE_INDEX: { + assets = TagAsset(assetField.colName, coveredData, beCoveredData, setNormalStatus, errCode); + break; + } + default: + LOGW("[CloudSyncer] Meet an unexpected type %d", assetField.type); + break; + } + return assets; +} +} // namespace DistributedDB diff --git a/relational_store/interfaces/ndk/src/relational_predicates_impl.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.h similarity index 51% rename from relational_store/interfaces/ndk/src/relational_predicates_impl.h rename to kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.h index fc1b5b00..76780056 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates_impl.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_tag_assets.h @@ -12,24 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef CLOUD_SYNC_TAG_ASSETS_H +#define CLOUD_SYNC_TAG_ASSETS_H -#ifndef RELATIONAL_PREDICATES_IMPL_H -#define RELATIONAL_PREDICATES_IMPL_H +#include -#include "rdb_predicates.h" -#include "oh_predicates.h" +#include "cloud/cloud_db_constant.h" +#include "cloud/cloud_storage_utils.h" +#include "cloud/cloud_store_types.h" +#include "cloud/cloud_sync_utils.h" +#include "db_errno.h" +#include "icloud_sync_storage_interface.h" +#include "log_print.h" +#include "platform_specific.h" -namespace OHOS { -namespace RdbNdk { -constexpr int RDB_PREDICATES_CID = 1234561; // The class id used to uniquely identify the OH_Predicates class. -class PredicateImpl : public OH_Predicates { -public: - explicit PredicateImpl(const char *table); - OHOS::NativeRdb::RdbPredicates &GetPredicates(); -private: - OHOS::NativeRdb::RdbPredicates predicates_; -}; -} // namespace RdbNdk -} // namespace OHOS -#endif // RELATIONAL_PREDICATES_IMPL_H +namespace DistributedDB { +Assets TagAssetsInSingleCol( + VBucket &coveredData, VBucket &beCoveredData, const Field &assetField, bool setNormalStatus, int &errCode); +} // namespace DistributedDB +#endif // CLOUD_SYNC_TAG_ASSETS_H \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.cpp index ee021e4e..ce805f86 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.cpp @@ -26,12 +26,13 @@ int GetCloudPkVals(const VBucket &datum, const std::vector &pkColNa LOGE("[CloudSyncer] Output paramater should be empty"); return -E_INVALID_ARGS; } - if (pkColNames.size() == 1 && pkColNames[0] == CloudDbConstant::ROW_ID_FIELD_NAME) { - // if data don't have primary key, then use rowID as value - cloudPkVals.push_back(dataKey); - return E_OK; - } for (const auto &pkColName : pkColNames) { + // if data is primary key or is a composite primary key, then use rowID as value + // The single primary key table, does not contain rowid. + if (pkColName == CloudDbConstant::ROW_ID_FIELD_NAME) { + cloudPkVals.push_back(dataKey); + continue; + } auto iter = datum.find(pkColName); if (iter == datum.end()) { LOGE("[CloudSyncer] Cloud data do not contain expected primary field value"); @@ -56,48 +57,9 @@ ChangeType OpTypeToChangeType(OpType strategy) } } - -bool IsCompositeKey(const std::vector &pKColNames) -{ - return (pKColNames.size() > 1); -} - -bool IsNoPrimaryKey(const std::vector &pKColNames) -{ - if (pKColNames.empty()) { - return true; - } - if (pKColNames.size() == 1 && pKColNames[0] == CloudDbConstant::ROW_ID_FIELD_NAME) { - return true; - } - return false; -} - -bool IsSinglePrimaryKey(const std::vector &pKColNames) +bool IsSinglePrimaryKey(const std::vector &pkColNames) { - if (IsCompositeKey(pKColNames) || IsNoPrimaryKey(pKColNames)) { - return false; - } - return true; -} - -int GetSinglePk(VBucket &datum, const std::vector &pkColNames, int64_t dataKey, Type &pkVal) -{ - std::vector pkVals; - int ret = E_OK; - if (IsSinglePrimaryKey(pkColNames)) { - ret = GetCloudPkVals(datum, pkColNames, dataKey, pkVals); - if (ret != E_OK) { - LOGE("[CloudSyncer] Cannot get single primary key for the datum %d", ret); - return ret; - } - pkVal = pkVals[0]; - if (pkVal.index() == TYPE_INDEX) { - LOGE("[CloudSyncer] Invalid primary key type in TagStatus, it's Nil."); - return -E_INTERNAL_ERROR; - } - } - return E_OK; + return pkColNames.size() == 1 && pkColNames[0] != CloudDbConstant::ROW_ID_FIELD_NAME; } void RemoveDataExceptExtendInfo(VBucket &datum, const std::vector &pkColNames) @@ -116,4 +78,71 @@ void RemoveDataExceptExtendInfo(VBucket &datum, const std::vector & } } } + +AssetOpType StatusToFlag(AssetStatus status) +{ + switch (status) { + case AssetStatus::INSERT: + return AssetOpType::INSERT; + case AssetStatus::DELETE: + return AssetOpType::DELETE; + case AssetStatus::UPDATE: + return AssetOpType::UPDATE; + case AssetStatus::NORMAL: + return AssetOpType::NO_CHANGE; + default: + LOGW("[CloudSyncer] Unexpected Situation and won't be handled" + ", Caller should ensure that current situation won't occur"); + return AssetOpType::NO_CHANGE; + } +} + +void StatusToFlagForAsset(Asset &asset) +{ + asset.flag = static_cast(StatusToFlag(static_cast(asset.status))); + asset.status = static_cast(AssetStatus::NORMAL); +} + +void StatusToFlagForAssets(Assets &assets) +{ + for (Asset &asset : assets) { + StatusToFlagForAsset(asset); + } +} + +void StatusToFlagForAssetsInRecord(const std::vector &fields, VBucket &record) +{ + for (const Field &field : fields) { + if (field.type == TYPE_INDEX && record[field.colName].index() == TYPE_INDEX) { + StatusToFlagForAssets(std::get(record[field.colName])); + } else if (field.type == TYPE_INDEX && record[field.colName].index() == TYPE_INDEX) { + StatusToFlagForAsset(std::get(record[field.colName])); + } + } +} + +bool IsChngDataEmpty(const ChangedData &changedData) +{ + return changedData.primaryData[ChangeType::OP_INSERT].empty() || + changedData.primaryData[ChangeType::OP_UPDATE].empty() || + changedData.primaryData[ChangeType::OP_DELETE].empty(); +} + +bool EqualInMsLevel(const Timestamp cmp, const Timestamp beCmp) +{ + return cmp / CloudDbConstant::TEN_THOUSAND == beCmp / CloudDbConstant::TEN_THOUSAND; +} + +bool NeedSaveData(const LogInfo &localLogInfo, const LogInfo &cloudLogInfo) +{ + // if timeStamp, write timestamp, cloudGid are all the same, + // we thought that the datum is mostly be the same between cloud and local + // However, there are still slightly possibility that it may be created from different device, + // So, during the strategy policy [i.e. TagSyncDataStatus], the datum was tagged as UPDATE + // But we won't notify the datum + bool isSame = localLogInfo.timestamp == cloudLogInfo.timestamp && + EqualInMsLevel(localLogInfo.wTimestamp, cloudLogInfo.wTimestamp) && + localLogInfo.cloudGid == cloudLogInfo.cloudGid; + return !isSame; +} } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h index c05c15d3..b8583a11 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h @@ -25,14 +25,22 @@ int GetCloudPkVals(const VBucket &datum, const std::vector &pkColNa ChangeType OpTypeToChangeType(OpType strategy); -bool IsCompositeKey(const std::vector &pKColNames); +bool IsSinglePrimaryKey(const std::vector &pKColNames); -bool IsNoPrimaryKey(const std::vector &pKColNames); +void RemoveDataExceptExtendInfo(VBucket &datum, const std::vector &pkColNames); -bool IsSinglePrimaryKey(const std::vector &pKColNames); +AssetOpType StatusToFlag(AssetStatus status); -int GetSinglePk(VBucket &datum, const std::vector &pkColNames, int64_t dataKey, Type &pkVal); +void StatusToFlagForAsset(Asset &asset); -void RemoveDataExceptExtendInfo(VBucket &datum, const std::vector &pkColNames); +void StatusToFlagForAssets(Assets &assets); + +void StatusToFlagForAssetsInRecord(const std::vector &fields, VBucket &record); + +bool IsChngDataEmpty(const ChangedData &changedData); + +bool EqualInMsLevel(const Timestamp cmp, const Timestamp beCmp); + +bool NeedSaveData(const LogInfo &localLogInfo, const LogInfo &cloudLogInfo); } #endif // CLOUD_SYNC_UTILS_H \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp index fa7ac63e..a5fb6aa7 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp @@ -16,9 +16,11 @@ #include #include +#include #include "cloud/cloud_db_constant.h" #include "cloud/cloud_storage_utils.h" +#include "cloud_sync_tag_assets.h" #include "cloud_sync_utils.h" #include "db_errno.h" #include "cloud/icloud_db.h" @@ -35,6 +37,7 @@ namespace { const TaskId INVALID_TASK_ID = 0u; const int MAX_HEARTBEAT_FAILED_LIMIT = 2; const int HEARTBEAT_PERIOD = 3; + const int MAX_DOWNLOAD_COMMIT_LIMIT = 5; } CloudSyncer::CloudSyncer(std::shared_ptr storageProxy) @@ -78,18 +81,16 @@ int CloudSyncer::Sync(const std::vector &devices, SyncMode mode, return TriggerSync(); } -int CloudSyncer::SetCloudDB(const std::shared_ptr &cloudDB) +void CloudSyncer::SetCloudDB(const std::shared_ptr &cloudDB) { cloudDB_.SetCloudDB(cloudDB); LOGI("[CloudSyncer] SetCloudDB finish"); - return E_OK; } -int CloudSyncer::SetIAssetLoader(const std::shared_ptr &loader) +void CloudSyncer::SetIAssetLoader(const std::shared_ptr &loader) { cloudDB_.SetIAssetLoader(loader); LOGI("[CloudSyncer] SetIAssetLoader finish"); - return E_OK; } void CloudSyncer::Close() @@ -135,100 +136,6 @@ void CloudSyncer::Close() WaitAllSyncCallbackTaskFinish(); } -CloudSyncer::ProcessNotifier::ProcessNotifier(CloudSyncer *syncer) - : syncer_(syncer) -{ - RefObject::IncObjRef(syncer_); -} - -CloudSyncer::ProcessNotifier::~ProcessNotifier() -{ - RefObject::DecObjRef(syncer_); -} - -void CloudSyncer::ProcessNotifier::Init(const std::vector &tableName, - const std::vector &devices) -{ - std::lock_guard autoLock(processMutex_); - syncProcess_.errCode = OK; - syncProcess_.process = ProcessStatus::PROCESSING; - for (const auto &table: tableName) { - TableProcessInfo tableInfo = { - .process = ProcessStatus::PREPARED - }; - syncProcess_.tableProcess[table] = tableInfo; - } - devices_ = devices; -} - -void CloudSyncer::ProcessNotifier::UpdateProcess(const CloudSyncer::InnerProcessInfo &process) -{ - if (process.tableName.empty()) { - return; - } - std::lock_guard autoLock(processMutex_); - syncProcess_.tableProcess[process.tableName].process = process.tableStatus; - if (process.downLoadInfo.batchIndex != 0u) { - LOGD("[ProcessNotifier] update download process index: %" PRIu32, process.downLoadInfo.batchIndex); - syncProcess_.tableProcess[process.tableName].downLoadInfo.batchIndex = process.downLoadInfo.batchIndex; - syncProcess_.tableProcess[process.tableName].downLoadInfo.total = process.downLoadInfo.total; - syncProcess_.tableProcess[process.tableName].downLoadInfo.failCount = process.downLoadInfo.failCount; - syncProcess_.tableProcess[process.tableName].downLoadInfo.successCount = process.downLoadInfo.successCount; - } - if (process.upLoadInfo.batchIndex != 0u) { - LOGD("[ProcessNotifier] update upload process index: %" PRIu32, process.upLoadInfo.batchIndex); - syncProcess_.tableProcess[process.tableName].upLoadInfo.batchIndex = process.upLoadInfo.batchIndex; - syncProcess_.tableProcess[process.tableName].upLoadInfo.total = process.upLoadInfo.total; - syncProcess_.tableProcess[process.tableName].upLoadInfo.failCount = process.upLoadInfo.failCount; - syncProcess_.tableProcess[process.tableName].upLoadInfo.successCount = process.upLoadInfo.successCount; - } -} - -void CloudSyncer::ProcessNotifier::NotifyProcess(const CloudTaskInfo &taskInfo, const InnerProcessInfo &process, - bool notifyWhenError) -{ - UpdateProcess(process); - std::map currentProcess; - { - std::lock_guard autoLock(processMutex_); - if (!notifyWhenError && taskInfo.errCode != E_OK) { - LOGD("[ProcessNotifier] task has error, do not notify now"); - return; - } - syncProcess_.errCode = TransferDBErrno(taskInfo.errCode); - syncProcess_.process = taskInfo.status; - for (const auto &device : devices_) { - // make sure only one device - currentProcess[device] = syncProcess_; - } - } - SyncProcessCallback callback = taskInfo.callback; - if (!callback) { - return; - } - CloudSyncer *syncer = syncer_; - if (syncer == nullptr) { - return; // should not happen - } - RefObject::IncObjRef(syncer); - auto id = syncer->GetIdentify(); - syncer->IncSyncCallbackTaskCount(); - int errCode = RuntimeContext::GetInstance()->ScheduleQueuedTask(id, [callback, currentProcess, syncer]() { - callback(currentProcess); - syncer->DecSyncCallbackTaskCount(); - RefObject::DecObjRef(syncer); - LOGD("[ProcessNotifier] notify process finish"); - }); - if (errCode != E_OK) { - LOGW("[ProcessNotifier] schedule notify process failed %d", errCode); - } -} - -std::vector CloudSyncer::ProcessNotifier::GetDevices() const -{ - return devices_; -} - int CloudSyncer::TriggerSync() { if (closed_) { @@ -308,8 +215,7 @@ int CloudSyncer::DoUploadInNeed(const CloudTaskInfo &taskInfo, const bool needUp return errCode; } for (size_t i = 0; i < taskInfo.table.size(); ++i) { - size_t index = i + 1; - LOGD("[CloudSyncer] try upload table, index: %zu", index); + LOGD("[CloudSyncer] try upload table, index: %zu", i); errCode = CheckTaskIdValid(taskInfo.taskId); if (errCode != E_OK) { LOGE("[CloudSyncer] task is invalid, abort sync"); @@ -348,8 +254,7 @@ int CloudSyncer::DoSyncInner(const CloudTaskInfo &taskInfo, const bool needUploa { int errCode = E_OK; for (size_t i = 0; i < taskInfo.table.size(); ++i) { - size_t index = i + 1; - LOGD("[CloudSyncer] try download table, index: %zu", index); + LOGD("[CloudSyncer] try download table, index: %zu", i); errCode = CheckTaskIdValid(taskInfo.taskId); if (errCode != E_OK) { LOGE("[CloudSyncer] task is invalid, abort sync"); @@ -364,12 +269,13 @@ int CloudSyncer::DoSyncInner(const CloudTaskInfo &taskInfo, const bool needUploa LOGE("[CloudSyncer] download failed %d", errCode); return errCode; } - if (!needUpload) { - errCode = SaveCloudWaterMark(taskInfo.table[i]); - if (errCode != E_OK) { - LOGE("[CloudSyncer] Can not save cloud water mark after downloading %d", errCode); - return errCode; - } + if (needUpload) { + continue; + } + errCode = SaveCloudWaterMark(taskInfo.table[i]); + if (errCode != E_OK) { + LOGE("[CloudSyncer] Can not save cloud water mark after downloading %d", errCode); + return errCode; } } @@ -423,7 +329,7 @@ void CloudSyncer::DoFinished(TaskId taskId, int errCode, const InnerProcessInfo } } -static int SaveChangedDataByType(VBucket &datum, ChangedData &changedData, const DataInfoWithLog &localInfo, +static int SaveChangedDataByType(const VBucket &datum, ChangedData &changedData, const DataInfoWithLog &localInfo, ChangeType type) { int ret = E_OK; @@ -440,24 +346,6 @@ static int SaveChangedDataByType(VBucket &datum, ChangedData &changedData, const return E_OK; } -inline bool EqualInMsLevel(const Timestamp cmp, const Timestamp beCmp) -{ - return cmp / CloudDbConstant::TEN_THOUSAND == beCmp / CloudDbConstant::TEN_THOUSAND; -} - -static bool NeedSaveData(const LogInfo &localLogInfo, const LogInfo &cloudLogInfo) -{ - // if timeStamp, write timestamp, cloudGid are all the same, - // we thought that the datum is mostly be the same between cloud and local - // However, there are still slightly possibility that it may be created from different device, - // So, during the strategy policy [i.e. TagSyncDataStatus], the datum was tagged as UPDATE - // But we won't notify the datum - bool isSame = localLogInfo.timestamp == cloudLogInfo.timestamp && - EqualInMsLevel(localLogInfo.wTimestamp, cloudLogInfo.wTimestamp) && - localLogInfo.cloudGid == cloudLogInfo.cloudGid; - return !isSame; -} - int CloudSyncer::FindDeletedListIndex(const std::vector> &deletedList, const Key &hashKey, size_t &delIdx) { @@ -467,19 +355,13 @@ int CloudSyncer::FindDeletedListIndex(const std::vector> return E_OK; } } - return E_INTERNAL_ERROR; + return -E_INTERNAL_ERROR; } -int CloudSyncer::SaveChangedData(SyncParam ¶m, int dataIndex, const DataInfo &dataInfo, - std::vector &InsertDataNoPrimaryKeys, std::vector> &deletedList) +int CloudSyncer::SaveChangedData(SyncParam ¶m, int downIndex, const DataInfo &dataInfo, + std::vector> &deletedList) { - // For no primary key situation, - if (param.downloadData.opType[dataIndex] == OpType::INSERT && param.changedData.field.size() == 1 && - param.changedData.field[0] == CloudDbConstant::ROW_ID_FIELD_NAME) { - InsertDataNoPrimaryKeys.push_back(dataIndex); - return E_OK; - } - OpType opType = param.downloadData.opType[dataIndex]; + OpType opType = param.downloadData.opType[downIndex]; Key hashKey = dataInfo.localInfo.logInfo.hashKey; if (param.deletePrimaryKeySet.find(hashKey) != param.deletePrimaryKeySet.end()) { if (opType == OpType::INSERT) { @@ -493,6 +375,11 @@ int CloudSyncer::SaveChangedData(SyncParam ¶m, int dataIndex, const DataInfo param.changedData.primaryData[ChangeType::OP_DELETE].begin() + delIdx); (void)param.dupHashKeySet.insert(hashKey); opType = OpType::UPDATE; + // only composite primary key needs to be processed. + if (!param.isSinglePrimaryKey) { + param.withoutRowIdData.updateData.push_back(std::make_tuple(downIndex, + param.changedData.primaryData[ChangeType::OP_UPDATE].size())); + } } else if (opType == OpType::DELETE) { std::pair pair{hashKey, static_cast( param.changedData.primaryData[ChangeType::OP_DELETE].size())}; @@ -501,32 +388,31 @@ int CloudSyncer::SaveChangedData(SyncParam ¶m, int dataIndex, const DataInfo LOGW("[CloudSyncer] deletePrimaryKeySet ignore opType %d.", opType); } } + // INSERT: for no primary key or composite primary key situation + if (!param.isSinglePrimaryKey && opType == OpType::INSERT) { + param.withoutRowIdData.insertData.push_back(downIndex); + return E_OK; + } switch (opType) { + // INSERT: only for single primary key situation case OpType::INSERT: return SaveChangedDataByType( - param.downloadData.data[dataIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_INSERT); + param.downloadData.data[downIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_INSERT); case OpType::UPDATE: if (NeedSaveData(dataInfo.localInfo.logInfo, dataInfo.cloudLogInfo)) { - return SaveChangedDataByType( - param.downloadData.data[dataIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_UPDATE); + return SaveChangedDataByType(param.downloadData.data[downIndex], param.changedData, + dataInfo.localInfo, ChangeType::OP_UPDATE); } break; case OpType::DELETE: - return SaveChangedDataByType( - param.downloadData.data[dataIndex], param.changedData, dataInfo.localInfo, ChangeType::OP_DELETE); + return SaveChangedDataByType(param.downloadData.data[downIndex], param.changedData, + dataInfo.localInfo, ChangeType::OP_DELETE); default: break; } return E_OK; } -static bool IsChngDataEmpty(ChangedData &changedData) -{ - return changedData.primaryData[ChangeType::OP_INSERT].empty() || - changedData.primaryData[ChangeType::OP_UPDATE].empty() || - changedData.primaryData[ChangeType::OP_DELETE].empty(); -} - static LogInfo GetCloudLogInfo(VBucket &datum) { LogInfo cloudLogInfo = { 0 }; @@ -536,179 +422,57 @@ static LogInfo GetCloudLogInfo(VBucket &datum) cloudLogInfo.cloudGid = std::get(datum[CloudDbConstant::GID_FIELD]); return cloudLogInfo; } + /** * UpdateChangedData will be used for Insert case, which we can only get rowid after we saved data in db. */ -static void UpdateChangedData(DownloadData &downloadData, const std::vector &InsertDataNoPrimaryKeys, - ChangedData &changedData) -{ - if (InsertDataNoPrimaryKeys.empty()) { - return; - } - for (size_t j : InsertDataNoPrimaryKeys) { - VBucket &datum = downloadData.data[j]; - changedData.primaryData[ChangeType::OP_INSERT].push_back({datum[CloudDbConstant::ROW_ID_FIELD_NAME]}); - } -} - -static void TagAsset(AssetOpType flag, AssetStatus status, Asset &asset, Assets &res) -{ - if (asset.status == static_cast(AssetStatus::DELETE)) { - asset.flag = static_cast(AssetOpType::DELETE); - } else { - asset.flag = static_cast(flag); - } - asset.status = static_cast(status); - Timestamp timestamp; - OS::GetCurrentSysTimeInMicrosecond(timestamp); - asset.timestamp = static_cast(timestamp / CloudDbConstant::TEN_THOUSAND); - asset.status = asset.flag == static_cast(AssetOpType::NO_CHANGE) ? - static_cast(AssetStatus::NORMAL) : asset.status; - res.push_back(asset); -} - -static void TagAssetWithNormalStatus(const bool isNormalStatus, AssetOpType flag, Asset &asset, Assets &res) -{ - if (isNormalStatus) { - TagAsset(flag, AssetStatus::NORMAL, asset, res); - return; - } - TagAsset(flag, AssetStatus::DOWNLOADING, asset, res); -} - -static void TagAssetsWithNormalStatus(const bool isNormalStatus, AssetOpType flag, Assets &assets, Assets &res) -{ - for (Asset &asset : assets) { - TagAssetWithNormalStatus(isNormalStatus, flag, asset, res); - } -} - -template -static bool IsDataContainField(const std::string &assetFieldName, const VBucket &data) +int CloudSyncer::UpdateChangedData(SyncParam ¶m, AssetDownloadList &assetsDownloadList) { - auto assetIter = data.find(assetFieldName); - if (assetIter == data.end()) { - return false; + if (param.withoutRowIdData.insertData.empty() && param.withoutRowIdData.updateData.empty()) { + return E_OK; } - // When type of Assets is not Nil but a vector which size is 0, we think data is not contain this field. - if (assetIter->second.index() == TYPE_INDEX) { - if (std::get(assetIter->second).empty()) { - return false; + int ret = E_OK; + for (size_t j : param.withoutRowIdData.insertData) { + VBucket &datum = param.downloadData.data[j]; + std::vector primaryValues; + ret = GetCloudPkVals(datum, param.changedData.field, + std::get(datum[CloudDbConstant::ROW_ID_FIELD_NAME]), primaryValues); + if (ret != E_OK) { + LOGE("[CloudSyncer] updateChangedData cannot get primaryValues"); + return ret; } - } - if (assetIter->second.index() != TYPE_INDEX) { - return false; - } - return true; -} - -// AssetOpType and AssetStatus will be tagged, assets to be changed will be returned -static Assets TagAsset(const std::string &assetFieldName, VBucket &coveredData, VBucket &beCoveredData, - bool setNormalStatus) -{ - Assets res = {}; - bool beCoveredHasAsset = IsDataContainField(assetFieldName, beCoveredData) || - IsDataContainField(assetFieldName, beCoveredData); - bool coveredHasAsset = IsDataContainField(assetFieldName, coveredData); - if (!beCoveredHasAsset) { - if (!coveredHasAsset) { - LOGD("[CloudSyncer] Both data do not contain certain asset field"); - return res; - } - TagAssetWithNormalStatus( - setNormalStatus, AssetOpType::INSERT, std::get(coveredData[assetFieldName]), res); - return res; - } - if (!coveredHasAsset) { - if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::DELETE, - std::get(beCoveredData[assetFieldName]), res); - } - if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { - TagAssetsWithNormalStatus(setNormalStatus, AssetOpType::DELETE, - std::get(beCoveredData[assetFieldName]), res); - } - return res; - } - Asset &covered = std::get(coveredData[assetFieldName]); - Asset beCovered; - if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { - // This indicates that asset in cloudData is stored as Asset - beCovered = std::get(beCoveredData[assetFieldName]); - } else if (beCoveredData[assetFieldName].index() == TYPE_INDEX) { - // Stored as ASSETS, first element in assets will be the target asset - beCovered = (std::get(beCoveredData[assetFieldName]))[0]; - } else { - LOGE("The type of data is neither Asset nor Assets"); - return res; - } - if (covered.name != beCovered.name) { - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::INSERT, covered, res); - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::DELETE, beCovered, res); - return res; - } - if (covered.hash != beCovered.hash) { - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::UPDATE, covered, res); - } else { - Assets tmpAssets; - TagAssetWithNormalStatus(true, AssetOpType::NO_CHANGE, covered, tmpAssets); - } - return res; -} - -// AssetOpType and AssetStatus will be tagged, assets to be changed will be returned -// use VBucket rather than Type because we need to check whether it is empty -static Assets TagAssets(const std::string &assetFieldName, VBucket &coveredData, VBucket &beCoveredData, - bool setNormalStatus) -{ - Assets res = {}; - bool beCoveredHasAssets = IsDataContainField(assetFieldName, beCoveredData); - bool coveredHasAssets = IsDataContainField(assetFieldName, coveredData); - if (!beCoveredHasAssets) { - if (!coveredHasAssets) { - return res; - } - // all the element in assets will be set to INSERT - TagAssetsWithNormalStatus(setNormalStatus, - AssetOpType::INSERT, std::get(coveredData[assetFieldName]), res); - return res; - } - if (!coveredHasAssets) { - // all the element in assets will be set to DELETE - TagAssetsWithNormalStatus(setNormalStatus, - AssetOpType::DELETE, std::get(beCoveredData[assetFieldName]), res); - coveredData[assetFieldName] = res; - return res; - } - Assets &covered = std::get(coveredData[assetFieldName]); - Assets &beCovered = std::get(beCoveredData[assetFieldName]); - std::map coveredAssetsIndexMap = CloudStorageUtils::GenAssetsIndexMap(covered); - for (Asset &beCoveredAsset : beCovered) { - auto it = coveredAssetsIndexMap.find(beCoveredAsset.name); - if (it == coveredAssetsIndexMap.end()) { - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::DELETE, beCoveredAsset, res); - std::get(coveredData[assetFieldName]).push_back(beCoveredAsset); - continue; + param.changedData.primaryData[ChangeType::OP_INSERT].push_back(primaryValues); + } + for (const auto &tuple : param.withoutRowIdData.assetInsertData) { + size_t downloadIndex = std::get<0>(tuple); + VBucket &datum = param.downloadData.data[downloadIndex]; + size_t insertIdx = std::get<1>(tuple); + std::vector &pkVal = std::get<5>(assetsDownloadList.downloadList[insertIdx]); // 5 means primary key list + pkVal[0] = datum[CloudDbConstant::ROW_ID_FIELD_NAME]; + } + for (const auto &tuple : param.withoutRowIdData.updateData) { + size_t downloadIndex = std::get<0>(tuple); + size_t updateIndex = std::get<1>(tuple); + VBucket &datum = param.downloadData.data[downloadIndex]; + size_t size = param.changedData.primaryData[ChangeType::OP_UPDATE].size(); + if (updateIndex >= size) { + LOGE("[CloudSyncer] updateIndex is invalid. index=%zu, size=%zu", updateIndex, size); + return -E_INTERNAL_ERROR; } - Asset &coveredAsset = covered[it->second]; - if (beCoveredAsset.hash != coveredAsset.hash) { - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::UPDATE, coveredAsset, res); - } else { - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::NO_CHANGE, coveredAsset, res); + if (param.changedData.primaryData[ChangeType::OP_UPDATE][updateIndex].empty()) { + LOGE("[CloudSyncer] primary key value list should not be empty."); + return -E_INTERNAL_ERROR; } - // Erase element which has been handled, remaining element will be set to Insert - coveredAssetsIndexMap.erase(it); - // flag in Asset is defaultly set to NoChange, so we just go to next iteration + // no primary key or composite primary key, the first element is rowid + param.changedData.primaryData[ChangeType::OP_UPDATE][updateIndex][0] = + datum[CloudDbConstant::ROW_ID_FIELD_NAME]; } - for (const auto &noHandledAssetKvPair : coveredAssetsIndexMap) { - TagAssetWithNormalStatus(setNormalStatus, AssetOpType::INSERT, covered[noHandledAssetKvPair.second], res); - } - return res; + return ret; } bool CloudSyncer::IsDataContainDuplicateAsset(const std::vector &assetFields, VBucket &data) { - for (auto &assetField : assetFields) { + for (const auto &assetField : assetFields) { if (assetField.type == TYPE_INDEX && data[assetField.colName].index() == TYPE_INDEX) { if (CloudStorageUtils::IsAssetsContainDuplicateAsset(std::get(data[assetField.colName]))) { return true; @@ -723,8 +487,9 @@ bool CloudSyncer::IsDataContainAssets() std::lock_guard autoLock(contextLock_); bool hasTable = (currentContext_.assetFields.find(currentContext_.tableName) != currentContext_.assetFields.end()); if (!hasTable) { - LOGE("[CloudSyncer] failed to get assetFields, because tablename doesn't exit in currentContext, %d.", + LOGW("[CloudSyncer] failed to get assetFields, because tableName doesn't exit in currentContext, %d.", -E_INTERNAL_ERROR); + return false; } if (hasTable && currentContext_.assetFields[currentContext_.tableName].empty()) { LOGI("[CloudSyncer] Current table do not contain assets, thereby we needn't download assets"); @@ -759,7 +524,7 @@ void CloudSyncer::WaitAllSyncCallbackTaskFinish() } std::map CloudSyncer::TagAssetsInSingleRecord(VBucket &coveredData, VBucket &beCoveredData, - bool setNormalStatus) + bool setNormalStatus, int &errCode) { // Define a map to store the result std::map res = {}; @@ -770,33 +535,15 @@ std::map CloudSyncer::TagAssetsInSingleRecord(VBucket &cove } // For every column contain asset or assets, assetFields are in context for (const Field &assetField : assetFields) { - Assets assets = TagAssetsInSingleCol(coveredData, beCoveredData, assetField, setNormalStatus); + Assets assets = TagAssetsInSingleCol(coveredData, beCoveredData, assetField, setNormalStatus, errCode); if (!assets.empty()) { res[assetField.colName] = assets; } - } - return res; -} - -Assets CloudSyncer::TagAssetsInSingleCol( - VBucket &coveredData, VBucket &beCoveredData, const Field &assetField, bool setNormalStatus) -{ - // Define a list to store the tagged result - Assets assets = {}; - switch (assetField.type) { - case TYPE_INDEX: { - assets = TagAssets(assetField.colName, coveredData, beCoveredData, setNormalStatus); - break; - } - case TYPE_INDEX: { - assets = TagAsset(assetField.colName, coveredData, beCoveredData, setNormalStatus); + if (errCode != E_OK) { break; } - default: - LOGW("[CloudSyncer] Meet an unexpected type %d", assetField.type); - break; } - return assets; + return res; } int CloudSyncer::FillCloudAssets( @@ -806,92 +553,130 @@ int CloudSyncer::FillCloudAssets( if (normalAssets.size() > 1) { ret = storageProxy_->FillCloudAssetForDownload(tableName, normalAssets, true); if (ret != E_OK) { + LOGE("[CloudSyncer] Can not fill normal cloud assets for download"); return ret; } } if (failedAssets.size() > 1) { ret = storageProxy_->FillCloudAssetForDownload(tableName, failedAssets, false); if (ret != E_OK) { + LOGE("[CloudSyncer] Can not fill abnormal assets for download"); return ret; } } return E_OK; } -int CloudSyncer::HandleDownloadResult(const std::string &tableName, const std::string &gid, - std::map &DownloadResult, bool setAllNormal) +int CloudSyncer::HandleDownloadResult(const std::string &tableName, DownloadCommitList &commitList, + uint32_t &successCount) { - VBucket normalAssets; - VBucket failedAssets; - normalAssets[CloudDbConstant::GID_FIELD] = gid; - failedAssets[CloudDbConstant::GID_FIELD] = gid; - for (auto &assetKvPair : DownloadResult) { - Assets &assets = assetKvPair.second; - if (setAllNormal) { - normalAssets[assetKvPair.first] = std::move(assets); - } else { - failedAssets[assetKvPair.first] = std::move(assets); + successCount = 0; + int errCode = storageProxy_->StartTransaction(TransactType::IMMEDIATE); + if (errCode != E_OK) { + LOGE("[CloudSyncer] start transaction Failed before handle download."); + return errCode; + } + errCode = storageProxy_->SetLogTriggerStatus(false); + if (errCode != E_OK) { + return errCode; + } + for (size_t i = 0; i < commitList.size(); i++) { + std::string gid = std::get<0>(commitList[i]); // 0 means gid is the first element in assetsInfo + // 1 means assetsMap info [colName, assets] is the forth element in downloadList[i] + std::map assetsMap = std::get<1>(commitList[i]); + bool setAllNormal = std::get<2>(commitList[i]); // 2 means whether the download return is E_OK + VBucket normalAssets; + VBucket failedAssets; + normalAssets[CloudDbConstant::GID_FIELD] = gid; + failedAssets[CloudDbConstant::GID_FIELD] = gid; + for (auto &assetKvPair : assetsMap) { + Assets &assets = assetKvPair.second; + if (setAllNormal) { + normalAssets[assetKvPair.first] = std::move(assets); + } else { + failedAssets[assetKvPair.first] = std::move(assets); + } } + errCode = FillCloudAssets(tableName, normalAssets, failedAssets); + if (errCode != E_OK) { + break; + } + successCount++; + } + errCode = storageProxy_->SetLogTriggerStatus(true); + if (errCode != E_OK) { + LOGE("Set log trigger true failed when handle download.%d", errCode); + successCount = 0; + storageProxy_->Rollback(); + return errCode; + } + errCode = storageProxy_->Commit(); + if (errCode != E_OK) { + successCount = 0; } - return FillCloudAssets(tableName, normalAssets, failedAssets); + return errCode; } int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, DownloadList &downloadList, bool willHandleResult, const std::set &dupHashKeySet, ChangedData &changedAssets) { int downloadStatus = E_OK; + DownloadCommitList commitList; for (size_t i = 0; i < downloadList.size(); i++) { - std::string gid = std::get<0>(downloadList[i]); // 0 means gid is the first element in assetsInfo - Type primaryKey = std::get<1>(downloadList[i]); // 1 means primaryKey is the second element in assetsInfo - OpType strategy = std::get<2>(downloadList[i]); // 2 means strategy is the third element in assetsInfo - // 3 means assets info [colName, assets] is the forth element in downloadList[i] - std::map assets = std::get<3>(downloadList[i]); - Key hashKey = std::get<4>(downloadList[i]); // 4 means hash key - std::map downloadAssets(assets); + DownloadItem downloadItem; + GetDownloadItem(downloadList, i, downloadItem); + std::map downloadAssets(downloadItem.assets); CloudStorageUtils::EraseNoChangeAsset(downloadAssets); - // Download data (include deleting) - if (downloadAssets.empty()) { + if (downloadAssets.empty()) { // Download data (include deleting) continue; } - int errorCode = cloudDB_.Download(info.tableName, gid, primaryKey, downloadAssets); + int errorCode = cloudDB_.Download(info.tableName, downloadItem.gid, downloadItem.prefix, downloadAssets); if (errorCode == -E_NOT_SET) { info.downLoadInfo.failCount += (downloadList.size() - i); info.downLoadInfo.successCount -= (downloadList.size() - i); return -E_NOT_SET; } - if (dupHashKeySet.find(hashKey) == dupHashKeySet.end()) { - changedAssets.primaryData[OpTypeToChangeType(strategy)].push_back({primaryKey}); - } else if (strategy == OpType::INSERT) { - changedAssets.primaryData[ChangeType::OP_UPDATE].push_back({primaryKey}); + if (dupHashKeySet.find(downloadItem.hashKey) == dupHashKeySet.end()) { + changedAssets.primaryData[OpTypeToChangeType(downloadItem.strategy)].push_back( + downloadItem.primaryKeyValList); + } else if (downloadItem.strategy == OpType::INSERT) { + changedAssets.primaryData[ChangeType::OP_UPDATE].push_back(downloadItem.primaryKeyValList); } if (!willHandleResult) { continue; } - CloudStorageUtils::MergeDownloadAsset(downloadAssets, assets); + CloudStorageUtils::MergeDownloadAsset(downloadAssets, downloadItem.assets); // Process result of each asset - if (errorCode != E_OK) { - // if not OK, update process info and handle download result seperately - int ret = HandleDownloadResult(info.tableName, gid, assets, false); + commitList.push_back(std::make_tuple(downloadItem.gid, std::move(downloadItem.assets), errorCode == E_OK)); + downloadStatus = downloadStatus == E_OK ? errorCode : downloadStatus; + if ((i + 1) % MAX_DOWNLOAD_COMMIT_LIMIT == 0 || i == (commitList.size() - 1)) { + int ret = CommitDownloadResult(info, commitList); if (ret != E_OK) { - info.downLoadInfo.failCount += (downloadList.size() - i); - info.downLoadInfo.successCount -= (downloadList.size() - i); return ret; } - downloadStatus = downloadStatus == E_OK ? errorCode : downloadStatus; - info.downLoadInfo.failCount++; - info.downLoadInfo.successCount--; - continue; } - int ret = HandleDownloadResult(info.tableName, gid, assets, true); + } + if (!commitList.empty()) { + int ret = CommitDownloadResult(info, commitList); if (ret != E_OK) { - info.downLoadInfo.failCount += (downloadList.size() - i); - info.downLoadInfo.successCount -= (downloadList.size() - i); return ret; } } + LOGD("Download status is %d", downloadStatus); return downloadStatus; } +void CloudSyncer::GetDownloadItem(const DownloadList &downloadList, size_t i, DownloadItem &downloadItem) +{ + downloadItem.gid = std::get<0>(downloadList[i]); // 0 means gid is the first element in assetsInfo + downloadItem.prefix = std::get<1>(downloadList[i]); // 1 means primaryKey is the second element in assetsInfo + downloadItem.strategy = std::get<2>(downloadList[i]); // 2 means strategy is the third element in assetsInfo + // 3 means assets info [colName, assets] is the forth element in downloadList[i] + downloadItem.assets = std::get<3>(downloadList[i]); + downloadItem.hashKey = std::get<4>(downloadList[i]); // 4 means hash key + downloadItem.primaryKeyValList = std::get<5>(downloadList[i]); // 5 means primary key value list +} + int CloudSyncer::DownloadAssets(InnerProcessInfo &info, const std::vector &pKColNames, const std::set &dupHashKeySet, ChangedData &changedAssets) { @@ -924,9 +709,8 @@ int CloudSyncer::DownloadAssets(InnerProcessInfo &info, const std::vector CloudSyncer::GetAssetsFromVBucket(VBucket &data) @@ -937,7 +721,7 @@ std::map CloudSyncer::GetAssetsFromVBucket(VBucket &data) std::lock_guard autoLock(contextLock_); fields = currentContext_.assetFields[currentContext_.tableName]; } - for (Field &field : fields) { + for (const auto &field : fields) { if (data.find(field.colName) != data.end()) { if (field.type == TYPE_INDEX && data[field.colName].index() == TYPE_INDEX) { assets[field.colName] = { std::get(data[field.colName]) }; @@ -955,14 +739,9 @@ std::map CloudSyncer::GetAssetsFromVBucket(VBucket &data) int CloudSyncer::TagStatus(bool isExist, SyncParam ¶m, size_t idx, DataInfo &dataInfo, VBucket &localAssetInfo) { OpType strategyOpResult = OpType::NOT_HANDLE; - { - std::lock_guard autoLock(contextLock_); - if (!currentContext_.strategy) { - LOGE("[CloudSyncer] strategy has not been set when tag status, %d.", -E_INTERNAL_ERROR); - return -E_INTERNAL_ERROR; - } - strategyOpResult = currentContext_.strategy->TagSyncDataStatus(isExist, dataInfo.localInfo.logInfo, - dataInfo.cloudLogInfo, param.deletePrimaryKeySet); + int errCode = TagStatusByStrategy(isExist, param, dataInfo, strategyOpResult); + if (errCode != E_OK) { + return errCode; } param.downloadData.opType[idx] = strategyOpResult; if (!IsDataContainAssets()) { @@ -978,39 +757,19 @@ int CloudSyncer::TagStatus(bool isExist, SyncParam ¶m, size_t idx, DataInfo int CloudSyncer::TagDownloadAssets(const Key &hashKey, size_t idx, SyncParam ¶m, DataInfo &dataInfo, VBucket &localAssetInfo) { - Type prefix; int ret = E_OK; OpType strategy = param.downloadData.opType[idx]; - std::map assetsMap; switch (strategy) { case OpType::INSERT: case OpType::UPDATE: - ret = GetSinglePk(param.downloadData.data[idx], param.pkColNames, - dataInfo.localInfo.logInfo.dataKey, prefix); - if (ret != E_OK) { - LOGE("Can not get single primary key while strategy is UPDATE/INSERT in TagDownloadAssets %d", ret); - return ret; - } - assetsMap = TagAssetsInSingleRecord(param.downloadData.data[idx], localAssetInfo, false); - param.assetsDownloadList.downloadList.push_back( - std::make_tuple(dataInfo.cloudLogInfo.cloudGid, prefix, strategy, assetsMap, hashKey)); - break; case OpType::DELETE: - ret = GetSinglePk(dataInfo.localInfo.primaryKeys, param.pkColNames, - dataInfo.localInfo.logInfo.dataKey, prefix); - if (ret != E_OK) { - LOGE("Can not get single primary key while strategy is DELETE in TagDownloadAssets %d", ret); - return ret; - } - assetsMap = TagAssetsInSingleRecord(param.downloadData.data[idx], localAssetInfo, false); - param.assetsDownloadList.completeDownloadList.push_back( - std::make_tuple(dataInfo.cloudLogInfo.cloudGid, prefix, strategy, assetsMap, hashKey)); + ret = HandleTagAssets(hashKey, idx, param, dataInfo, localAssetInfo); break; case OpType::NOT_HANDLE: case OpType::ONLY_UPDATE_GID: case OpType::SET_CLOUD_FORCE_PUSH_FLAG_ZERO: { // means upload need this data // Save the asset info into context - assetsMap = GetAssetsFromVBucket(param.downloadData.data[idx]); + std::map assetsMap = GetAssetsFromVBucket(param.downloadData.data[idx]); { std::lock_guard autoLock(contextLock_); if (currentContext_.assetsInfo.find(param.tableName) == currentContext_.assetsInfo.end()) { @@ -1023,11 +782,48 @@ int CloudSyncer::TagDownloadAssets(const Key &hashKey, size_t idx, SyncParam &pa default: break; } - return E_OK; + return ret; } -int CloudSyncer::SaveDatum(SyncParam ¶m, size_t idx, std::vector &InsertDataNoPrimaryKeys, - std::vector> &deletedList) +int CloudSyncer::HandleTagAssets(const Key &hashKey, size_t idx, SyncParam ¶m, DataInfo &dataInfo, + VBucket &localAssetInfo) +{ + Type prefix; + std::vector pkVals; + OpType strategy = param.downloadData.opType[idx]; + bool isDelStrategy = (strategy == OpType::DELETE); + int ret = GetCloudPkVals(isDelStrategy ? dataInfo.localInfo.primaryKeys : param.downloadData.data[idx], + param.pkColNames, dataInfo.localInfo.logInfo.dataKey, pkVals); + if (ret != E_OK) { + LOGE("[CloudSyncer] HandleTagAssets cannot get primary key value list. %d", ret); + return ret; + } + prefix = param.isSinglePrimaryKey ? pkVals[0] : prefix; + if (param.isSinglePrimaryKey && prefix.index() == TYPE_INDEX) { + LOGE("[CloudSyncer] Invalid primary key type in TagStatus, it's Nil."); + return -E_INTERNAL_ERROR; + } + std::map assetsMap = TagAssetsInSingleRecord(param.downloadData.data[idx], localAssetInfo, + false, ret); + if (ret != E_OK) { + LOGE("[CloudSyncer] TagAssetsInSingleRecord report ERROR"); + return ret; + } + if (isDelStrategy) { + param.assetsDownloadList.completeDownloadList.push_back( + std::make_tuple(dataInfo.cloudLogInfo.cloudGid, prefix, strategy, assetsMap, hashKey, pkVals)); + } else { + if (!param.isSinglePrimaryKey && strategy == OpType::INSERT) { + param.withoutRowIdData.assetInsertData.push_back(std::make_tuple(idx, + param.assetsDownloadList.downloadList.size())); + } + param.assetsDownloadList.downloadList.push_back( + std::make_tuple(dataInfo.cloudLogInfo.cloudGid, prefix, strategy, assetsMap, hashKey, pkVals)); + } + return ret; +} + +int CloudSyncer::SaveDatum(SyncParam ¶m, size_t idx, std::vector> &deletedList) { int ret = PreHandleData(param.downloadData.data[idx], param.pkColNames); if (ret != E_OK) { @@ -1054,31 +850,38 @@ int CloudSyncer::SaveDatum(SyncParam ¶m, size_t idx, std::vector &In LOGE("[CloudSyncer] Cannot tag status: %d.", ret); return ret; } - ret = SaveChangedData(param, idx, dataInfo, InsertDataNoPrimaryKeys, deletedList); + ret = SaveChangedData(param, idx, dataInfo, deletedList); if (ret != E_OK) { LOGE("[CloudSyncer] Cannot save changed data: %d.", ret); } return ret; } +void CloudSyncer::ClearWithoutData(SyncParam ¶m) +{ + param.withoutRowIdData.insertData.clear(); + param.withoutRowIdData.updateData.clear(); + param.withoutRowIdData.assetInsertData.clear(); +} + int CloudSyncer::SaveData(SyncParam ¶m) { if (!IsChngDataEmpty(param.changedData)) { LOGE("[CloudSyncer] changedData.primaryData should have no member inside."); return -E_INVALID_ARGS; } - // Update download btach Info + // Update download batch Info param.info.downLoadInfo.batchIndex += 1; param.info.downLoadInfo.total += param.downloadData.data.size(); int ret = E_OK; - std::vector InsertDataNoPrimaryKeys; AssetDownloadList assetsDownloadList; param.assetsDownloadList = assetsDownloadList; param.deletePrimaryKeySet.clear(); param.dupHashKeySet.clear(); + ClearWithoutData(param); std::vector> deletedList; for (size_t i = 0; i < param.downloadData.data.size(); i++) { - ret = SaveDatum(param, i, InsertDataNoPrimaryKeys, deletedList); + ret = SaveDatum(param, i, deletedList); if (ret != E_OK) { param.info.downLoadInfo.failCount += param.downloadData.data.size(); LOGE("[CloudSyncer] Cannot save datum due to error code %d", ret); @@ -1090,14 +893,19 @@ int CloudSyncer::SaveData(SyncParam ¶m) std::lock_guard autoLock(contextLock_); currentContext_.assetDownloadList = param.assetsDownloadList; } - // save the data to the database by batch + // save the data to the database by batch, downloadData will return rowid when insert data. ret = storageProxy_->PutCloudSyncData(param.tableName, param.downloadData); if (ret != E_OK) { param.info.downLoadInfo.failCount += param.downloadData.data.size(); LOGE("[CloudSyncer] Cannot save the data to database with error code: %d.", ret); return ret; } - UpdateChangedData(param.downloadData, InsertDataNoPrimaryKeys, param.changedData); + ret = UpdateChangedData(param, currentContext_.assetDownloadList); + if (ret != E_OK) { + param.info.downLoadInfo.failCount += param.downloadData.data.size(); + LOGE("[CloudSyncer] Cannot update changed data: %d.", ret); + return ret; + } // Update downloadInfo param.info.downLoadInfo.successCount += param.downloadData.data.size(); // Get latest cloudWaterMark @@ -1141,8 +949,7 @@ bool CloudSyncer::NeedNotifyChangedData(const ChangedData &changedData) } } // when there have no data been changed, it needn't notified - if (changedData.primaryData[OP_INSERT].empty() && - changedData.primaryData[OP_UPDATE].empty() && + if (changedData.primaryData[OP_INSERT].empty() && changedData.primaryData[OP_UPDATE].empty() && changedData.primaryData[OP_DELETE].empty()) { return false; } @@ -1168,7 +975,6 @@ int CloudSyncer::NotifyChangedData(ChangedData &&changedData) int ret = storageProxy_->NotifyChangedData(deviceName, std::move(changedData)); if (ret != E_OK) { LOGE("[CloudSyncer] Cannot notify changed data while downloading, %d.", ret); - return ret; } return ret; } @@ -1222,15 +1028,15 @@ int CloudSyncer::SaveDataInTransaction(CloudSyncer::TaskId taskId, SyncParam &pa ret = storageProxy_->Commit(); if (ret != E_OK) { LOGE("[CloudSyncer] Cannot commit a transaction: %d.", ret); - return ret; } - return E_OK; + return ret; } int CloudSyncer::SaveDataNotifyProcess(CloudSyncer::TaskId taskId, SyncParam ¶m) { ChangedData changedData; param.changedData = changedData; + param.downloadData.opType.resize(param.downloadData.data.size()); int ret = SaveDataInTransaction(taskId, param); if (ret != E_OK) { return ret; @@ -1241,12 +1047,12 @@ int CloudSyncer::SaveDataNotifyProcess(CloudSyncer::TaskId taskId, SyncParam &pa LOGE("[CloudSyncer] Cannot notify changed data due to error %d", ret); return ret; } - // Begin dowloading assets + // Begin downloading assets ChangedData changedAssets; ret = DownloadAssets(param.info, param.pkColNames, param.dupHashKeySet, changedAssets); (void)NotifyChangedData(std::move(changedAssets)); if (ret != E_OK) { - LOGE("[CloudSyncer] Someting wrong happened during assets downloading due to error %d", ret); + LOGE("[CloudSyncer] Cannot notify downloadAssets due to error %d", ret); return ret; } UpdateCloudWaterMark(param); @@ -1279,6 +1085,7 @@ int CloudSyncer::DoDownload(CloudSyncer::TaskId taskId) } param.info.tableName = param.tableName; std::vector assetFields; + // only no primary key and composite primary key contains rowid. ret = storageProxy_->GetPrimaryColNamesWithAssetsFields(param.tableName, param.pkColNames, assetFields); if (ret != E_OK) { LOGE("[CloudSyncer] Cannot get primary column names: %d", ret); @@ -1288,11 +1095,14 @@ int CloudSyncer::DoDownload(CloudSyncer::TaskId taskId) std::lock_guard autoLock(contextLock_); currentContext_.assetFields[currentContext_.tableName] = assetFields; } - - ret = storageProxy_->GetCloudWaterMark(param.tableName, param.cloudWaterMark); - if (ret != E_OK) { - LOGE("[CloudSyncer] Cannot get cloud water level from cloud meta data: %d.", ret); - return ret; + param.isSinglePrimaryKey = IsSinglePrimaryKey(param.pkColNames); + param.cloudWaterMark = ""; + if (!IsModeForcePull(taskId)) { + ret = storageProxy_->GetCloudWaterMark(param.tableName, param.cloudWaterMark); + if (ret != E_OK) { + LOGE("[CloudSyncer] Cannot get cloud water level from cloud meta data: %d.", ret); + return ret; + } } return DoDownloadInner(taskId, param); } @@ -1300,11 +1110,11 @@ int CloudSyncer::DoDownload(CloudSyncer::TaskId taskId) int CloudSyncer::DoDownloadInner(CloudSyncer::TaskId taskId, SyncParam ¶m) { // Query data by batch until reaching end and not more data need to be download - bool queryEnd = false; int ret = PreCheck(taskId, param.info.tableName); if (ret != E_OK) { return ret; } + bool queryEnd = false; while (!queryEnd) { // Get cloud data after cloud water mark param.info.tableStatus = ProcessStatus::PROCESSING; @@ -1359,7 +1169,7 @@ void CloudSyncer::NotifyInEmptyDownload(CloudSyncer::TaskId taskId, InnerProcess } } -int CloudSyncer::PreCheckUpload(CloudSyncer::TaskId &taskId, const TableName &tableName, LocalWaterMark &localMark) +int CloudSyncer::PreCheckUpload(CloudSyncer::TaskId &taskId, const TableName &tableName, Timestamp &localMark) { int ret = PreCheck(taskId, tableName); if (ret != E_OK) { @@ -1388,7 +1198,7 @@ int CloudSyncer::PreCheckUpload(CloudSyncer::TaskId &taskId, const TableName &ta return ret; } -bool CloudSyncer::CheckCloudSyncDataEmpty(CloudSyncData &uploadData) +bool CloudSyncer::CheckCloudSyncDataEmpty(const CloudSyncData &uploadData) { return uploadData.insData.extend.empty() && uploadData.insData.record.empty() && uploadData.updData.extend.empty() && uploadData.updData.record.empty() && @@ -1478,7 +1288,7 @@ int CloudSyncer::DoUpload(CloudSyncer::TaskId taskId, bool lastTable) return ret; } - LocalWaterMark localMark = 0u; + Timestamp localMark = 0u; ret = PreCheckUpload(taskId, tableName, localMark); if (ret != E_OK) { LOGE("[CloudSyncer] Doing upload sync pre check failed, %d.", ret); @@ -1516,53 +1326,11 @@ int CloudSyncer::DoUpload(CloudSyncer::TaskId taskId, bool lastTable) return DoUploadInner(tableName, param); } -static AssetOpType StatusToFlag(AssetStatus status) { - switch (status) - { - case AssetStatus::INSERT: - return AssetOpType::INSERT; - case AssetStatus::DELETE: - return AssetOpType::DELETE; - case AssetStatus::UPDATE: - return AssetOpType::UPDATE; - case AssetStatus::NORMAL: - return AssetOpType::NO_CHANGE; - default: - LOGW("[CloudSyncer] Unexpected Situation and won't be handled" - ", Caller should ensure that current situation won't occur"); - return AssetOpType::NO_CHANGE; - } -} - -static void StatusToFlagForAsset(Asset &asset) -{ - asset.flag = static_cast(StatusToFlag(static_cast(asset.status))); - asset.status = static_cast(AssetStatus::NORMAL); -} - -static void StatusToFlagForAssets(Assets &assets) -{ - for (Asset &asset : assets) { - StatusToFlagForAsset(asset); - } -} - -static void StatusToFlagForAssetsInRecord(const std::vector &fields, VBucket &record) -{ - for (const Field &field : fields) { - if (field.type == TYPE_INDEX && record[field.colName].index() == TYPE_INDEX) { - StatusToFlagForAssets(std::get(record[field.colName])); - } - if (field.type == TYPE_INDEX && record[field.colName].index() == TYPE_INDEX) { - StatusToFlagForAsset(std::get(record[field.colName])); - } - } -} - -void CloudSyncer::TagUploadAssets(CloudSyncData &uploadData) +int CloudSyncer::TagUploadAssets(CloudSyncData &uploadData) { + int errCode = E_OK; if (!IsDataContainAssets()) { - return; + return E_OK; } std::map> cloudAssets; { @@ -1573,7 +1341,11 @@ void CloudSyncer::TagUploadAssets(CloudSyncData &uploadData) // for insert scenario, gid does not exist. Thereby, we needn't compare with cloud asset get in download procedure for (size_t i = 0; i < uploadData.insData.extend.size(); i++) { VBucket cloudAsset; // cloudAsset must be empty - (void)TagAssetsInSingleRecord(uploadData.insData.record[i], cloudAsset, true); + (void)TagAssetsInSingleRecord(uploadData.insData.record[i], cloudAsset, true, errCode); + if (errCode != E_OK) { + LOGE("[CloudSyncer] TagAssetsInSingleRecord report ERROR in DELETE/INSERT option"); + return errCode; + } } // for update scenario, assets shoulb be compared with asset get in download procedure. for (size_t i = 0; i < uploadData.updData.extend.size(); i++) { @@ -1583,7 +1355,7 @@ void CloudSyncer::TagUploadAssets(CloudSyncData &uploadData) auto gidIter = uploadData.updData.extend[i].find(CloudDbConstant::GID_FIELD); if (gidIter == uploadData.updData.extend[i].end()) { LOGE("[CloudSyncer] Datum to be upload must contain gid"); - return; + return -E_INVALID_DATA; } // update data must contain gid, however, we could only pull data after water mark // Therefore, we need to check whether we contain the data @@ -1601,12 +1373,17 @@ void CloudSyncer::TagUploadAssets(CloudSyncData &uploadData) for (const auto &it : cloudAssets[gid]) { cloudAsset[it.first] = it.second; } - (void)TagAssetsInSingleRecord(uploadData.updData.record[i], cloudAsset, true); + (void)TagAssetsInSingleRecord(uploadData.updData.record[i], cloudAsset, true, errCode); + if (errCode != E_OK) { + LOGE("[CloudSyncer] TagAssetsInSingleRecord report ERROR in UPDATE option"); + return errCode; + } } + return E_OK; } int CloudSyncer::PreProcessBatchUpload(TaskId taskId, const InnerProcessInfo &innerProcessInfo, - CloudSyncData &uploadData, LocalWaterMark &localMark) + CloudSyncData &uploadData, Timestamp &localMark) { // Precheck and calculate local water mark which would be updated if batch upload successed. int ret = CheckTaskIdValid(taskId); @@ -1618,20 +1395,22 @@ int CloudSyncer::PreProcessBatchUpload(TaskId taskId, const InnerProcessInfo &in LOGE("[CloudSyncer] Invalid Cloud Sync Data of Upload, %d.", ret); return ret; } - TagUploadAssets(uploadData); + ret = TagUploadAssets(uploadData); + if (ret != E_OK) { + LOGE("TagUploadAssets report ERROR, cannot tag uploadAssets"); + return ret; + } // get local water mark to be updated in future. - if (!IsModeForcePush(taskId)) { - ret = UpdateExtendTime(uploadData, innerProcessInfo.upLoadInfo.total, taskId, localMark); - if (ret != E_OK) { - LOGE("[CloudSyncer] Failed to get new local water mark in Cloud Sync Data, %d.", ret); - } + ret = UpdateExtendTime(uploadData, innerProcessInfo.upLoadInfo.total, taskId, localMark); + if (ret != E_OK) { + LOGE("[CloudSyncer] Failed to get new local water mark in Cloud Sync Data, %d.", ret); } return ret; } int CloudSyncer::SaveCloudWaterMark(const TableName &tableName) { - CloudWaterMark cloudWaterMark; + std::string cloudWaterMark; { std::lock_guard autoLock(contextLock_); if (currentContext_.cloudWaterMarks.find(tableName) == currentContext_.cloudWaterMarks.end()) { @@ -1659,6 +1438,12 @@ bool CloudSyncer::IsModeForcePush(const TaskId taskId) return cloudTaskInfos_[taskId].mode == SYNC_MODE_CLOUD_FORCE_PUSH; } +bool CloudSyncer::IsModeForcePull(const TaskId taskId) +{ + std::lock_guard autoLock(queueLock_); + return cloudTaskInfos_[taskId].mode == SYNC_MODE_CLOUD_FORCE_PULL; +} + int CloudSyncer::DoUploadInner(const std::string &tableName, UploadParam &uploadParam) { ContinueToken continueStmtToken = nullptr; @@ -1721,7 +1506,7 @@ int CloudSyncer::DoUploadInner(const std::string &tableName, UploadParam &upload int CloudSyncer::PreHandleData(VBucket &datum, const std::vector &pkColNames) { // type index of field in fields - std::vector> filedAndIndex = { + std::vector> fieldAndIndex = { std::pair(CloudDbConstant::GID_FIELD, TYPE_INDEX), std::pair(CloudDbConstant::CREATE_FIELD, TYPE_INDEX), std::pair(CloudDbConstant::MODIFY_FIELD, TYPE_INDEX), @@ -1729,13 +1514,13 @@ int CloudSyncer::PreHandleData(VBucket &datum, const std::vector &p std::pair(CloudDbConstant::CURSOR_FIELD, TYPE_INDEX) }; - for (size_t i = 0; i < filedAndIndex.size(); i++) { - if (datum.find(filedAndIndex[i].first) == datum.end()) { - LOGE("[CloudSyncer] Cloud data do not contain expected field: %s.", filedAndIndex[i].first.c_str()); + for (const auto &fieldIndex : fieldAndIndex) { + if (datum.find(fieldIndex.first) == datum.end()) { + LOGE("[CloudSyncer] Cloud data do not contain expected field: %s.", fieldIndex.first.c_str()); return -E_CLOUD_ERROR; } - if (datum[filedAndIndex[i].first].index() != static_cast(filedAndIndex[i].second)) { - LOGE("[CloudSyncer] Cloud data's field: %s, doesn't has expected type.", filedAndIndex[i].first.c_str()); + if (datum[fieldIndex.first].index() != static_cast(fieldIndex.second)) { + LOGE("[CloudSyncer] Cloud data's field: %s, doesn't has expected type.", fieldIndex.first.c_str()); return -E_CLOUD_ERROR; } } @@ -1745,19 +1530,19 @@ int CloudSyncer::PreHandleData(VBucket &datum, const std::vector &p } std::lock_guard autoLock(contextLock_); if (IsDataContainDuplicateAsset(currentContext_.assetFields[currentContext_.tableName], datum)) { + LOGE("[CloudSyncer] Cloud data contain duplicate asset"); return -E_CLOUD_ERROR; } return E_OK; } -int CloudSyncer::QueryCloudData(const std::string &tableName, CloudWaterMark &cloudWaterMark, +int CloudSyncer::QueryCloudData(const std::string &tableName, std::string &cloudWaterMark, DownloadData &downloadData) { VBucket extend = { {CloudDbConstant::CURSOR_FIELD, cloudWaterMark} }; int ret = cloudDB_.Query(tableName, extend, downloadData.data); - downloadData.opType.resize(downloadData.data.size()); if (ret == -E_QUERY_END) { LOGD("[CloudSyncer] Download data from cloud database success and no more data need to be downloaded"); return -E_QUERY_END; @@ -1779,12 +1564,8 @@ int CloudSyncer::QueryCloudData(const std::string &tableName, CloudWaterMark &cl int CloudSyncer::CheckParamValid(const std::vector &devices, SyncMode mode) { - if (devices.empty()) { - LOGE("[CloudSyncer] devices is empty"); - return -E_INVALID_ARGS; - } - if (devices.size() > 1) { - LOGE("[CloudSyncer] too much devices"); + if (devices.size() != 1) { + LOGE("[CloudSyncer] invalid devices size %zu", devices.size()); return -E_INVALID_ARGS; } for (const auto &dev: devices) { @@ -2054,7 +1835,7 @@ int CloudSyncer::CheckCloudSyncDataValid(CloudSyncData uploadData, const std::st return E_OK; } -int CloudSyncer::GetWaterMarkAndUpdateTime(std::vector& extend, LocalWaterMark &waterMark) +int CloudSyncer::GetWaterMarkAndUpdateTime(std::vector& extend, Timestamp &waterMark) { for (auto &extendData: extend) { if (extendData.empty() || extendData.find(CloudDbConstant::MODIFY_FIELD) == extendData.end()) { @@ -2086,10 +1867,9 @@ int CloudSyncer::GetWaterMarkAndUpdateTime(std::vector& extend, LocalWa // After doing a batch upload, we need to use CloudSyncData's maximum timestamp to update the water mark; int CloudSyncer::UpdateExtendTime(CloudSyncData &uploadData, const int64_t &count, - TaskId taskId, LocalWaterMark &waterMark) + TaskId taskId, Timestamp &waterMark) { - int ret = E_OK; - ret = CheckCloudSyncDataValid(uploadData, uploadData.tableName, count, taskId); + int ret = CheckCloudSyncDataValid(uploadData, uploadData.tableName, count, taskId); if (ret != E_OK) { LOGE("[CloudSyncer] Invalid Sync Data when get local water mark."); return ret; @@ -2139,6 +1919,7 @@ void CloudSyncer::ClearCloudSyncData(CloudSyncData &uploadData) std::vector().swap(uploadData.delData.record); std::vector().swap(uploadData.delData.extend); } + int32_t CloudSyncer::GetCloudSyncTaskCount() { std::lock_guard autoLock(queueLock_); @@ -2173,6 +1954,7 @@ int CloudSyncer::CleanCloudData(ClearMode mode, const std::vector & storageProxy_->Rollback(); return errCode; } + if (!assets.empty() && mode == FLAG_AND_DATA) { errCode = cloudDB_.RemoveLocalAssets(assets); if (errCode != E_OK) { @@ -2183,11 +1965,9 @@ int CloudSyncer::CleanCloudData(ClearMode mode, const std::vector & } storageProxy_->Commit(); - return errCode; } - void CloudSyncer::ModifyCloudDataTime(VBucket &data) { // data already check field modify_field and create_field @@ -2211,8 +1991,42 @@ void CloudSyncer::UpdateCloudWaterMark(const SyncParam ¶m) } } +int CloudSyncer::CommitDownloadResult(InnerProcessInfo &info, DownloadCommitList &commitList) +{ + uint32_t successCount = 0; + int ret = HandleDownloadResult(info.tableName, commitList, successCount); + info.downLoadInfo.failCount += (commitList.size() - successCount); + info.downLoadInfo.successCount -= (commitList.size() - successCount); + if (ret != E_OK) { + LOGE("Commit download result failed.%d", ret); + } + commitList.clear(); + return ret; +} + std::string CloudSyncer::GetIdentify() const { return id_; } + +int CloudSyncer::TagStatusByStrategy(bool isExist, SyncParam ¶m, DataInfo &dataInfo, OpType &strategyOpResult) +{ + strategyOpResult = OpType::NOT_HANDLE; + // ignore same record with local generate data + if (dataInfo.localInfo.logInfo.device.empty() && + !NeedSaveData(dataInfo.localInfo.logInfo, dataInfo.cloudLogInfo)) { + // not handle same data + return E_OK; + } + { + std::lock_guard autoLock(contextLock_); + if (!currentContext_.strategy) { + LOGE("[CloudSyncer] strategy has not been set when tag status, %d.", -E_INTERNAL_ERROR); + return -E_INTERNAL_ERROR; + } + strategyOpResult = currentContext_.strategy->TagSyncDataStatus(isExist, dataInfo.localInfo.logInfo, + dataInfo.cloudLogInfo, param.deletePrimaryKeySet); + } + return E_OK; +} } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h index 1ccc43cc..5258b042 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h @@ -23,6 +23,8 @@ #include "cloud_db_proxy.h" #include "cloud/cloud_store_types.h" #include "cloud/cloud_sync_strategy.h" +#include "cloud/icloud_syncer.h" +#include "cloud/process_notifier.h" #include "data_transformer.h" #include "db_common.h" #include "cloud/icloud_db.h" @@ -32,8 +34,10 @@ #include "store_observer.h" namespace DistributedDB { -using DownloadList = std::vector, Key>>; -class CloudSyncer : public RefObject { +using DownloadList = std::vector, Key, + std::vector>>; +using DownloadCommitList = std::vector, bool>>; +class CloudSyncer : public ICloudSyncer { public: explicit CloudSyncer(std::shared_ptr storageProxy); ~CloudSyncer() override = default; @@ -42,9 +46,9 @@ public: int Sync(const std::vector &devices, SyncMode mode, const std::vector &tables, const SyncProcessCallback &callback, int64_t waitTime); - int SetCloudDB(const std::shared_ptr &cloudDB); + void SetCloudDB(const std::shared_ptr &cloudDB); - int SetIAssetLoader(const std::shared_ptr &loader); + void SetIAssetLoader(const std::shared_ptr &loader); int CleanCloudData(ClearMode mode, const std::vector &tableNameList, const RelationalSchemaObject &localSchema); @@ -52,64 +56,41 @@ public: int32_t GetCloudSyncTaskCount(); void Close(); + + void IncSyncCallbackTaskCount() override; + + void DecSyncCallbackTaskCount() override; + + std::string GetIdentify() const override; protected: - using TaskId = uint64_t; - struct CloudTaskInfo { - SyncMode mode = SyncMode::SYNC_MODE_PUSH_ONLY; - ProcessStatus status = ProcessStatus::PREPARED; - int errCode = 0; - TaskId taskId = 0u; - std::vector table; - SyncProcessCallback callback; - int64_t timeout; - std::vector devices; - }; struct DataInfo { DataInfoWithLog localInfo; LogInfo cloudLogInfo; }; - struct InnerProcessInfo { - std::string tableName; - ProcessStatus tableStatus = ProcessStatus::PREPARED; - Info downLoadInfo; - Info upLoadInfo; - }; struct AssetDownloadList { // assets in following list will fill STATUS and timestamp after calling downloading DownloadList downloadList = {}; // assets in following list won't fill STATUS and timestamp after calling downloading DownloadList completeDownloadList = {}; }; + struct WithoutRowIdData { + std::vector insertData = {}; + std::vector> updateData = {}; + std::vector> assetInsertData = {}; + }; struct SyncParam { DownloadData downloadData; ChangedData changedData; InnerProcessInfo info; AssetDownloadList assetsDownloadList; - CloudWaterMark cloudWaterMark; + std::string cloudWaterMark; std::vector pkColNames; std::set deletePrimaryKeySet; std::set dupHashKeySet; std::string tableName; + bool isSinglePrimaryKey; bool isLastBatch = false; - }; - class ProcessNotifier { - public: - explicit ProcessNotifier(CloudSyncer *syncer); - ~ProcessNotifier(); - - void Init(const std::vector &tableName, const std::vector &devices); - - void UpdateProcess(const InnerProcessInfo &process); - - void NotifyProcess(const CloudTaskInfo &taskInfo, const InnerProcessInfo &process, - bool notifyWhenError = false); - - std::vector GetDevices() const; - protected: - std::mutex processMutex_; - SyncProcess syncProcess_; - std::vector devices_; - CloudSyncer *syncer_; + WithoutRowIdData withoutRowIdData; }; struct TaskContext { TaskId currentTaskId = 0u; @@ -121,14 +102,22 @@ protected: AssetDownloadList assetDownloadList; // store GID and assets, using in upload procedure std::map>> assetsInfo; - std::map cloudWaterMarks; + std::map cloudWaterMarks; }; struct UploadParam { int64_t count = 0; TaskId taskId = 0u; - LocalWaterMark localMark = 0u; + Timestamp localMark = 0u; bool lastTable = false; }; + struct DownloadItem { + std::string gid; + Type prefix; + OpType strategy; + std::map assets; + Key hashKey; + std::vector primaryKeyValList; + }; int TriggerSync(); @@ -148,7 +137,7 @@ protected: void NotifyInEmptyDownload(CloudSyncer::TaskId taskId, InnerProcessInfo &info); - int PreCheckUpload(TaskId &taskId, const TableName &tableName, LocalWaterMark &localMark); + int PreCheckUpload(TaskId &taskId, const TableName &tableName, Timestamp &localMark); int PreCheck(TaskId &taskId, const TableName &tableName); @@ -157,17 +146,17 @@ protected: int CheckCloudSyncDataValid(CloudSyncData uploadData, const std::string &tableName, const int64_t &count, TaskId &taskId); - bool CheckCloudSyncDataEmpty(CloudSyncData &uploadData); + static bool CheckCloudSyncDataEmpty(const CloudSyncData &uploadData); - int GetWaterMarkAndUpdateTime(std::vector& extend, LocalWaterMark &waterMark); + int GetWaterMarkAndUpdateTime(std::vector& extend, Timestamp &waterMark); int UpdateExtendTime(CloudSyncData &uploadData, const int64_t &count, TaskId taskId, - LocalWaterMark &waterMark); + Timestamp &waterMark); void ClearCloudSyncData(CloudSyncData &uploadData); int PreProcessBatchUpload(TaskId taskId, const InnerProcessInfo &innerProcessInfo, - CloudSyncData &uploadData, LocalWaterMark &localMark); + CloudSyncData &uploadData, Timestamp &localMark); int PutWaterMarkAfterBatchUpload(const std::string &tableName, UploadParam &uploadParam); @@ -177,11 +166,13 @@ protected: bool IsModeForcePush(const TaskId taskId); + bool IsModeForcePull(const TaskId taskId); + int DoUploadInner(const std::string &tableName, UploadParam &uploadParam); int PreHandleData(VBucket &datum, const std::vector &pkColNames); - int QueryCloudData(const std::string &tableName, CloudWaterMark &cloudWaterMark, DownloadData &downloadData); + int QueryCloudData(const std::string &tableName, std::string &cloudWaterMark, DownloadData &downloadData); int CheckTaskIdValid(TaskId taskId); @@ -209,8 +200,7 @@ protected: void SetTaskFailed(TaskId taskId, int errCode); - int SaveDatum(SyncParam ¶m, size_t idx, std::vector &InsertDataNoPrimaryKeys, - std::vector> &deletedList); + int SaveDatum(SyncParam ¶m, size_t idx, std::vector> &deletedList); int SaveData(SyncParam ¶m); @@ -219,10 +209,10 @@ protected: int SaveDataInTransaction(CloudSyncer::TaskId taskId, SyncParam ¶m); int FindDeletedListIndex(const std::vector> &deletedList, const Key &hashKey, - size_t &delIdx); + size_t &delIdx); int SaveChangedData(SyncParam ¶m, int dataIndex, const DataInfo &dataInfo, - std::vector &InsertDataNoPrimaryKeys, std::vector> &deletedList); + std::vector> &deletedList); int SaveDataNotifyProcess(CloudSyncer::TaskId taskId, SyncParam ¶m); @@ -235,22 +225,20 @@ protected: std::map GetAssetsFromVBucket(VBucket &data); std::map TagAssetsInSingleRecord(VBucket &coveredData, VBucket &beCoveredData, - bool setNormalStatus); - - Assets TagAssetsInSingleCol(VBucket &coveredData, VBucket &beCoveredData, const Field &assetField, - bool setNormalStatus); + bool setNormalStatus, int &errCode); int TagStatus(bool isExist, SyncParam ¶m, size_t idx, DataInfo &dataInfo, VBucket &localAssetInfo); + int HandleTagAssets(const Key &hashKey, size_t idx, SyncParam ¶m, DataInfo &dataInfo, VBucket &localAssetInfo); + int TagDownloadAssets(const Key &hashKey, size_t idx, SyncParam ¶m, DataInfo &dataInfo, VBucket &localAssetInfo); - void TagUploadAssets(CloudSyncData &uploadData); + int TagUploadAssets(CloudSyncData &uploadData); int FillCloudAssets(const std::string &tableName, VBucket &normalAssets, VBucket &failedAssets); - int HandleDownloadResult(const std::string &tableName, const std::string &gid, - std::map &DownloadResult, bool setAllNormal); + int HandleDownloadResult(const std::string &tableName, DownloadCommitList &commitList, uint32_t &successCount); int DownloadAssets(InnerProcessInfo &info, const std::vector &pKColNames, const std::set &dupHashKeySet, ChangedData &changedAssets); @@ -258,25 +246,29 @@ protected: int CloudDbDownloadAssets(InnerProcessInfo &info, DownloadList &downloadList, bool willHandleResult, const std::set &dupHashKeySet, ChangedData &changedAssets); + void GetDownloadItem(const DownloadList &downloadList, size_t i, DownloadItem &downloadItem); + bool IsDataContainAssets(); - bool IsDataContainDuplicateAsset(const std::vector &assetFields, VBucket &data); + void ModifyCloudDataTime(VBucket &data); + + int SaveCloudWaterMark(const TableName &tableName); - void IncSyncCallbackTaskCount(); + bool IsDataContainDuplicateAsset(const std::vector &assetFields, VBucket &data); - void DecSyncCallbackTaskCount(); + int UpdateChangedData(SyncParam ¶m, AssetDownloadList &assetsDownloadList); void WaitAllSyncCallbackTaskFinish(); - static int CheckParamValid(const std::vector &devices, SyncMode mode); + void UpdateCloudWaterMark(const SyncParam ¶m); - void ModifyCloudDataTime(VBucket &data); + int TagStatusByStrategy(bool isExist, SyncParam ¶m, DataInfo &dataInfo, OpType &strategyOpResult); - int SaveCloudWaterMark(const TableName &tableName); + int CommitDownloadResult(InnerProcessInfo &info, DownloadCommitList &commitList); - void UpdateCloudWaterMark(const SyncParam ¶m); + static int CheckParamValid(const std::vector &devices, SyncMode mode); - std::string GetIdentify() const; + void ClearWithoutData(SyncParam ¶m); std::mutex queueLock_; TaskId currentTaskId_; @@ -286,7 +278,6 @@ protected: std::mutex contextLock_; TaskContext currentContext_; std::condition_variable contextCv_; - std::mutex syncMutex_; // Clean Cloud Data and Sync are mutually exclusive CloudDBProxy cloudDB_; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/icloud_syncer.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/icloud_syncer.h new file mode 100644 index 00000000..850138d4 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/icloud_syncer.h @@ -0,0 +1,48 @@ +/* + * 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 I_CLOUD_SYNCER_H +#define I_CLOUD_SYNCER_H +#include "cloud/cloud_store_types.h" +#include "ref_object.h" +namespace DistributedDB { +class ICloudSyncer : public virtual RefObject { +public: + using TaskId = uint64_t; + struct CloudTaskInfo { + SyncMode mode = SyncMode::SYNC_MODE_PUSH_ONLY; + ProcessStatus status = ProcessStatus::PREPARED; + int errCode = 0; + TaskId taskId = 0u; + std::vector table; + SyncProcessCallback callback; + int64_t timeout = 0; + std::vector devices; + }; + + struct InnerProcessInfo { + std::string tableName; + ProcessStatus tableStatus = ProcessStatus::PREPARED; + Info downLoadInfo; + Info upLoadInfo; + }; + + virtual void IncSyncCallbackTaskCount() = 0; + + virtual void DecSyncCallbackTaskCount() = 0; + + virtual std::string GetIdentify() const = 0; +}; +} +#endif // I_CLOUD_SYNCER_H diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.cpp new file mode 100644 index 00000000..668c33d2 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.cpp @@ -0,0 +1,116 @@ +/* + * 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 "process_notifier.h" + +#include "db_errno.h" +#include "kv_store_errno.h" +#include "runtime_context.h" +namespace DistributedDB { +ProcessNotifier::ProcessNotifier(ICloudSyncer *syncer) + : syncer_(syncer) +{ + RefObject::IncObjRef(syncer_); +} + +ProcessNotifier::~ProcessNotifier() +{ + RefObject::DecObjRef(syncer_); +} + +void ProcessNotifier::Init(const std::vector &tableName, + const std::vector &devices) +{ + std::lock_guard autoLock(processMutex_); + syncProcess_.errCode = OK; + syncProcess_.process = ProcessStatus::PROCESSING; + for (const auto &table: tableName) { + TableProcessInfo tableInfo = { + .process = ProcessStatus::PREPARED + }; + syncProcess_.tableProcess[table] = tableInfo; + } + devices_ = devices; +} + +void ProcessNotifier::UpdateProcess(const ICloudSyncer::InnerProcessInfo &process) +{ + if (process.tableName.empty()) { + return; + } + std::lock_guard autoLock(processMutex_); + syncProcess_.tableProcess[process.tableName].process = process.tableStatus; + if (process.downLoadInfo.batchIndex != 0u) { + LOGD("[ProcessNotifier] update download process index: %" PRIu32, process.downLoadInfo.batchIndex); + syncProcess_.tableProcess[process.tableName].downLoadInfo.batchIndex = process.downLoadInfo.batchIndex; + syncProcess_.tableProcess[process.tableName].downLoadInfo.total = process.downLoadInfo.total; + syncProcess_.tableProcess[process.tableName].downLoadInfo.failCount = process.downLoadInfo.failCount; + syncProcess_.tableProcess[process.tableName].downLoadInfo.successCount = process.downLoadInfo.successCount; + } + if (process.upLoadInfo.batchIndex != 0u) { + LOGD("[ProcessNotifier] update upload process index: %" PRIu32, process.upLoadInfo.batchIndex); + syncProcess_.tableProcess[process.tableName].upLoadInfo.batchIndex = process.upLoadInfo.batchIndex; + syncProcess_.tableProcess[process.tableName].upLoadInfo.total = process.upLoadInfo.total; + syncProcess_.tableProcess[process.tableName].upLoadInfo.failCount = process.upLoadInfo.failCount; + syncProcess_.tableProcess[process.tableName].upLoadInfo.successCount = process.upLoadInfo.successCount; + } +} + +void ProcessNotifier::NotifyProcess(const ICloudSyncer::CloudTaskInfo &taskInfo, + const ICloudSyncer::InnerProcessInfo &process, bool notifyWhenError) +{ + UpdateProcess(process); + std::map currentProcess; + { + std::lock_guard autoLock(processMutex_); + if (!notifyWhenError && taskInfo.errCode != E_OK) { + LOGD("[ProcessNotifier] task has error, do not notify now"); + return; + } + syncProcess_.errCode = TransferDBErrno(taskInfo.errCode); + syncProcess_.process = taskInfo.status; + for (const auto &device : devices_) { + // make sure only one device + currentProcess[device] = syncProcess_; + } + } + SyncProcessCallback callback = taskInfo.callback; + if (!callback) { + LOGD("[ProcessNotifier] task hasn't callback"); + return; + } + ICloudSyncer *syncer = syncer_; + if (syncer == nullptr) { + return; // should not happen + } + RefObject::IncObjRef(syncer); + auto id = syncer->GetIdentify(); + syncer->IncSyncCallbackTaskCount(); + int errCode = RuntimeContext::GetInstance()->ScheduleQueuedTask(id, [callback, currentProcess, syncer]() { + LOGD("[ProcessNotifier] begin notify process"); + callback(currentProcess); + syncer->DecSyncCallbackTaskCount(); + RefObject::DecObjRef(syncer); + LOGD("[ProcessNotifier] notify process finish"); + }); + if (errCode != E_OK) { + LOGW("[ProcessNotifier] schedule notify process failed %d", errCode); + } +} + +std::vector ProcessNotifier::GetDevices() const +{ + return devices_; +} +} \ No newline at end of file diff --git a/relational_store/interfaces/ndk/src/relational_values_bucket_impl.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.h similarity index 45% rename from relational_store/interfaces/ndk/src/relational_values_bucket_impl.h rename to kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.h index ef51d3ac..326d8ad5 100644 --- a/relational_store/interfaces/ndk/src/relational_values_bucket_impl.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/process_notifier.h @@ -13,22 +13,28 @@ * limitations under the License. */ -#ifndef RELATIONAL_VALUES_BUCKET_IMPL_H -#define RELATIONAL_VALUES_BUCKET_IMPL_H +#ifndef PROCESS_NOTIFIER_H +#define PROCESS_NOTIFIER_H +#include "icloud_syncer.h" +namespace DistributedDB { +class ProcessNotifier { +public: + explicit ProcessNotifier(ICloudSyncer *syncer); + ~ProcessNotifier(); -#include "oh_values_bucket.h" -#include "values_bucket.h" + void Init(const std::vector &tableName, const std::vector &devices); -namespace OHOS { -namespace RdbNdk { -constexpr int RDB_VBUCKET_CID = 1234562; // The class id used to uniquely identify the OH_Rdb_VBucket class. -class ValuesBucketImpl : public OH_VBucket { -public: - ValuesBucketImpl(); - OHOS::NativeRdb::ValuesBucket &getValuesBucket(); -private: - OHOS::NativeRdb::ValuesBucket valuesBucket_; + void UpdateProcess(const ICloudSyncer::InnerProcessInfo &process); + + void NotifyProcess(const ICloudSyncer::CloudTaskInfo &taskInfo, const ICloudSyncer::InnerProcessInfo &process, + bool notifyWhenError = false); + + std::vector GetDevices() const; +protected: + std::mutex processMutex_; + SyncProcess syncProcess_; + std::vector devices_; + ICloudSyncer *syncer_; }; -} // namespace RdbNdk -} // namespace OHOS -#endif // RELATIONAL_VALUES_BUCKET_IMPL_H +} +#endif // PROCESS_NOTIFIER_H diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp index 64bef321..ab7ff0e8 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/generic_syncer.cpp @@ -34,6 +34,9 @@ #include "single_ver_serialize_manager.h" namespace DistributedDB { +namespace { + constexpr uint32_t DEFAULT_MTU_SIZE = 1024u * 1024u; // 1M +} const int GenericSyncer::MIN_VALID_SYNC_ID = 1; std::mutex GenericSyncer::moduleInitLock_; int GenericSyncer::currentSyncId_ = 0; @@ -1043,7 +1046,7 @@ int GenericSyncer::GetSyncDataSize(const std::string &device, size_t &size) cons metadata = metadata_; } metadata->GetLocalWaterMark(device, localWaterMark); - uint32_t expectedMtuSize = 1024u * 1024u; // 1M + uint32_t expectedMtuSize = DEFAULT_MTU_SIZE; DataSizeSpecInfo syncDataSizeInfo = {expectedMtuSize, static_cast(MAX_TIMESTAMP)}; std::vector outData; ContinueToken token = nullptr; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/sync_task_context.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/sync_task_context.cpp index b8fedaaa..71bd609f 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/sync_task_context.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/sync_task_context.cpp @@ -32,8 +32,8 @@ std::mutex SyncTaskContext::synTaskContextSetLock_; std::set SyncTaskContext::synTaskContextSet_; namespace { - const int NEGOTIATION_LIMIT = 2; - const uint32_t SESSION_ID_MAX_VALUE = 0x8fffffffu; + constexpr int NEGOTIATION_LIMIT = 2; + constexpr uint32_t SESSION_ID_MAX_VALUE = 0x8fffffffu; } SyncTaskContext::SyncTaskContext() @@ -808,10 +808,7 @@ SyncOperation *SyncTaskContext::GetAndIncSyncOperation() const uint32_t SyncTaskContext::GenerateRequestSessionId() { - uint32_t sessionId = 0u; - if (lastRequestSessionId_ != 0) { - sessionId = lastRequestSessionId_ + 1; - } + uint32_t sessionId = lastRequestSessionId_ != 0 ? lastRequestSessionId_ + 1 : 0; // make sure sessionId is between 0x01 and 0x8fffffff if (sessionId > SESSION_ID_MAX_VALUE || sessionId == 0) { sessionId = Hash::Hash32Func(deviceId_ + std::to_string(syncId_) + diff --git a/kv_store/frameworks/libs/distributeddb/test/BUILD.gn b/kv_store/frameworks/libs/distributeddb/test/BUILD.gn index 9478c2d2..9fda240c 100644 --- a/kv_store/frameworks/libs/distributeddb/test/BUILD.gn +++ b/kv_store/frameworks/libs/distributeddb/test/BUILD.gn @@ -247,8 +247,10 @@ ohos_source_set("src_file") { "../syncer/src/cloud/cloud_force_pull_strategy.cpp", "../syncer/src/cloud/cloud_force_push_strategy.cpp", "../syncer/src/cloud/cloud_merge_strategy.cpp", + "../syncer/src/cloud/cloud_sync_tag_assets.cpp", "../syncer/src/cloud/cloud_sync_utils.cpp", "../syncer/src/cloud/cloud_syncer.cpp", + "../syncer/src/cloud/process_notifier.cpp", "../syncer/src/cloud/strategy_factory.cpp", "../syncer/src/commit_history_sync.cpp", "../syncer/src/communicator_proxy.cpp", @@ -854,6 +856,17 @@ distributeddb_unittest("DistributedDBCloudSaveCloudDataTest") { sources = [ "unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp" ] } +distributeddb_unittest( + "DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest") { + sources = [ "unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp" ] +} + +distributeddb_unittest("DistributedDBCloudCheckSyncTest") { + sources = [ + "unittest/common/storage/cloud/distributeddb_cloud_check_sync_test.cpp", + ] +} + ############################################################################### group("unittest") { testonly = true @@ -863,8 +876,10 @@ group("unittest") { ":DistributedDBAbilitySyncTest", ":DistributedDBAutoLaunchUnitTest", ":DistributedDBCloudAssetCompareTest", + ":DistributedDBCloudCheckSyncTest", ":DistributedDBCloudDBProxyTest", ":DistributedDBCloudInterfacesRelationalExtTest", + ":DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest", ":DistributedDBCloudInterfacesRelationalSyncTest", ":DistributedDBCloudSaveCloudDataTest", ":DistributedDBCloudSchemaMgrTest", @@ -977,6 +992,7 @@ group("distributeddatamgr_fuzztest") { "fuzztest/relationalstoredelegate_fuzzer:fuzztest", "fuzztest/relationalstoremanager_fuzzer:fuzztest", "fuzztest/schemadelegate_fuzzer:fuzztest", + "fuzztest/storage_fuzzer:fuzztest", "fuzztest/sync_fuzzer:fuzztest", ] } diff --git a/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp b/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp index bdb8b62e..d7d48af7 100644 --- a/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/cloudsync_fuzzer/cloudsync_fuzzer.cpp @@ -15,6 +15,8 @@ #include "cloudsync_fuzzer.h" #include "cloud_db_types.h" +#include "cloud_db_constant.h" +#include "time_helper.h" #include "distributeddb_data_generate_unit_test.h" #include "distributeddb_tools_test.h" #include "log_print.h" @@ -37,11 +39,24 @@ static const char *g_table = "worker1"; static const char *g_createLocalTableSql = "CREATE TABLE IF NOT EXISTS worker1(" \ "name TEXT PRIMARY KEY," \ - "height REAL ," \ - "married BOOLEAN ," \ + "height REAL DEFAULT 123.4," \ + "married BOOLEAN DEFAULT false," \ "photo BLOB NOT NULL," \ - "assert BLOB," \ - "age INT);"; + "assert BLOB DEFAULT NULL," \ + "asserts BLOB DEFAULT NULL," \ + "age INT DEFAULT 1);"; +static const char *g_insertLocalDataSql = + "INSERT OR REPLACE INTO worker1(name, photo) VALUES(?, ?);"; +static const char *g_insertLocalAssetSql = + "INSERT OR REPLACE INTO worker1(name, photo, assert, asserts) VALUES(?, ?, ?, ?);"; +static const Asset g_localAsset = { + .version = 1, .name = "Phone", .assetId = "0", .subpath = "/local/sync", .uri = "/local/sync", + .modifyTime = "123456", .createTime = "", .size = "256", .hash = "ASE" +}; +static const Asset g_cloudAsset = { + .version = 2, .name = "Phone", .assetId = "0", .subpath = "/local/sync", .uri = "/cloud/sync", + .modifyTime = "123456", .createTime = "0", .size = "1024", .hash = "DEC" +}; class CloudSyncContext { public: void FinishAndNotify() @@ -92,7 +107,7 @@ public: const std::vector cloudFiled = { {"name", TYPE_INDEX, true}, {"height", TYPE_INDEX}, {"married", TYPE_INDEX}, {"photo", TYPE_INDEX, false, false}, - {"assert", TYPE_INDEX}, {"age", TYPE_INDEX} + {"assert", TYPE_INDEX}, {"asserts", TYPE_INDEX}, {"age", TYPE_INDEX} }; TableSchema tableSchema = { .name = g_table, @@ -103,6 +118,117 @@ public: delegate->CreateDistributedTable(g_table, CLOUD_COOPERATION); } + static void InitDbData(sqlite3 *&db, const uint8_t *data, size_t size) + { + sqlite3_stmt *stmt = nullptr; + int errCode = SQLiteUtils::GetStatement(db, g_insertLocalDataSql, stmt); + if (errCode != E_OK) { + return; + } + FuzzerData fuzzerData(data, size); + uint32_t len = fuzzerData.GetUInt32(); + for (size_t i = 0; i <= size; ++i) { + std::string idStr = fuzzerData.GetString(len); + errCode = SQLiteUtils::BindTextToStatement(stmt, 1, idStr); + if (errCode != E_OK) { + break; + } + std::vector photo = fuzzerData.GetSequence(fuzzerData.GetInt()); + errCode = SQLiteUtils::BindBlobToStatement(stmt, 2, photo); // 2 is index of photo + if (errCode != E_OK) { + break; + } + errCode = SQLiteUtils::StepWithRetry(stmt); + if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { + break; + } + SQLiteUtils::ResetStatement(stmt, false, errCode); + } + SQLiteUtils::ResetStatement(stmt, true, errCode); + } + + static Asset GenAsset(std::string name, std::string hash) + { + Asset asset; + asset.name = name; + asset.hash = hash; + return asset; + } + + void InitDbAsset(const uint8_t* data, size_t size) + { + sqlite3_stmt *stmt = nullptr; + int errCode = SQLiteUtils::GetStatement(db_, g_insertLocalAssetSql, stmt); + if (errCode != E_OK) { + return; + } + FuzzerData fuzzerData(data, size); + uint32_t len = fuzzerData.GetUInt32(); + for (size_t i = 0; i <= size; ++i) { + std::string idStr = fuzzerData.GetString(len); + errCode = SQLiteUtils::BindTextToStatement(stmt, 1, idStr); + if (errCode != E_OK) { + break; + } + std::vector photo = fuzzerData.GetSequence(fuzzerData.GetInt()); + errCode = SQLiteUtils::BindBlobToStatement(stmt, 2, photo); // 2 is index of photo + if (errCode != E_OK) { + break; + } + std::vector assetBlob; + RuntimeContext::GetInstance()->AssetToBlob(localAssets_[i % size], assetBlob); + errCode = SQLiteUtils::BindBlobToStatement(stmt, 3, assetBlob); // 3 is index of assert + if (errCode != E_OK) { + break; + } + std::vector assetsBlob; + std::vector assetVec(localAssets_.begin() + (i % size), localAssets_.end()); + RuntimeContext::GetInstance()->AssetsToBlob(assetVec, assetBlob); + errCode = SQLiteUtils::BindBlobToStatement(stmt, 4, assetBlob); // 4 is index of asserts + if (errCode != E_OK) { + break; + } + errCode = SQLiteUtils::StepWithRetry(stmt); + if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { + break; + } + SQLiteUtils::ResetStatement(stmt, false, errCode); + } + SQLiteUtils::ResetStatement(stmt, true, errCode); + } + + void InsertCloudTableRecord(int64_t begin, int64_t count, int64_t photoSize, bool assetIsNull) + { + std::vector photo(photoSize, 'v'); + std::vector record1; + std::vector extend1; + double randomHeight = 166.0; // 166.0 is random double value + int64_t randomAge = 13L; // 13 is random int64_t value + Timestamp now = TimeHelper::GetSysCurrentTime(); + for (int64_t i = begin; i < begin + count; ++i) { + VBucket data; + data.insert_or_assign("name", "Cloud" + std::to_string(i)); + data.insert_or_assign("height", randomHeight); + data.insert_or_assign("married", false); + data.insert_or_assign("photo", photo); + data.insert_or_assign("age", randomAge); + Asset asset = g_cloudAsset; + asset.name = asset.name + std::to_string(i); + assetIsNull ? data.insert_or_assign("assert", Nil()) : data.insert_or_assign("assert", asset); + record1.push_back(data); + VBucket log; + log.insert_or_assign(CloudDbConstant::CREATE_FIELD, + static_cast(now / CloudDbConstant::TEN_THOUSAND + i)); + log.insert_or_assign(CloudDbConstant::MODIFY_FIELD, + static_cast(now / CloudDbConstant::TEN_THOUSAND + i)); + log.insert_or_assign(CloudDbConstant::DELETE_FIELD, false); + extend1.push_back(log); + } + virtualCloudDb_->BatchInsert(g_table, std::move(record1), extend1); + LOGD("insert cloud record worker1[primary key]:[cloud%" PRId64 " - cloud%" PRId64 ")", begin, count); + std::this_thread::sleep_for(std::chrono::milliseconds(count)); + } + void SetUp() { DistributedDBToolsTest::TestDirInit(testDir_); @@ -177,6 +303,56 @@ public: LOGI("[RandomModeSync] select mode %d", static_cast(mode)); BlockSync(mode); } + + void DataChangeSync(const uint8_t* data, size_t size) + { + SetCloudDbSchema(delegate_); + if (size == 0) { + return; + } + InitDbData(db_, data, size); + BlockSync(); + } + + void InitAssets(const uint8_t* data, size_t size) + { + FuzzerData fuzzerData(data, size); + uint32_t len = fuzzerData.GetUInt32(); + for (size_t i = 0; i <= size; ++i) { + std::string nameStr = fuzzerData.GetString(len); + localAssets_.push_back(GenAsset(nameStr, std::to_string(data[0]))); + } + } + + void AssetChangeSync(const uint8_t* data, size_t size) + { + SetCloudDbSchema(delegate_); + if (size == 0) { + return; + } + InitAssets(data, size); + InitDbAsset(data, size); + BlockSync(); + } + + void RandomModeRemoveDeviceData(const uint8_t* data, size_t size) + { + if (size == 0) { + return; + } + SetCloudDbSchema(delegate_); + int64_t cloudCount = 10; + int64_t paddingSize = 10; + InsertCloudTableRecord(0, cloudCount, paddingSize, false); + BlockSync(); + auto mode = static_cast(data[0]); + LOGI("[RandomModeRemoveDeviceData] select mode %d", static_cast(mode)); + if (mode == DEFAULT) { + return; + } + std::string device = ""; + delegate_->RemoveDeviceData(device, mode); + } private: std::string testDir_; std::string storePath_; @@ -185,6 +361,7 @@ private: std::shared_ptr virtualCloudDb_; std::shared_ptr virtualAssetLoader_; std::shared_ptr mgr_; + Assets localAssets_; }; CloudSyncTest *g_cloudSyncTest = nullptr; @@ -215,6 +392,9 @@ void CombineTest(const uint8_t* data, size_t size) } g_cloudSyncTest->NormalSync(); g_cloudSyncTest->RandomModeSync(data, size); + g_cloudSyncTest->DataChangeSync(data, size); + g_cloudSyncTest->AssetChangeSync(data, size); + g_cloudSyncTest->RandomModeRemoveDeviceData(data, size); } } diff --git a/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/BUILD.gn b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/BUILD.gn new file mode 100644 index 00000000..cef00b41 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/BUILD.gn @@ -0,0 +1,113 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("../../../distributeddb.gni") + +##############################fuzztest########################################## +ohos_fuzztest("StorageFuzzTest") { + module_out_path = "kv_store/distributeddb" + + include_dirs = [ + "../../../test/fuzztest/common", + "../../../test/unittest/common/common", + "../../../test/unittest/common/syncer", + "../../../test/unittest/common/syncer/cloud", + "../../../test/unittest/common/storage", + "../../../include", + "../../../interfaces/include", + "../../../interfaces/include/cloud", + "../../../interfaces/include/relational", + "../../../interfaces/src", + "../../../interfaces/src/relational", + "../../../storage/include", + "../../../storage/src", + "../../../storage/src/cloud", + "../../../storage/src/multiver", + "../../../storage/src/operation", + "../../../storage/src/sqlite", + "../../../storage/src/sqlite/relational", + "../../../storage/src/upgrader", + "../../../common/include", + "../../../common/include/cloud", + "../../../common/include/relational", + "../../../common/src", + "../../../communicator/include", + "../../../communicator/src", + "../../../syncer/include", + "../../../syncer/src", + "../../../syncer/src/cloud", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + fuzz_config_file = "../storage_fuzzer" + + sources = distributeddb_src + sources += [ + "../../../test/fuzztest/common/distributeddb_tools_test.cpp", + "../../../test/fuzztest/common/fuzzer_data.cpp", + "../../../test/fuzztest/storage_fuzzer/storage_fuzzer.cpp", + "../../../test/unittest/common/common/distributeddb_data_generate_unit_test.cpp", + ] + + defines = [ + "SQLITE_ENABLE_SNAPSHOT", + "_LARGEFILE64_SOURCE", + "_FILE_OFFSET_BITS=64", + "SQLITE_HAS_CODEC", + "SQLITE_ENABLE_JSON1", + "USING_HILOG_LOGGER", + "USE_SQLITE_SYMBOLS", + "USING_DB_JSON_EXTRACT_AUTOMATICALLY", + "LOW_LEVEL_MEM_DEV", + "JSONCPP_USE_BUILDER", + "OMIT_FLATBUFFER", + "RELATIONAL_STORE", + "SQLITE_DISTRIBUTE_RELATIONAL", + "SQLITE_EXPORT_SYMBOLS", + "SQLITE_ENABLE_DROPTABLE_CALLBACK", + "OPENSSL_SUPPRESS_DEPRECATED", + ] + + deps = [ + "../../../../distributeddb:distributeddb", + "//third_party/jsoncpp:jsoncpp", + "//third_party/openssl:libcrypto_shared", + "//third_party/sqlite:sqlite", + "//third_party/zlib:shared_libz", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] +} + +############################################################################### + +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":StorageFuzzTest", + ] +} diff --git a/preferences/test/js/unittest/src/BUILD.gn b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/corpus/init similarity index 58% rename from preferences/test/js/unittest/src/BUILD.gn rename to kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/corpus/init index a4af7f05..e4ceac1b 100644 --- a/preferences/test/js/unittest/src/BUILD.gn +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/corpus/init @@ -1,4 +1,4 @@ -# 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 @@ -11,20 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/test.gni") - -module_output_path = "preferences/storage" - -ohos_js_unittest("StorageJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - - certificate_profile = - "//test/testfwk/developer_test/signature/openharmony_sx.p7b" -} - -group("unittest") { - testonly = true - deps = [ ":StorageJsTest" ] -} +FUZZ \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/project.xml b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/project.xml new file mode 100644 index 00000000..798d910c --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 30 + + 4096 + + diff --git a/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.cpp b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.cpp new file mode 100644 index 00000000..47bb2028 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.cpp @@ -0,0 +1,223 @@ +/* + * 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 "storage_fuzzer.h" + +#include "db_errno.h" +#include "distributeddb_data_generate_unit_test.h" +#include "relational_sync_able_storage.h" +#include "relational_store_instance.h" +#include "sqlite_relational_store.h" +#include "log_table_manager_factory.h" + +#include "cloud_db_types.h" +#include "distributeddb_tools_test.h" +#include "log_print.h" +#include "fuzzer_data.h" +#include "relational_store_delegate.h" +#include "relational_store_manager.h" +#include "runtime_config.h" +#include "storage_proxy.h" +#include "virtual_asset_loader.h" +#include "virtual_cloud_data_translate.h" +#include "virtual_cloud_db.h" + +namespace OHOS { +using namespace DistributedDB; +using namespace DistributedDBTest; +using namespace DistributedDBUnitTest; + +TableName TABLE_NAME_1 = "tableName1"; +const auto STORE_ID = "Relational_Store_ID"; +std::string TEST_DIR; +std::string STORE_PATH = "./g_store.db"; +DistributedDB::RelationalStoreManager g_mgr(APP_ID, USER_ID); +RelationalStoreDelegate *g_delegate = nullptr; +IRelationalStore *g_store = nullptr; +std::shared_ptr g_storageProxy = nullptr; + +class CloudMetaDataTest { +public: + void SetUp() + { + DistributedDBToolsTest::TestDirInit(TEST_DIR); + LOGD("Test dir is %s", TEST_DIR.c_str()); + CreateDB(); + int ret = g_mgr.OpenStore(STORE_PATH, STORE_ID, RelationalStoreDelegate::Option {}, g_delegate); + if (ret != DBStatus::OK) { + LOGE("can not open store"); + return; + } + if (g_delegate == nullptr) { + LOGE("unexpected g_delegate"); + return; + } + g_storageProxy = GetStorageProxy((ICloudSyncStorageInterface *) GetRelationalStore()); + } + + void TearDown() + { + if (g_delegate != nullptr) { + if (g_mgr.CloseStore(g_delegate) != DBStatus::OK) { + LOGE("Can not close store"); + return; + } + g_delegate = nullptr; + g_storageProxy = nullptr; + } + if (DistributedDBToolsTest::RemoveTestDbFiles(TEST_DIR) != 0) { + LOGE("rm test db files error."); + } + } + + void FuzzTest(const uint8_t* data, size_t size) + { + FuzzerData fuzzData(data, size); + if (!SetAndGetLocalWaterMark(TABLE_NAME_1, fuzzData.GetUInt64())) { + LOGE("Set and get local watermark unsuccess"); + return; + } + std::string cloudMark = fuzzData.GetString(size); + if (!SetAndGetCloudWaterMark(TABLE_NAME_1, cloudMark)) { + LOGE("Set and get cloud watermark unsuccess"); + return; + } + } + +private: + void CreateDB() + { + sqlite3 *db = nullptr; + int errCode = sqlite3_open(STORE_PATH.c_str(), &db); + if (errCode != SQLITE_OK) { + LOGE("open db failed:%d", errCode); + sqlite3_close(db); + return; + } + + const std::string sql = "PRAGMA journal_mode=WAL;"; + if (SQLiteUtils::ExecuteRawSQL(db, sql.c_str()) != E_OK) { + LOGE("can not execute sql"); + return; + } + sqlite3_close(db); + } + + void InitStoreProp(const std::string &storePath, const std::string &appId, const std::string &userId, + RelationalDBProperties &properties) + { + properties.SetStringProp(RelationalDBProperties::DATA_DIR, storePath); + properties.SetStringProp(RelationalDBProperties::APP_ID, appId); + properties.SetStringProp(RelationalDBProperties::USER_ID, userId); + properties.SetStringProp(RelationalDBProperties::STORE_ID, STORE_ID); + std::string identifier = userId + "-" + appId + "-" + STORE_ID; + std::string hashIdentifier = DBCommon::TransferHashString(identifier); + properties.SetStringProp(RelationalDBProperties::IDENTIFIER_DATA, hashIdentifier); + } + + const RelationalSyncAbleStorage *GetRelationalStore() + { + RelationalDBProperties properties; + InitStoreProp(STORE_PATH, APP_ID, USER_ID, properties); + int errCode = E_OK; + g_store = RelationalStoreInstance::GetDataBase(properties, errCode); + if (g_store == nullptr) { + LOGE("Get db failed:%d", errCode); + return nullptr; + } + return static_cast(g_store)->GetStorageEngine(); + } + + std::shared_ptr GetStorageProxy(ICloudSyncStorageInterface *store) + { + return StorageProxy::GetCloudDb(store); + } + + bool SetAndGetLocalWaterMark(TableName &tableName, Timestamp mark) + { + if (g_storageProxy->PutLocalWaterMark(tableName, mark) != E_OK) { + LOGE("Can not put local watermark"); + return false; + } + Timestamp retMark; + if (g_storageProxy->GetLocalWaterMark(tableName, retMark) != E_OK) { + LOGE("Can not get local watermark"); + return false; + } + if (retMark != mark) { + LOGE("watermark in not conformed to expectation"); + return false; + } + return true; + } + + bool SetAndGetCloudWaterMark(TableName &tableName, std::string &mark) + { + if (g_storageProxy->SetCloudWaterMark(tableName, mark) != E_OK) { + LOGE("Can not set cloud watermark"); + return false; + } + std::string retMark; + if (g_storageProxy->GetCloudWaterMark(tableName, retMark) != E_OK) { + LOGE("Can not get cloud watermark"); + return false; + } + if (retMark != mark) { + LOGE("watermark in not conformed to expectation"); + return false; + } + return true; + } +}; + +CloudMetaDataTest *g_cloudMetaDataTest = nullptr; + +void Setup() +{ + LOGI("Set up"); + g_cloudMetaDataTest = new(std::nothrow) CloudMetaDataTest(); + if (g_cloudMetaDataTest == nullptr) { + return; + } + g_cloudMetaDataTest->SetUp(); +} + +void TearDown() +{ + LOGI("Tear down"); + g_cloudMetaDataTest->TearDown(); + if (g_cloudMetaDataTest != nullptr) { + delete g_cloudMetaDataTest; + g_cloudMetaDataTest = nullptr; + } +} + +void CombineTest(const uint8_t* data, size_t size) +{ + if (g_cloudMetaDataTest == nullptr) { + return; + } + g_cloudMetaDataTest->FuzzTest(data, size); +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Setup(); + OHOS::CombineTest(data, size); + OHOS::TearDown(); + return 0; +} \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.h b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.h new file mode 100644 index 00000000..cbbefb49 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/storage_fuzzer/storage_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 STORAGE_FUZZER_H +#define STORAGE_FUZZER_H + +#define FUZZ_PROJECT_NAME "Storage_fuzzer" + +#endif // STORAGE_FUZZER_H \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp new file mode 100644 index 00000000..ed3807f2 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp @@ -0,0 +1,706 @@ +/* + * 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. + */ +#ifdef RELATIONAL_STORE +#include +#include +#include "cloud/cloud_storage_utils.h" +#include "cloud_db_constant.h" +#include "distributeddb_data_generate_unit_test.h" +#include "distributeddb_tools_unit_test.h" +#include "process_system_api_adapter_impl.h" +#include "relational_store_instance.h" +#include "relational_store_manager.h" +#include "runtime_config.h" +#include "sqlite_relational_store.h" +#include "sqlite_relational_utils.h" +#include "store_observer.h" +#include "time_helper.h" +#include "virtual_asset_loader.h" +#include "virtual_cloud_data_translate.h" +#include "virtual_cloud_db.h" +#include "mock_asset_loader.h" + +using namespace testing::ext; +using namespace DistributedDB; +using namespace DistributedDBUnitTest; +using namespace std; + +namespace { + string g_storeID = "Relational_Store_SYNC"; + const string g_tableName1 = "worker1"; + const string g_tableName2 = "worker2"; + const string g_tableName3 = "worker3"; + const string g_tableName4 = "worker4"; + const string DEVICE_CLOUD = "cloud_dev"; + const string DB_SUFFIX = ".db"; + const int64_t g_syncWaitTime = 60; + const int g_arrayHalfSub = 2; + int g_syncIndex = 0; + string g_testDir; + string g_storePath; + std::mutex g_processMutex; + std::condition_variable g_processCondition; + std::shared_ptr g_virtualCloudDb; + std::shared_ptr g_virtualAssetLoader; + DistributedDB::RelationalStoreManager g_mgr(APP_ID, USER_ID); + RelationalStoreObserverUnitTest *g_observer = nullptr; + RelationalStoreDelegate *g_delegate = nullptr; + SyncProcess g_syncProcess; + using CloudSyncStatusCallback = std::function &onProcess)>; + const std::string CREATE_LOCAL_TABLE_SQL = + "CREATE TABLE IF NOT EXISTS " + g_tableName1 + "(" \ + "name TEXT PRIMARY KEY," \ + "height REAL ," \ + "married BOOLEAN ," \ + "photo BLOB NOT NULL," \ + "assert BLOB," \ + "age INT);"; + const std::string INTEGER_PRIMARY_KEY_TABLE_SQL = + "CREATE TABLE IF NOT EXISTS " + g_tableName2 + "(" \ + "id INTEGER PRIMARY KEY," \ + "name TEXT ," \ + "height REAL ," \ + "photo BLOB ," \ + "asserts BLOB," \ + "age INT);"; + const std::string DROP_INTEGER_PRIMARY_KEY_TABLE_SQL = "DROP TABLE " + g_tableName2 + ";"; + const std::string CREATE_LOCAL_TABLE_WITHOUT_PRIMARY_KEY_SQL = + "CREATE TABLE IF NOT EXISTS " + g_tableName3 + "(" \ + "name TEXT," \ + "height REAL ," \ + "married BOOLEAN ," \ + "photo BLOB NOT NULL," \ + "assert BLOB," \ + "age INT);"; + const std::string INTEGER_PRIMARY_KEY_TABLE_SQL_WRONG_SYNC_MODE = + "CREATE TABLE IF NOT EXISTS " + g_tableName4 + "(" \ + "id INTEGER PRIMARY KEY," \ + "name TEXT ," \ + "height REAL ," \ + "photo BLOB ," \ + "asserts BLOB," \ + "age INT);"; + const std::vector g_cloudFiled1 = { + {"name", TYPE_INDEX, true}, {"height", TYPE_INDEX}, + {"married", TYPE_INDEX}, {"photo", TYPE_INDEX, false, false}, + {"assert", TYPE_INDEX}, {"age", TYPE_INDEX} + }; + const std::vector g_invalidCloudFiled1 = { + {"name", TYPE_INDEX, true}, {"height", TYPE_INDEX}, + {"married", TYPE_INDEX}, {"photo", TYPE_INDEX, false, false}, + {"assert", TYPE_INDEX}, {"age", TYPE_INDEX} + }; + const std::vector g_cloudFiled2 = { + {"id", TYPE_INDEX, true}, {"name", TYPE_INDEX}, + {"height", TYPE_INDEX}, {"photo", TYPE_INDEX}, + {"asserts", TYPE_INDEX}, {"age", TYPE_INDEX} + }; + const std::vector g_cloudFiledWithOutPrimaryKey3 = { + {"name", TYPE_INDEX, false, true}, {"height", TYPE_INDEX}, + {"married", TYPE_INDEX}, {"photo", TYPE_INDEX, false, false}, + {"assert", TYPE_INDEX}, {"age", TYPE_INDEX} + }; + const std::vector g_tables = {g_tableName1, g_tableName2}; + const std::vector g_tablesPKey = {g_cloudFiled1[0].colName, g_cloudFiled2[0].colName}; + const std::vector g_prefix = {"Local", ""}; + const Asset g_localAsset = { + .version = 1, .name = "Phone", .assetId = "0", .subpath = "/local/sync", .uri = "/local/sync", + .modifyTime = "123456", .createTime = "", .size = "256", .hash = "ASE" + }; + const Asset g_cloudAsset = { + .version = 2, .name = "Phone", .assetId = "0", .subpath = "/local/sync", .uri = "/cloud/sync", + .modifyTime = "123456", .createTime = "0", .size = "1024", .hash = "DEC" + }; + + void CreateUserDBAndTable(sqlite3 *&db) + { + EXPECT_EQ(RelationalTestUtils::ExecSql(db, "PRAGMA journal_mode=WAL;"), SQLITE_OK); + EXPECT_EQ(RelationalTestUtils::ExecSql(db, CREATE_LOCAL_TABLE_SQL), SQLITE_OK); + EXPECT_EQ(RelationalTestUtils::ExecSql(db, INTEGER_PRIMARY_KEY_TABLE_SQL), SQLITE_OK); + EXPECT_EQ(RelationalTestUtils::ExecSql(db, CREATE_LOCAL_TABLE_WITHOUT_PRIMARY_KEY_SQL), SQLITE_OK); + } + + void InsertUserTableRecord(sqlite3 *&db, int64_t begin, int64_t count, int64_t photoSize, bool assetIsNull) + { + std::string photo(photoSize, 'v'); + int errCode; + std::vector assetBlob; + for (int64_t i = begin; i < begin + count; ++i) { + Asset asset = g_localAsset; + asset.name = asset.name + std::to_string(i); + RuntimeContext::GetInstance()->AssetToBlob(asset, assetBlob); + string sql = "INSERT OR REPLACE INTO " + g_tableName1 + + " (name, height, married, photo, assert, age) VALUES ('Local" + std::to_string(i) + + "', '175.8', '0', '" + photo + "', ? , '18');"; + sqlite3_stmt *stmt = nullptr; + ASSERT_EQ(SQLiteUtils::GetStatement(db, sql, stmt), E_OK); + if (assetIsNull) { + ASSERT_EQ(sqlite3_bind_null(stmt, 1), SQLITE_OK); + } else { + ASSERT_EQ(SQLiteUtils::BindBlobToStatement(stmt, 1, assetBlob, false), E_OK); + } + EXPECT_EQ(SQLiteUtils::StepWithRetry(stmt), SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)); + SQLiteUtils::ResetStatement(stmt, true, errCode); + } + for (int64_t i = begin; i < begin + count; ++i) { + std::vector assets; + Asset asset = g_localAsset; + asset.name = g_localAsset.name + std::to_string(i); + assets.push_back(asset); + asset.name = g_localAsset.name + std::to_string(i + 1); + assets.push_back(asset); + RuntimeContext::GetInstance()->AssetsToBlob(assets, assetBlob); + string sql = "INSERT OR REPLACE INTO " + g_tableName2 + + " (id, name, height, photo, asserts, age) VALUES ('" + std::to_string(i) + "', 'Local" + + std::to_string(i) + "', '155.10', '"+ photo + "', ? , '21');"; + sqlite3_stmt *stmt = nullptr; + ASSERT_EQ(SQLiteUtils::GetStatement(db, sql, stmt), E_OK); + if (assetIsNull) { + ASSERT_EQ(sqlite3_bind_null(stmt, 1), E_OK); + } else { + ASSERT_EQ(SQLiteUtils::BindBlobToStatement(stmt, 1, assetBlob, false), E_OK); + } + EXPECT_EQ(SQLiteUtils::StepWithRetry(stmt), SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)); + SQLiteUtils::ResetStatement(stmt, true, errCode); + } + LOGD("insert user record worker1[primary key]:[Local%" PRId64 " - Local%" PRId64 + ") , worker2[primary key]:[%" PRId64 "- %" PRId64")", begin, count, begin, count); + } + + void InsertCloudTableRecord(int64_t begin, int64_t count, int64_t photoSize, bool assetIsNull) + { + std::vector photo(photoSize, 'v'); + std::vector record1; + std::vector extend1; + std::vector record2; + std::vector extend2; + Timestamp now = TimeHelper::GetSysCurrentTime(); + for (int64_t i = begin; i < begin + count; ++i) { + VBucket data; + data.insert_or_assign("name", "Cloud" + std::to_string(i)); + data.insert_or_assign("height", 166.0); // 166.0 is random double value + data.insert_or_assign("married", false); + data.insert_or_assign("photo", photo); + data.insert_or_assign("age", 13L); + Asset asset = g_cloudAsset; + asset.name = asset.name + std::to_string(i); + assetIsNull ? data.insert_or_assign("assert", Nil()) : data.insert_or_assign("assert", asset); + record1.push_back(data); + VBucket log; + log.insert_or_assign(CloudDbConstant::CREATE_FIELD, (int64_t)now / CloudDbConstant::TEN_THOUSAND + i); + log.insert_or_assign(CloudDbConstant::MODIFY_FIELD, (int64_t)now / CloudDbConstant::TEN_THOUSAND + i); + log.insert_or_assign(CloudDbConstant::DELETE_FIELD, false); + extend1.push_back(log); + + std::vector assets; + data.insert_or_assign("id", i); + data.insert_or_assign("height", 180.3); // 180.3 is random double value + for (int64_t j = i; j <= i + 2; j++) { // 2 extra num + asset.name = g_cloudAsset.name + std::to_string(j); + assets.push_back(asset); + } + data.erase("assert"); + data.erase("married"); + assetIsNull ? data.insert_or_assign("asserts", Nil()) : data.insert_or_assign("asserts", assets); + record2.push_back(data); + extend2.push_back(log); + } + ASSERT_EQ(g_virtualCloudDb->BatchInsert(g_tableName1, std::move(record1), extend1), DBStatus::OK); + ASSERT_EQ(g_virtualCloudDb->BatchInsert(g_tableName2, std::move(record2), extend2), DBStatus::OK); + LOGD("insert cloud record worker1[primary key]:[cloud%" PRId64 " - cloud%" PRId64 + ") , worker2[primary key]:[%" PRId64 "- %" PRId64")", begin, count, begin, count); + std::this_thread::sleep_for(std::chrono::milliseconds(count)); + } + + void GetCloudDbSchema(DataBaseSchema &dataBaseSchema) + { + TableSchema tableSchema1 = { + .name = g_tableName1, + .fields = g_cloudFiled1 + }; + TableSchema tableSchema2 = { + .name = g_tableName2, + .fields = g_cloudFiled2 + }; + TableSchema tableSchemaWithOutPrimaryKey = { + .name = g_tableName3, + .fields = g_cloudFiledWithOutPrimaryKey3 + }; + TableSchema tableSchema4 = { + .name = g_tableName4, + .fields = g_cloudFiled2 + }; + dataBaseSchema.tables.push_back(tableSchema1); + dataBaseSchema.tables.push_back(tableSchema2); + dataBaseSchema.tables.push_back(tableSchemaWithOutPrimaryKey); + dataBaseSchema.tables.push_back(tableSchema4); + } + + int QueryCountCallback(void *data, int count, char **colValue, char **colName) + { + if (count != 1) { + return 0; + } + auto expectCount = reinterpret_cast(data); + EXPECT_EQ(strtol(colValue[0], nullptr, 10), expectCount); // 10: decimal + return 0; + } + + void CheckCloudRecordNum(sqlite3 *&db, std::vector tableList, std::vector countList) + { + int i = 0; + for (const auto &tableName: tableList) { + std::string sql = "select count(*) from " + DBCommon::GetLogTableName(tableName) + + " where device = 'cloud'" + " and cloud_gid is not null and cloud_gid != '' and flag & 0x2 = 0;"; + EXPECT_EQ(sqlite3_exec(db, sql.c_str(), QueryCountCallback, + reinterpret_cast(countList[i]), nullptr), SQLITE_OK); + i++; + } + } + + void CheckCleanLogNum(sqlite3 *&db, const std::vector tableList, int count) + { + for (const auto &tableName: tableList) { + std::string sql1 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + + " where device = 'cloud';"; + EXPECT_EQ(sqlite3_exec(db, sql1.c_str(), QueryCountCallback, + reinterpret_cast(count), nullptr), SQLITE_OK); + std::string sql2 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + + " where cloud_gid " + " is not null and cloud_gid != '';"; + EXPECT_EQ(sqlite3_exec(db, sql2.c_str(), QueryCountCallback, + reinterpret_cast(count), nullptr), SQLITE_OK); + std::string sql3 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + + " where flag & 0x02 = 0;"; + EXPECT_EQ(sqlite3_exec(db, sql3.c_str(), QueryCountCallback, + reinterpret_cast(count), nullptr), SQLITE_OK); + } + } + + void CheckCleanDataAndLogNum(sqlite3 *&db, const std::vector tableList, int count, + std::vector localNum) + { + int i = 0; + for (const auto &tableName: tableList) { + std::string sql1 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + + " where device = 'cloud';"; + EXPECT_EQ(sqlite3_exec(db, sql1.c_str(), QueryCountCallback, + reinterpret_cast(count), nullptr), SQLITE_OK); + std::string sql2 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + " where cloud_gid " + " is not null and cloud_gid != '';"; + EXPECT_EQ(sqlite3_exec(db, sql2.c_str(), QueryCountCallback, + reinterpret_cast(count), nullptr), SQLITE_OK); + std::string sql3 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + + " where flag & 0x02 = 0;"; + EXPECT_EQ(sqlite3_exec(db, sql3.c_str(), QueryCountCallback, + reinterpret_cast(count), nullptr), SQLITE_OK); + std::string local_sql = "select count(*) from " + tableName +";"; + EXPECT_EQ(sqlite3_exec(db, local_sql.c_str(), QueryCountCallback, + reinterpret_cast(localNum[i]), nullptr), SQLITE_OK); + i++; + } + } + + void InitProcessForCleanCloudData1(const uint32_t &cloudCount, std::vector &expectProcess) + { + // cloudCount also means data count in one batch + expectProcess.clear(); + std::vector infos; + uint32_t index = 1; + infos.push_back(TableProcessInfo{ + FINISHED, {index, cloudCount, cloudCount, 0}, {0, 0, 0, 0} + }); + infos.push_back(TableProcessInfo{ + PREPARED, {0, 0, 0, 0}, {0, 0, 0, 0} + }); + + infos.push_back(TableProcessInfo{ + FINISHED, {index, cloudCount, cloudCount, 0}, {0, 0, 0, 0} + }); + infos.push_back(TableProcessInfo{ + FINISHED, {index, cloudCount, cloudCount, 0}, {0, 0, 0, 0} + }); + + for (size_t i = 0; i < infos.size() / g_arrayHalfSub; ++i) { + SyncProcess syncProcess; + syncProcess.errCode = OK; + syncProcess.process = i == infos.size() ? FINISHED : PROCESSING; + syncProcess.tableProcess.insert_or_assign(g_tables[0], std::move(infos[g_arrayHalfSub * i])); + syncProcess.tableProcess.insert_or_assign(g_tables[1], std::move(infos[g_arrayHalfSub * i + 1])); + expectProcess.push_back(syncProcess); + } + } + + void GetCallback(SyncProcess &syncProcess, CloudSyncStatusCallback &callback, + std::vector &expectProcess) + { + g_syncIndex = 0; + callback = [&syncProcess, &expectProcess](const std::map &process) { + LOGI("devices size = %d", process.size()); + ASSERT_EQ(process.size(), 1u); + syncProcess = std::move(process.begin()->second); + ASSERT_EQ(process.begin()->first, DEVICE_CLOUD); + ASSERT_NE(syncProcess.tableProcess.empty(), true); + LOGI("current sync process status:%d, db status:%d ", syncProcess.process, syncProcess.errCode); + std::for_each(g_tables.begin(), g_tables.end(), [&](const auto &item) { + auto table1 = syncProcess.tableProcess.find(item); + if (table1 != syncProcess.tableProcess.end()) { + LOGI("table[%s], table process status:%d, [downloadInfo](batchIndex:%u, total:%u, successCount:%u, " + "failCount:%u) [uploadInfo](batchIndex:%u, total:%u, successCount:%u,failCount:%u", + item.c_str(), table1->second.process, table1->second.downLoadInfo.batchIndex, + table1->second.downLoadInfo.total, table1->second.downLoadInfo.successCount, + table1->second.downLoadInfo.failCount, table1->second.upLoadInfo.batchIndex, + table1->second.upLoadInfo.total, table1->second.upLoadInfo.successCount, + table1->second.upLoadInfo.failCount); + } + }); + if (expectProcess.empty()) { + if (syncProcess.process == FINISHED) { + g_processCondition.notify_one(); + } + return; + } + ASSERT_LE(static_cast(g_syncIndex), expectProcess.size()); + for (size_t i = 0; i < g_tables.size(); ++i) { + SyncProcess head = expectProcess[g_syncIndex]; + for (auto &expect : head.tableProcess) { + auto real = syncProcess.tableProcess.find(expect.first); + ASSERT_NE(real, syncProcess.tableProcess.end()); + EXPECT_EQ(expect.second.process, real->second.process); + EXPECT_EQ(expect.second.downLoadInfo.batchIndex, real->second.downLoadInfo.batchIndex); + EXPECT_EQ(expect.second.downLoadInfo.total, real->second.downLoadInfo.total); + EXPECT_EQ(expect.second.downLoadInfo.successCount, real->second.downLoadInfo.successCount); + EXPECT_EQ(expect.second.downLoadInfo.failCount, real->second.downLoadInfo.failCount); + EXPECT_EQ(expect.second.upLoadInfo.batchIndex, real->second.upLoadInfo.batchIndex); + EXPECT_EQ(expect.second.upLoadInfo.total, real->second.upLoadInfo.total); + EXPECT_EQ(expect.second.upLoadInfo.successCount, real->second.upLoadInfo.successCount); + EXPECT_EQ(expect.second.upLoadInfo.failCount, real->second.upLoadInfo.failCount); + } + } + g_syncIndex++; + if (syncProcess.process == FINISHED) { + g_processCondition.notify_one(); + } + }; + } + + void WaitForSyncFinish(SyncProcess &syncProcess, const int64_t &waitTime) + { + std::unique_lock lock(g_processMutex); + bool result = g_processCondition.wait_for(lock, std::chrono::seconds(waitTime), [&syncProcess]() { + return syncProcess.process == FINISHED; + }); + ASSERT_EQ(result, true); + LOGD("-------------------sync end--------------"); + } + + void CloseDb() + { + delete g_observer; + g_virtualCloudDb = nullptr; + if (g_delegate != nullptr) { + EXPECT_EQ(g_mgr.CloseStore(g_delegate), DBStatus::OK); + g_delegate = nullptr; + } + } + + class DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest : public testing::Test { + public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + protected: + sqlite3 *db = nullptr; + }; + + void DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest::SetUpTestCase(void) + { + DistributedDBToolsUnitTest::TestDirInit(g_testDir); + g_storePath = g_testDir + "/" + g_storeID + DB_SUFFIX; + LOGI("The test db is:%s", g_testDir.c_str()); + RuntimeConfig::SetCloudTranslate(std::make_shared()); + } + + void DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest::TearDownTestCase(void) + {} + + void DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest::SetUp(void) + { + if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) { + LOGE("rm test db files error."); + } + DistributedDBToolsUnitTest::PrintTestCaseInfo(); + LOGD("Test dir is %s", g_testDir.c_str()); + db = RelationalTestUtils::CreateDataBase(g_storePath); + ASSERT_NE(db, nullptr); + CreateUserDBAndTable(db); + g_observer = new (std::nothrow) RelationalStoreObserverUnitTest(); + ASSERT_NE(g_observer, nullptr); + ASSERT_EQ(g_mgr.OpenStore(g_storePath, g_storeID, RelationalStoreDelegate::Option { .observer = g_observer }, + g_delegate), DBStatus::OK); + ASSERT_NE(g_delegate, nullptr); + ASSERT_EQ(g_delegate->CreateDistributedTable(g_tableName1, CLOUD_COOPERATION), DBStatus::OK); + ASSERT_EQ(g_delegate->CreateDistributedTable(g_tableName2, CLOUD_COOPERATION), DBStatus::OK); + ASSERT_EQ(g_delegate->CreateDistributedTable(g_tableName3, CLOUD_COOPERATION), DBStatus::OK); + g_virtualCloudDb = make_shared(); + g_virtualAssetLoader = make_shared(); + g_syncProcess = {}; + ASSERT_EQ(g_delegate->SetCloudDB(g_virtualCloudDb), DBStatus::OK); + ASSERT_EQ(g_delegate->SetIAssetLoader(g_virtualAssetLoader), DBStatus::OK); + // sync before setting cloud db schema,it should return SCHEMA_MISMATCH + Query query = Query::Select().FromTable(g_tables); + CloudSyncStatusCallback callback; + ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_MERGE, query, callback, g_syncWaitTime), + DBStatus::SCHEMA_MISMATCH); + DataBaseSchema dataBaseSchema; + GetCloudDbSchema(dataBaseSchema); + ASSERT_EQ(g_delegate->SetCloudDbSchema(dataBaseSchema), DBStatus::OK); + } + + void DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest::TearDown(void) + { + EXPECT_EQ(sqlite3_close_v2(db), SQLITE_OK); + if (DistributedDBToolsUnitTest::RemoveTestDbFiles(g_testDir) != 0) { + LOGE("rm test db files error."); + } + } + +/* + * @tc.name: CleanCloudDataTest001 + * @tc.desc: Test FLAG_ONLY mode of RemoveDeviceData, and invalid mode else. + * @tc.type: FUNC + * @tc.require: + * @tc.author: huangboxin + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest, CleanCloudDataTest001, TestSize.Level0) +{ + int64_t paddingSize = 10; + int localCount = 10; + int cloudCount = 20; + InsertCloudTableRecord(0, cloudCount, paddingSize, false); + InsertUserTableRecord(db, 0, localCount, paddingSize, false); + Query query = Query::Select().FromTable(g_tables); + std::vector expectProcess; + InitProcessForCleanCloudData1(cloudCount, expectProcess); + CloudSyncStatusCallback callback; + GetCallback(g_syncProcess, callback, expectProcess); + ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback, g_syncWaitTime), + DBStatus::OK); + WaitForSyncFinish(g_syncProcess, g_syncWaitTime); + std::string device = ""; + CheckCloudRecordNum(db, g_tables, {20, 20}); + ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_ONLY), DBStatus::OK); + CheckCleanLogNum(db, g_tables, 0); + + ASSERT_EQ(g_delegate->RemoveDeviceData(device, ClearMode(BUTT + 1)), DBStatus::INVALID_ARGS); + ASSERT_EQ(g_delegate->RemoveDeviceData(device, ClearMode(-1)), DBStatus::INVALID_ARGS); + + CloseDb(); +} + +/* + * @tc.name: CleanCloudDataTest002 + * @tc.desc: Test FLAG_AND_DATA mode of RemoveDeviceData + * @tc.type: FUNC + * @tc.require: + * @tc.author: huangboxin + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest, CleanCloudDataTest002, TestSize.Level0) +{ + int64_t paddingSize = 10; + int localCount = 10; + int cloudCount = 20; + InsertCloudTableRecord(0, cloudCount, paddingSize, false); + InsertUserTableRecord(db, 0, localCount, paddingSize, false); + Query query = Query::Select().FromTable(g_tables); + std::vector expectProcess; + InitProcessForCleanCloudData1(cloudCount, expectProcess); + CloudSyncStatusCallback callback; + GetCallback(g_syncProcess, callback, expectProcess); + ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback, g_syncWaitTime), + DBStatus::OK); + WaitForSyncFinish(g_syncProcess, g_syncWaitTime); + std::string device = ""; + CheckCloudRecordNum(db, g_tables, {20, 20}); // 20 means cloud data num + ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_AND_DATA), DBStatus::OK); + CheckCleanDataAndLogNum(db, g_tables, 0, {localCount, 0}); + CloseDb(); +} + +/* + * @tc.name: CleanCloudDataTest003 + * @tc.desc: Test FLAG_ONLY mode of RemoveDeviceData concurrently with Sync + * @tc.type: FUNC + * @tc.require: + * @tc.author: huangboxin + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest, CleanCloudDataTest003, TestSize.Level0) +{ + /** + * @tc.steps: step1. make data: 10 records on local and 20 records on cloud + */ + int64_t paddingSize = 10; + int localCount = 10; + int cloudCount = 20; + InsertCloudTableRecord(0, cloudCount, paddingSize, false); + InsertUserTableRecord(db, 0, localCount, paddingSize, false); + /** + * @tc.steps: step2. call Sync with cloud force pull strategy, and after that, local will has 20 records. + */ + Query query = Query::Select().FromTable(g_tables); + std::vector expectProcess; + InitProcessForCleanCloudData1(cloudCount, expectProcess); + CloudSyncStatusCallback callback; + GetCallback(g_syncProcess, callback, expectProcess); + ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback, g_syncWaitTime), + DBStatus::OK); + WaitForSyncFinish(g_syncProcess, g_syncWaitTime); + CheckCloudRecordNum(db, g_tables, {20, 20}); // 20 means cloud data num + + /** + * @tc.steps: step3. insert 10 records into local, so local will has 20 local records and 20 cloud records. + */ + InsertUserTableRecord(db, 21, localCount, paddingSize, false); // 21 means insert start index + /** + * @tc.steps: step4. call RemoveDeviceData synchronize with Sync with cloud force push strategy. + */ + g_syncProcess = {}; + std::vector expectProcess2; + InitProcessForCleanCloudData1(cloudCount, expectProcess2); + CloudSyncStatusCallback callback2; + GetCallback(g_syncProcess, callback2, expectProcess2); + std::string device = ""; + + std::thread thread1([&]() { + ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_AND_DATA), DBStatus::OK); + }); + std::thread thread2([&]() { + ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback2, g_syncWaitTime), + DBStatus::OK); + LOGD("-------------------sync end--------------"); + }); + thread1.join(); + thread2.join(); + WaitForSyncFinish(g_syncProcess, g_syncWaitTime); + CheckCleanLogNum(db, g_tables, 20); + LOGD("================================== test clean cloud data 003 end ==================================="); + CloseDb(); +} + +static void InitGetCloudSyncTaskCountTest001(sqlite3 *&db) +{ + int64_t localCount = 20; + int64_t cloudCount = 10; + int64_t paddingSize = 100; + InsertUserTableRecord(db, 0, localCount, paddingSize, false); + InsertCloudTableRecord(0, cloudCount, paddingSize, false); +} +/* + * @tc.name: GetCloudSyncTaskCountTest001 + * @tc.desc: Test FLAG_ONLY mode of RemoveDeviceData concurrently with Sync + * @tc.type: FUNC + * @tc.require: + * @tc.author: huangboxin + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest, GetCloudSyncTaskCountTest001, TestSize.Level0) +{ + InitGetCloudSyncTaskCountTest001(db); + Query query = Query::Select().FromTable(g_tables); + std::mutex dataMutex1, dataMutex2; + std::condition_variable cv1, cv2; + bool finish1 = false, finish2 = false; + /** + * @tc.steps: step1. Call Sync once. + * @tc.expected: OK. + */ + CloudSyncStatusCallback callback1 = [&dataMutex1, &cv1, &finish1]( + const std::map &process) { + std::map syncProcess; + { + std::lock_guard autoLock(dataMutex1); + syncProcess = process; + if (syncProcess[DEVICE_CLOUD].process == FINISHED) { + finish1 = true; + } + } + cv1.notify_one(); + }; + /** + * @tc.steps: step2. Call Sync twice. + * @tc.expected: OK. + */ + ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_MERGE, query, callback1, g_syncWaitTime), DBStatus::OK); + + CloudSyncStatusCallback callback2 = [&dataMutex2, &cv2, &finish2]( + const std::map &process) { + std::map syncProcess; + { + std::lock_guard autoLock(dataMutex2); + syncProcess = process; + if (syncProcess[DEVICE_CLOUD].process == FINISHED) { + finish2 = true; + } + } + cv2.notify_one(); + }; + ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_MERGE, query, callback2, g_syncWaitTime), DBStatus::OK); + /** + * @tc.steps: step3. Call Get Cloud Sync Task Count + * @tc.expected: OK. + */ + EXPECT_EQ(g_delegate->GetCloudSyncTaskCount(), 2); // 2 is task count + /** + * @tc.steps: step3. Wait For Sync Task Finished + * @tc.expected: OK. + */ + { + std::unique_lock uniqueLock(dataMutex1); + cv1.wait(uniqueLock, [&finish1] { + return finish1; + }); + } + { + std::unique_lock uniqueLock(dataMutex2); + cv2.wait(uniqueLock, [&finish2] { + return finish2; + }); + } + CloseDb(); +} + +/* + * @tc.name: CleanCloudDataTest004 + * @tc.desc: Test RemoveDeviceData when cloudSchema doesn't have local table + * @tc.type: FUNC + * @tc.require: + * @tc.author: huangboxin + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest, CleanCloudDataTest004, TestSize.Level0) +{ + DataBaseSchema dataBaseSchema; + TableSchema tableSchema1 = { + .name = "table_not_existed", + .fields = g_cloudFiled1 + }; + dataBaseSchema.tables.push_back(tableSchema1); + GetCloudDbSchema(dataBaseSchema); + ASSERT_EQ(g_delegate->SetCloudDbSchema(dataBaseSchema), DBStatus::OK); + std::string device = ""; + ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_AND_DATA), DBStatus::OK); + CloseDb(); +} + +} +#endif // RELATIONAL_STORE \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp index 369faebd..f47f01bd 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_test.cpp @@ -1133,12 +1133,15 @@ HWTEST_F(DistributedDBInterfacesRelationalTest, RelationalRemoveDeviceDataTest00 * @tc.steps:step3. Remove device data * @tc.expected: step3. ok */ + EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_A"), DISTRIBUTED_SCHEMA_NOT_FOUND); + EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_D"), DISTRIBUTED_SCHEMA_NOT_FOUND); + EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_A", "sync_data"), DISTRIBUTED_SCHEMA_NOT_FOUND); EXPECT_EQ(delegate->CreateDistributedTable("sync_data"), OK); EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_A"), OK); EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_B"), OK); EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_C", "sync_data"), OK); EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_D"), OK); - EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_A", "sync_data_A"), OK); + EXPECT_EQ(delegate->RemoveDeviceData("DEVICE_A", "sync_data_A"), DISTRIBUTED_SCHEMA_NOT_FOUND); /** * @tc.steps:step4. Remove device data with invalid args diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_check_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_check_sync_test.cpp new file mode 100644 index 00000000..831183c4 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_check_sync_test.cpp @@ -0,0 +1,201 @@ +/* + * 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. + */ +#ifdef RELATIONAL_STORE +#include +#include "cloud_db_types.h" +#include "distributeddb_data_generate_unit_test.h" +#include "log_print.h" +#include "relational_store_delegate.h" +#include "relational_store_manager.h" +#include "runtime_config.h" +#include "virtual_asset_loader.h" +#include "virtual_cloud_data_translate.h" +#include "virtual_cloud_db.h" +namespace { +using namespace testing::ext; +using namespace DistributedDB; +using namespace DistributedDBUnitTest; +const char *g_createSQL = + "CREATE TABLE IF NOT EXISTS DistributedDBCloudCheckSyncTest(" \ + "id TEXT PRIMARY KEY," \ + "name TEXT," \ + "height REAL ," \ + "photo BLOB," \ + "age INT);"; +const int64_t g_syncWaitTime = 60; + +void CreateUserDBAndTable(sqlite3 *&db) +{ + EXPECT_EQ(RelationalTestUtils::ExecSql(db, "PRAGMA journal_mode=WAL;"), SQLITE_OK); + EXPECT_EQ(RelationalTestUtils::ExecSql(db, g_createSQL), SQLITE_OK); +} + +void BlockSync(const Query &query, RelationalStoreDelegate *delegate) +{ + std::mutex dataMutex; + std::condition_variable cv; + bool finish = false; + auto callback = [&cv, &dataMutex, &finish](const std::map &process) { + for (const auto &item: process) { + if (item.second.process == DistributedDB::FINISHED) { + { + std::lock_guard autoLock(dataMutex); + finish = true; + } + cv.notify_one(); + } + } + }; + ASSERT_EQ(delegate->Sync({ "CLOUD" }, SYNC_MODE_CLOUD_MERGE, query, callback, g_syncWaitTime), OK); + std::unique_lock uniqueLock(dataMutex); + cv.wait(uniqueLock, [&finish]() { + return finish; + }); +} + +class DistributedDBCloudCheckSyncTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +protected: + void InitTestDir(); + DataBaseSchema GetSchema(); + void CloseDb(); + void InsertUserTableRecord(int64_t recordCounts, int64_t begin = 0); + std::string testDir_; + std::string storePath_; + sqlite3 *db_ = nullptr; + RelationalStoreDelegate *delegate_ = nullptr; + std::shared_ptr virtualCloudDb_ = nullptr; + std::shared_ptr virtualAssetLoader_ = nullptr; + std::shared_ptr mgr_ = nullptr; + std::string tableName_ = "DistributedDBCloudCheckSyncTest"; +}; + +void DistributedDBCloudCheckSyncTest::SetUpTestCase() +{ + RuntimeConfig::SetCloudTranslate(std::make_shared()); +} + +void DistributedDBCloudCheckSyncTest::TearDownTestCase() +{} + +void DistributedDBCloudCheckSyncTest::SetUp() +{ + DistributedDBToolsUnitTest::PrintTestCaseInfo(); + InitTestDir(); + if (DistributedDBToolsUnitTest::RemoveTestDbFiles(testDir_) != 0) { + LOGE("rm test db files error."); + } + DistributedDBToolsUnitTest::PrintTestCaseInfo(); + LOGD("Test dir is %s", testDir_.c_str()); + db_ = RelationalTestUtils::CreateDataBase(storePath_); + ASSERT_NE(db_, nullptr); + CreateUserDBAndTable(db_); + mgr_ = std::make_shared(APP_ID, USER_ID); + RelationalStoreDelegate::Option option; + ASSERT_EQ(mgr_->OpenStore(storePath_, STORE_ID_1, option, delegate_), DBStatus::OK); + ASSERT_NE(delegate_, nullptr); + ASSERT_EQ(delegate_->CreateDistributedTable(tableName_, CLOUD_COOPERATION), DBStatus::OK); + virtualCloudDb_ = std::make_shared(); + virtualAssetLoader_ = std::make_shared(); + ASSERT_EQ(delegate_->SetCloudDB(virtualCloudDb_), DBStatus::OK); + ASSERT_EQ(delegate_->SetIAssetLoader(virtualAssetLoader_), DBStatus::OK); + DataBaseSchema dataBaseSchema = GetSchema(); + ASSERT_EQ(delegate_->SetCloudDbSchema(dataBaseSchema), DBStatus::OK); +} + +void DistributedDBCloudCheckSyncTest::TearDown() +{ + CloseDb(); + EXPECT_EQ(sqlite3_close_v2(db_), SQLITE_OK); + if (DistributedDBToolsUnitTest::RemoveTestDbFiles(testDir_) != 0) { + LOGE("rm test db files error."); + } +} + +void DistributedDBCloudCheckSyncTest::InitTestDir() +{ + if (!testDir_.empty()) { + return; + } + DistributedDBToolsUnitTest::TestDirInit(testDir_); + storePath_ = testDir_ + "/" + STORE_ID_1 + ".db"; + LOGI("The test db is:%s", testDir_.c_str()); +} + +DataBaseSchema DistributedDBCloudCheckSyncTest::GetSchema() +{ + DataBaseSchema schema; + TableSchema tableSchema; + tableSchema.name = tableName_; + tableSchema.fields = { + {"id", TYPE_INDEX, true}, {"name", TYPE_INDEX}, {"height", TYPE_INDEX}, + {"photo", TYPE_INDEX}, {"age", TYPE_INDEX} + }; + schema.tables.push_back(tableSchema); + return schema; +} + +void DistributedDBCloudCheckSyncTest::CloseDb() +{ + virtualCloudDb_ = nullptr; + EXPECT_EQ(mgr_->CloseStore(delegate_), DBStatus::OK); + delegate_ = nullptr; + mgr_ = nullptr; +} + +void DistributedDBCloudCheckSyncTest::InsertUserTableRecord(int64_t recordCounts, int64_t begin) +{ + ASSERT_NE(db_, nullptr); + for (int64_t i = begin; i < recordCounts; ++i) { + string sql = "INSERT OR REPLACE INTO " + tableName_ + + " (id, name, height, photo, age) VALUES ('" + std::to_string(i) + "', 'Local" + + std::to_string(i) + "', '155.10', 'text', '21');"; + ASSERT_EQ(SQLiteUtils::ExecuteRawSQL(db_, sql), E_OK); + } +} + +/** + * @tc.name: CloudSyncTest001 + * @tc.desc: sync with device sync query + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCloudCheckSyncTest, CloudSyncTest001, TestSize.Level0) +{ + // prepare data + const int actualCount = 10; + InsertUserTableRecord(actualCount); + // sync twice + Query query = Query::Select().FromTable({ tableName_ }); + BlockSync(query, delegate_); + BlockSync(query, delegate_); + // remove cloud data + delegate_->RemoveDeviceData("CLOUD", ClearMode::FLAG_AND_DATA); + // check local data + int dataCnt = -1; + std::string checkLogSql = "SELECT count(*) FROM " + tableName_; + RelationalTestUtils::ExecSql(db_, checkLogSql, nullptr, [&dataCnt](sqlite3_stmt *stmt) { + dataCnt = sqlite3_column_int(stmt, 0); + return E_OK; + }); + EXPECT_EQ(dataCnt, actualCount); +} +} +#endif \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp index 312a64bd..fb6a9064 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp @@ -536,60 +536,6 @@ namespace { } } - void CheckCloudRecordNum(sqlite3 *&db, std::vector tableList, std::vector countList) - { - int i = 0; - for (const auto &tableName: tableList) { - std::string sql = "select count(*) from " + DBCommon::GetLogTableName(tableName) + - " where device = 'cloud'" + " and cloud_gid is not null and cloud_gid != '' and flag & 0x2 = 0;"; - EXPECT_EQ(sqlite3_exec(db, sql.c_str(), QueryCountCallback, - reinterpret_cast(countList[i]), nullptr), SQLITE_OK); - i++; - } - } - - void CheckCleanLogNum(sqlite3 *&db, const std::vector tableList, int count) - { - for (const auto &tableName: tableList) { - std::string sql1 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + - " where device = 'cloud';"; - EXPECT_EQ(sqlite3_exec(db, sql1.c_str(), QueryCountCallback, - reinterpret_cast(count), nullptr), SQLITE_OK); - std::string sql2 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + - " where cloud_gid " + " is not null and cloud_gid != '';"; - EXPECT_EQ(sqlite3_exec(db, sql2.c_str(), QueryCountCallback, - reinterpret_cast(count), nullptr), SQLITE_OK); - std::string sql3 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + - " where flag & 0x02 = 0;"; - EXPECT_EQ(sqlite3_exec(db, sql3.c_str(), QueryCountCallback, - reinterpret_cast(count), nullptr), SQLITE_OK); - } - } - - void CheckCleanDataAndLogNum(sqlite3 *&db, const std::vector tableList, int count, - std::vector localNum) - { - int i = 0; - for (const auto &tableName: tableList) { - std::string sql1 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + - " where device = 'cloud';"; - EXPECT_EQ(sqlite3_exec(db, sql1.c_str(), QueryCountCallback, - reinterpret_cast(count), nullptr), SQLITE_OK); - std::string sql2 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + " where cloud_gid " - " is not null and cloud_gid != '';"; - EXPECT_EQ(sqlite3_exec(db, sql2.c_str(), QueryCountCallback, - reinterpret_cast(count), nullptr), SQLITE_OK); - std::string sql3 = "select count(*) from " + DBCommon::GetLogTableName(tableName) + - " where flag & 0x02 = 0;"; - EXPECT_EQ(sqlite3_exec(db, sql3.c_str(), QueryCountCallback, - reinterpret_cast(count), nullptr), SQLITE_OK); - std::string local_sql = "select count(*) from " + tableName +";"; - EXPECT_EQ(sqlite3_exec(db, local_sql.c_str(), QueryCountCallback, - reinterpret_cast(localNum[i]), nullptr), SQLITE_OK); - i++; - } - } - void CheckCloudTotalCount(std::vector expectCounts) { VBucket extend; @@ -730,36 +676,6 @@ namespace { } } - void InitProcessForCleanCloudData1(const uint32_t &cloudCount, std::vector &expectProcess) - { - // cloudCount also means data count in one batch - expectProcess.clear(); - std::vector infos; - uint32_t index = 1; - infos.push_back(TableProcessInfo{ - FINISHED, {index, cloudCount, cloudCount, 0}, {0, 0, 0, 0} - }); - infos.push_back(TableProcessInfo{ - PREPARED, {0, 0, 0, 0}, {0, 0, 0, 0} - }); - - infos.push_back(TableProcessInfo{ - FINISHED, {index, cloudCount, cloudCount, 0}, {0, 0, 0, 0} - }); - infos.push_back(TableProcessInfo{ - FINISHED, {index, cloudCount, cloudCount, 0}, {0, 0, 0, 0} - }); - - for (size_t i = 0; i < infos.size() / g_arrayHalfSub; ++i) { - SyncProcess syncProcess; - syncProcess.errCode = OK; - syncProcess.process = i == infos.size() ? FINISHED : PROCESSING; - syncProcess.tableProcess.insert_or_assign(g_tables[0], std::move(infos[g_arrayHalfSub * i])); - syncProcess.tableProcess.insert_or_assign(g_tables[1], std::move(infos[g_arrayHalfSub * i + 1])); - expectProcess.push_back(syncProcess); - } - } - void InitProcessForTest2(const uint32_t &cloudCount, const uint32_t &localCount, std::vector &expectProcess) { @@ -1078,6 +994,28 @@ namespace { SQLiteUtils::ResetStatement(stmt, true, errCode); } + void InsertCloudForCloudProcessNotify001(std::vector &record, std::vector &extend) + { + VBucket data; + std::vector photo(1, 'v'); + data.insert_or_assign("name", "Local" + std::to_string(0)); + data.insert_or_assign("height", 166.0); // 166.0 is random double value + data.insert_or_assign("married", false); + data.insert_or_assign("age", 13L); + data.insert_or_assign("photo", photo); + Asset asset = g_cloudAsset; + asset.name = asset.name + std::to_string(0); + data.insert_or_assign("assert", asset); + record.push_back(data); + VBucket log; + Timestamp now = TimeHelper::GetSysCurrentTime(); + log.insert_or_assign(CloudDbConstant::CREATE_FIELD, (int64_t)now / CloudDbConstant::TEN_THOUSAND); + log.insert_or_assign(CloudDbConstant::MODIFY_FIELD, (int64_t)now / CloudDbConstant::TEN_THOUSAND); + log.insert_or_assign(CloudDbConstant::DELETE_FIELD, false); + log.insert_or_assign("#_gid", std::to_string(2)); // 2 is gid + extend.push_back(log); + } + void WaitForSyncFinish(SyncProcess &syncProcess, const int64_t &waitTime) { std::unique_lock lock(g_processMutex); @@ -1735,6 +1673,40 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CloudSyncTest014, TestS CloseDb(); } +/* + * @tc.name: CloudSyncTest016 + * @tc.desc: Test sync when push before merge + * @tc.type: FUNC + * @tc.require: + * @tc.author: chenchaohao + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CloudSyncTest016, TestSize.Level0) +{ + int64_t localCount = 10; + int64_t paddingSize = 10; + InsertUserTableRecord(db, 0, localCount, paddingSize, false); + callSync(g_tables, SYNC_MODE_CLOUD_FORCE_PUSH, DBStatus::OK); + CheckCloudTotalCount({10L, 10L}); + UpdateUserTableRecord(db, 0, localCount); + callSync(g_tables, SYNC_MODE_CLOUD_MERGE, DBStatus::OK); + + VBucket extend; + extend[CloudDbConstant::CURSOR_FIELD] = std::to_string(0); + std::vector data1; + g_virtualCloudDb->Query(g_tables[0], extend, data1); + for (int i = 0; i < 10; ++i) { // index[0, 10) in cloud db expected to be updated + EXPECT_EQ(std::get(data1[i]["age"]), 99); // 99 is the updated age field of cloud db + } + + std::vector data2; + g_virtualCloudDb->Query(g_tables[1], extend, data2); + for (int i = 0; i < 10; ++i) { // index[0, 10) in cloud db expected to be updated + EXPECT_EQ(std::get(data2[i]["age"]), 99); // 99 is the updated age field of cloud db + } + + CloseDb(); +} + /* * @tc.name: DataNotifier001 * @tc.desc: Notify data without primary key @@ -1840,7 +1812,7 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CloudProcessNotify001, */ std::vector record1; std::vector extend1; - RelationalTestUtils::GenerateAssetData(g_cloudAsset, record1, extend1); + InsertCloudForCloudProcessNotify001(record1, extend1); ASSERT_EQ(g_virtualCloudDb->BatchInsertWithGid(g_tableName1, std::move(record1), extend1), DBStatus::OK); /** @@ -1869,233 +1841,6 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CloudProcessNotify001, CloseDb(); } -/* - * @tc.name: CleanCloudDataTest001 - * @tc.desc: Test FLAG_ONLY mode of RemoveDeviceData, and invalid mode else. - * @tc.type: FUNC - * @tc.require: - * @tc.author: huangboxin - */ -HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CleanCloudDataTest001, TestSize.Level0) -{ - int64_t paddingSize = 10; - int localCount = 10; - int cloudCount = 20; - InsertCloudTableRecord(0, cloudCount, paddingSize, false); - InsertUserTableRecord(db, 0, localCount, paddingSize, false); - Query query = Query::Select().FromTable(g_tables); - std::vector expectProcess; - InitProcessForCleanCloudData1(cloudCount, expectProcess); - CloudSyncStatusCallback callback; - GetCallback(g_syncProcess, callback, expectProcess); - ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback, g_syncWaitTime), - DBStatus::OK); - WaitForSyncFinish(g_syncProcess, g_syncWaitTime); - std::string device = ""; - CheckCloudRecordNum(db, g_tables, {20, 20}); - ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_ONLY), DBStatus::OK); - CheckCleanLogNum(db, g_tables, 0); - - ASSERT_EQ(g_delegate->RemoveDeviceData(device, ClearMode(BUTT + 1)), DBStatus::INVALID_ARGS); - ASSERT_EQ(g_delegate->RemoveDeviceData(device, ClearMode(-1)), DBStatus::INVALID_ARGS); - - CloseDb(); -} - -/* - * @tc.name: CleanCloudDataTest002 - * @tc.desc: Test FLAG_AND_DATA mode of RemoveDeviceData - * @tc.type: FUNC - * @tc.require: - * @tc.author: huangboxin - */ -HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CleanCloudDataTest002, TestSize.Level0) -{ - int64_t paddingSize = 10; - int localCount = 10; - int cloudCount = 20; - InsertCloudTableRecord(0, cloudCount, paddingSize, false); - InsertUserTableRecord(db, 0, localCount, paddingSize, false); - Query query = Query::Select().FromTable(g_tables); - std::vector expectProcess; - InitProcessForCleanCloudData1(cloudCount, expectProcess); - CloudSyncStatusCallback callback; - GetCallback(g_syncProcess, callback, expectProcess); - ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback, g_syncWaitTime), - DBStatus::OK); - WaitForSyncFinish(g_syncProcess, g_syncWaitTime); - std::string device = ""; - CheckCloudRecordNum(db, g_tables, {20, 20}); // 20 means cloud data num - ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_AND_DATA), DBStatus::OK); - CheckCleanDataAndLogNum(db, g_tables, 0, {localCount, 0}); - CloseDb(); -} - -/* - * @tc.name: CleanCloudDataTest003 - * @tc.desc: Test FLAG_ONLY mode of RemoveDeviceData concurrently with Sync - * @tc.type: FUNC - * @tc.require: - * @tc.author: huangboxin - */ -HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CleanCloudDataTest003, TestSize.Level0) -{ - /** - * @tc.steps: step1. make data: 10 records on local and 20 records on cloud - */ - int64_t paddingSize = 10; - int localCount = 10; - int cloudCount = 20; - InsertCloudTableRecord(0, cloudCount, paddingSize, false); - InsertUserTableRecord(db, 0, localCount, paddingSize, false); - /** - * @tc.steps: step2. call Sync with cloud force pull strategy, and after that, local will has 20 records. - */ - Query query = Query::Select().FromTable(g_tables); - std::vector expectProcess; - InitProcessForCleanCloudData1(cloudCount, expectProcess); - CloudSyncStatusCallback callback; - GetCallback(g_syncProcess, callback, expectProcess); - ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback, g_syncWaitTime), - DBStatus::OK); - WaitForSyncFinish(g_syncProcess, g_syncWaitTime); - CheckCloudRecordNum(db, g_tables, {20, 20}); // 20 means cloud data num - - /** - * @tc.steps: step3. insert 10 records into local, so local will has 20 local records and 20 cloud records. - */ - InsertUserTableRecord(db, 21, localCount, paddingSize, false); // 21 means insert start index - /** - * @tc.steps: step4. call RemoveDeviceData synchronize with Sync with cloud force push strategy. - */ - g_syncProcess = {}; - std::vector expectProcess2; - InitProcessForCleanCloudData1(cloudCount, expectProcess2); - CloudSyncStatusCallback callback2; - GetCallback(g_syncProcess, callback2, expectProcess2); - std::string device = ""; - - std::thread thread1([&]() { - ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_AND_DATA), DBStatus::OK); - }); - std::thread thread2([&]() { - ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_FORCE_PULL, query, callback2, g_syncWaitTime), - DBStatus::OK); - LOGD("-------------------sync end--------------"); - }); - thread1.join(); - thread2.join(); - WaitForSyncFinish(g_syncProcess, g_syncWaitTime); - RuntimeContext::GetInstance()->StopTaskPool(); - CheckCleanLogNum(db, g_tables, 20); - LOGD("================================== test clean cloud data 003 end ==================================="); - CloseDb(); -} - -static void InitGetCloudSyncTaskCountTest001(sqlite3 *&db) -{ - int64_t localCount = 20; - int64_t cloudCount = 10; - int64_t paddingSize = 100; - InsertUserTableRecord(db, 0, localCount, paddingSize, false); - InsertCloudTableRecord(0, cloudCount, paddingSize, false); -} -/* - * @tc.name: GetCloudSyncTaskCountTest001 - * @tc.desc: Test FLAG_ONLY mode of RemoveDeviceData concurrently with Sync - * @tc.type: FUNC - * @tc.require: - * @tc.author: huangboxin - */ -HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, GetCloudSyncTaskCountTest001, TestSize.Level0) -{ - InitGetCloudSyncTaskCountTest001(db); - Query query = Query::Select().FromTable(g_tables); - std::mutex dataMutex1, dataMutex2; - std::condition_variable cv1, cv2; - bool finish1 = false, finish2 = false; - /** - * @tc.steps: step1. Call Sync once. - * @tc.expected: OK. - */ - CloudSyncStatusCallback callback1 = [&dataMutex1, &cv1, &finish1]( - const std::map &process) { - std::map syncProcess; - { - std::lock_guard autoLock(dataMutex1); - syncProcess = process; - if (syncProcess[DEVICE_CLOUD].process == FINISHED) { - finish1 = true; - } - } - cv1.notify_one(); - }; - /** - * @tc.steps: step2. Call Sync twice. - * @tc.expected: OK. - */ - ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_MERGE, query, callback1, g_syncWaitTime), DBStatus::OK); - - CloudSyncStatusCallback callback2 = [&dataMutex2, &cv2, &finish2]( - const std::map &process) { - std::map syncProcess; - { - std::lock_guard autoLock(dataMutex2); - syncProcess = process; - if (syncProcess[DEVICE_CLOUD].process == FINISHED) { - finish2 = true; - } - } - cv2.notify_one(); - }; - ASSERT_EQ(g_delegate->Sync({DEVICE_CLOUD}, SYNC_MODE_CLOUD_MERGE, query, callback2, g_syncWaitTime), DBStatus::OK); - /** - * @tc.steps: step3. Call Get Cloud Sync Task Count - * @tc.expected: OK. - */ - EXPECT_EQ(g_delegate->GetCloudSyncTaskCount(), 2); // 2 is task count - /** - * @tc.steps: step3. Wait For Sync Task Finished - * @tc.expected: OK. - */ - { - std::unique_lock uniqueLock(dataMutex1); - cv1.wait(uniqueLock, [&finish1] { - return finish1; - }); - } - { - std::unique_lock uniqueLock(dataMutex2); - cv2.wait(uniqueLock, [&finish2] { - return finish2; - }); - } - RuntimeContext::GetInstance()->StopTaskPool(); - CloseDb(); -} - -/* - * @tc.name: CleanCloudDataTest004 - * @tc.desc: Test RemoveDeviceData when cloudSchema doesn't have local table - * @tc.type: FUNC - * @tc.require: - * @tc.author: huangboxin - */ -HWTEST_F(DistributedDBCloudInterfacesRelationalSyncTest, CleanCloudDataTest004, TestSize.Level0) -{ - DataBaseSchema dataBaseSchema; - TableSchema tableSchema1 = { - .name = "table_not_existed", - .fields = g_cloudFiled1 - }; - dataBaseSchema.tables.push_back(tableSchema1); - GetCloudDbSchema(dataBaseSchema); - ASSERT_EQ(g_delegate->SetCloudDbSchema(dataBaseSchema), DBStatus::OK); - std::string device = ""; - ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_AND_DATA), DBStatus::OK); - CloseDb(); -} - /* * @tc.name: CloudSyncAssetTest002 * @tc.desc: diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp index 8d34a059..ea784f6f 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp @@ -88,17 +88,17 @@ namespace { return StorageProxy::GetCloudDb(store); } - void SetAndGetWaterMark(TableName tableName, LocalWaterMark mark) + void SetAndGetWaterMark(TableName tableName, Timestamp mark) { - LocalWaterMark retMark; + Timestamp retMark; EXPECT_EQ(g_storageProxy->PutLocalWaterMark(tableName, mark), E_OK); EXPECT_EQ(g_storageProxy->GetLocalWaterMark(tableName, retMark), E_OK); EXPECT_EQ(retMark, mark); } - void SetAndGetWaterMark(TableName tableName, CloudWaterMark mark) + void SetAndGetWaterMark(TableName tableName, std::string mark) { - CloudWaterMark retMark; + std::string retMark; EXPECT_EQ(g_storageProxy->SetCloudWaterMark(tableName, mark), E_OK); EXPECT_EQ(g_storageProxy->GetCloudWaterMark(tableName, retMark), E_OK); EXPECT_EQ(retMark, mark); @@ -185,11 +185,11 @@ namespace { */ HWTEST_F(DistributedDBCloudMetaDataTest, CloudMetaDataTest003, TestSize.Level0) { - CloudWaterMark retMark; + std::string retMark; EXPECT_EQ(g_storageProxy->GetCloudWaterMark(TABLE_NAME_2, retMark), E_OK); EXPECT_EQ(retMark, ""); - LocalWaterMark retLocalMark; + Timestamp retLocalMark; EXPECT_EQ(g_storageProxy->GetLocalWaterMark(TABLE_NAME_2, retLocalMark), E_OK); EXPECT_EQ(retLocalMark, 0u); } diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp index 822ced03..bd99eaa7 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp @@ -264,6 +264,12 @@ namespace { } else { EXPECT_EQ(dataInfoWithLog.primaryKeys.size(), 0u); } + Timestamp eraseTime = dataInfoWithLog.logInfo.timestamp / CloudDbConstant::TEN_THOUSAND * + CloudDbConstant::TEN_THOUSAND; + Timestamp eraseWTime = dataInfoWithLog.logInfo.wTimestamp / CloudDbConstant::TEN_THOUSAND * + CloudDbConstant::TEN_THOUSAND; + EXPECT_EQ(dataInfoWithLog.logInfo.timestamp, eraseTime); + EXPECT_EQ(dataInfoWithLog.logInfo.wTimestamp, eraseWTime); } } @@ -977,4 +983,65 @@ namespace { { DeleteWithPkTest(PrimaryKeyType::COMPOSITE_PRIMARY_KEY); } + + /** + * @tc.name: DropTableTest001 + * @tc.desc: Test drop table + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangshijie + */ + HWTEST_F(DistributedDBCloudSaveCloudDataTest, DropTableTest001, TestSize.Level1) + { + /** + * @tc.steps:step1. create db, create table, prepare data. + * @tc.expected: step1. ok. + */ + sqlite3 *db = RelationalTestUtils::CreateDataBase(g_dbDir + STORE_ID + DB_SUFFIX); + EXPECT_NE(db, nullptr); + EXPECT_EQ(RelationalTestUtils::ExecSql(db, "PRAGMA journal_mode=WAL;"), SQLITE_OK); + + std::string sql = "create table t_device(key int, value text);create table t_cloud(key int, value text);"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); + EXPECT_EQ(g_delegate->CreateDistributedTable("t_device", DistributedDB::DEVICE_COOPERATION), OK); + EXPECT_EQ(g_delegate->CreateDistributedTable("t_cloud", DistributedDB::CLOUD_COOPERATION), OK); + + sql = "insert into t_device values(1, 'zhangsan');insert into t_cloud values(1, 'zhangsan');"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); + sql = "update " + DBCommon::GetLogTableName("t_cloud") + " set flag = 0"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); + return; + + /** + * @tc.steps:step2. drop table t_cloud, check log data + * @tc.expected: step2. success. + */ + sql = "drop table t_cloud;"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); + sql = "select flag from " + DBCommon::GetLogTableName("t_cloud") + " where data_key = -1;"; + int count = 0; + int errCode = RelationalTestUtils::ExecSql(db, sql, nullptr, [&count] (sqlite3_stmt *stmt) { + EXPECT_EQ(sqlite3_column_int(stmt, 0), 3); // 3 mean local delete + count++; + return OK; + }); + EXPECT_EQ(errCode, E_OK); + EXPECT_EQ(count, 1); + + /** + * @tc.steps:step3. drop table t_device, check log data + * @tc.expected: step3. success. + */ + sql = "drop table t_device;"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); + sql = "select flag from " + DBCommon::GetLogTableName("t_device") + " where flag = 0x03;"; + count = 0; + errCode = RelationalTestUtils::ExecSql(db, sql, nullptr, [&count] (sqlite3_stmt *stmt) { + count++; + return OK; + }); + EXPECT_EQ(errCode, E_OK); + EXPECT_EQ(count, 1); + EXPECT_EQ(sqlite3_close_v2(db), E_OK); + } } diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp index c0ee9b2a..af4f51dc 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp @@ -237,7 +237,7 @@ int QueryCountCallback(void *data, int count, char **colValue, char **colName) return 0; } -void fillCloudAssetTest(int64_t count, AssetStatus statusType, bool isFullReplace) +void fillCloudAssetTest(int64_t count, AssetStatus statusType, bool isDownloadSuccess) { VBucket vBucket; vBucket[CloudDbConstant::GID_FIELD] = std::to_string(1); @@ -256,7 +256,9 @@ void fillCloudAssetTest(int64_t count, AssetStatus statusType, bool isFullReplac } vBucket["assert"] = asset; vBucket["asserts"] = assets; - ASSERT_EQ(g_storageProxy->FillCloudAssetForDownload(g_tableName, vBucket, isFullReplace), E_OK); + ASSERT_EQ(g_storageProxy->StartTransaction(TransactType::IMMEDIATE), E_OK); + ASSERT_EQ(g_storageProxy->FillCloudAssetForDownload(g_tableName, vBucket, isDownloadSuccess), E_OK); + ASSERT_EQ(g_storageProxy->Commit(), E_OK); } } @@ -434,8 +436,8 @@ HWTEST_F(DistributedDBRelationalCloudSyncableStorageTest, TransactionTest001, Te */ HWTEST_F(DistributedDBRelationalCloudSyncableStorageTest, TransactionTest002, TestSize.Level1) { - LocalWaterMark cloudTime = 666888; - LocalWaterMark localTime; + Timestamp cloudTime = 666888; + Timestamp localTime; EXPECT_EQ(g_storageProxy->GetLocalWaterMark(g_tableName, localTime), E_OK); /** diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp index aba2381b..6d1f8bfd 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp @@ -278,7 +278,6 @@ void SetNextBeginTime001() EXPECT_EQ(token->IsGetAllDataFinished(), false); token->SetNextBeginTime(dataItem); } -} class DistributedDBRelationalGetDataTest : public testing::Test { public: @@ -1664,6 +1663,70 @@ HWTEST_F(DistributedDBRelationalGetDataTest, CloseStore001, TestSize.Level1) RefObject::DecObjRef(syncInterface); } +/** + * @tc.name: ReleaseContinueTokenTest001 + * @tc.desc: Test relaese continue token + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangshijie + */ +HWTEST_F(DistributedDBRelationalGetDataTest, ReleaseContinueTokenTest001, TestSize.Level1) +{ + /** + * @tc.steps: step1. open store prepare data. + * @tc.expected: Succeed. + */ + ASSERT_EQ(g_mgr.OpenStore(g_storePath, g_storeID, RelationalStoreDelegate::Option {}, g_delegate), DBStatus::OK); + ASSERT_NE(g_delegate, nullptr); + ASSERT_EQ(g_delegate->CreateDistributedTable(g_tableName), DBStatus::OK); + + for (int i = 1; i <= 5; ++i) { // 5 is loop count + EXPECT_EQ(PutBatchData(1, i * 1024 * 1024), E_OK); // 1024*1024 equals 1M. + } + + EXPECT_EQ(g_mgr.CloseStore(g_delegate), DBStatus::OK); + g_delegate = nullptr; + + /** + * @tc.steps: step2. call GetSyncData. + * @tc.expected: return -E_UNFINISHED. + */ + auto store = new(std::nothrow) SQLiteRelationalStore(); + ASSERT_NE(store, nullptr); + RelationalDBProperties properties; + InitStoreProp(g_storePath, APP_ID, USER_ID, properties); + EXPECT_EQ(store->Open(properties), E_OK); + int errCode = E_OK; + auto connection = store->GetDBConnection(errCode); + EXPECT_EQ(errCode, E_OK); + ASSERT_NE(connection, nullptr); + errCode = store->RegisterLifeCycleCallback([](const std::string &, const std::string &) { + }); + EXPECT_EQ(errCode, E_OK); + errCode = store->RegisterLifeCycleCallback(nullptr); + EXPECT_EQ(errCode, E_OK); + auto syncInterface = store->GetStorageEngine(); + ASSERT_NE(syncInterface, nullptr); + + ContinueToken token = nullptr; + QueryObject query(Query::Select(g_tableName)); + std::vector entries; + + DataSizeSpecInfo sizeInfo; + sizeInfo.blockSize = 1 * 1024 * 1024; // permit 1M. + EXPECT_EQ(syncInterface->GetSyncData(query, SyncTimeRange {}, sizeInfo, token, entries), -E_UNFINISHED); + EXPECT_NE(token, nullptr); + syncInterface->ReleaseContinueToken(token); + RefObject::IncObjRef(syncInterface); + + SingleVerKvEntry::Release(entries); + store->ReleaseDBConnection(1, connection); // 1 is connection id + RefObject::DecObjRef(store); + store = nullptr; + std::this_thread::sleep_for(std::chrono::seconds(1)); + RefObject::DecObjRef(syncInterface); +} + /** * @tc.name: StopSync001 * @tc.desc: Test Relational Stop Sync Action. @@ -1718,4 +1781,5 @@ HWTEST_F(DistributedDBRelationalGetDataTest, EraseDeviceWaterMark001, TestSize.L ASSERT_NE(syncAbleEngine, nullptr); EXPECT_EQ(syncAbleEngine->EraseDeviceWaterMark("", true), -E_INVALID_ARGS); } +} #endif diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/cloud_syncer_test.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/cloud_syncer_test.h index 02fad804..ae5f38d3 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/cloud_syncer_test.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/cloud_syncer_test.h @@ -226,7 +226,8 @@ public: std::map TestTagAssetsInSingleRecord( VBucket &coveredData, VBucket &beCoveredData, bool setNormalStatus = false) { - return TagAssetsInSingleRecord(coveredData, beCoveredData, setNormalStatus); + int ret = E_OK; + return TagAssetsInSingleRecord(coveredData, beCoveredData, setNormalStatus, ret); } bool TestIsDataContainDuplicateAsset(std::vector &assetFields, VBucket &data) @@ -234,7 +235,7 @@ public: return IsDataContainDuplicateAsset(assetFields, data); } - void SetCloudWaterMarks(const TableName &tableName, const CloudWaterMark &mark) + void SetCloudWaterMarks(const TableName &tableName, const std::string &mark) { currentContext_.tableName = tableName; currentContext_.cloudWaterMarks[tableName] = mark; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_db_proxy_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_db_proxy_test.cpp index f254c1ba..231b3264 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_db_proxy_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_db_proxy_test.cpp @@ -148,7 +148,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest001, TestSize.Level0) * @tc.expected: step1. E_OK */ CloudDBProxy proxy; - EXPECT_EQ(proxy.SetCloudDB(virtualCloudDb_), E_OK); + proxy.SetCloudDB(virtualCloudDb_); /** * @tc.steps: step2. proxy close cloud db with cloud error * @tc.expected: step2. -E_CLOUD_ERROR @@ -178,7 +178,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest002, TestSize.Level0) * @tc.expected: step1. E_OK */ CloudDBProxy proxy; - ASSERT_EQ(proxy.SetCloudDB(virtualCloudDb_), E_OK); + proxy.SetCloudDB(virtualCloudDb_); /** * @tc.steps: step2. insert data to cloud db * @tc.expected: step2. OK @@ -234,7 +234,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest003, TestSize.Level0) * @tc.expected: step1. E_OK */ CloudDBProxy proxy; - ASSERT_EQ(proxy.SetCloudDB(virtualCloudDb_), E_OK); + proxy.SetCloudDB(virtualCloudDb_); /** * @tc.steps: step2. insert data to cloud db * @tc.expected: step2. OK @@ -292,7 +292,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest004, TestSize.Level3) EXPECT_CALL(*iCloud, StartTransaction).WillRepeatedly(testing::Return(E_OK)); EXPECT_CALL(*iCloud, Commit).WillRepeatedly(testing::Return(E_OK)); ASSERT_NE(cloudSyncer, nullptr); - ASSERT_EQ(cloudSyncer->SetCloudDB(virtualCloudDb_), E_OK); + cloudSyncer->SetCloudDB(virtualCloudDb_); cloudSyncer->SetSyncAction(true, false); cloudSyncer->SetDownloadFunc([]() { std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5s @@ -359,7 +359,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest005, TestSize.Level0) EXPECT_CALL(*iCloud, StartTransaction).WillRepeatedly(testing::Return(E_OK)); EXPECT_CALL(*iCloud, Commit).WillRepeatedly(testing::Return(E_OK)); ASSERT_NE(cloudSyncer, nullptr); - ASSERT_EQ(cloudSyncer->SetCloudDB(virtualCloudDb_), E_OK); + cloudSyncer->SetCloudDB(virtualCloudDb_); cloudSyncer->SetSyncAction(false, false); virtualCloudDb_->SetCloudError(true); /** @@ -398,7 +398,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest006, TestSize.Level3) EXPECT_CALL(*iCloud, Commit).WillRepeatedly(testing::Return(E_OK)); EXPECT_CALL(*iCloud, Rollback).WillRepeatedly(testing::Return(E_OK)); ASSERT_NE(cloudSyncer, nullptr); - ASSERT_EQ(cloudSyncer->SetCloudDB(virtualCloudDb_), E_OK); + cloudSyncer->SetCloudDB(virtualCloudDb_); cloudSyncer->SetSyncAction(true, false); cloudSyncer->SetDownloadFunc([cloudSyncer]() { std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5s @@ -443,7 +443,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest007, TestSize.Level4) EXPECT_CALL(*iCloud, StartTransaction).WillRepeatedly(testing::Return(E_OK)); EXPECT_CALL(*iCloud, Commit).WillRepeatedly(testing::Return(E_OK)); ASSERT_NE(cloudSyncer, nullptr); - ASSERT_EQ(cloudSyncer->SetCloudDB(virtualCloudDb_), E_OK); + cloudSyncer->SetCloudDB(virtualCloudDb_); cloudSyncer->SetSyncAction(false, false); /** * @tc.steps: step2. call sync and wait sync finish @@ -495,7 +495,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest008, TestSize.Level0) * @tc.expected: step1. E_OK */ CloudDBProxy proxy; - EXPECT_EQ(proxy.SetCloudDB(virtualCloudDb_), E_OK); + proxy.SetCloudDB(virtualCloudDb_); /** * @tc.steps: step2. proxy heartbeat with diff status */ @@ -551,7 +551,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest009, TestSize.Level3) EXPECT_CALL(*iCloud, Rollback).WillRepeatedly(testing::Return(E_OK)); auto cloudSyncer = new(std::nothrow) VirtualCloudSyncer(StorageProxy::GetCloudDb(iCloud.get())); ASSERT_NE(cloudSyncer, nullptr); - EXPECT_EQ(cloudSyncer->SetCloudDB(virtualCloudDb_), E_OK); + cloudSyncer->SetCloudDB(virtualCloudDb_); cloudSyncer->SetSyncAction(true, false); cloudSyncer->SetDownloadFunc([]() { std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5s @@ -605,7 +605,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudDBProxyTest010, TestSize.Level0) * @tc.expected: step1. E_OK */ CloudDBProxy proxy; - EXPECT_EQ(proxy.SetCloudDB(virtualCloudDb_), E_OK); + proxy.SetCloudDB(virtualCloudDb_); /** * @tc.steps: step2. proxy lock with diff status */ @@ -645,7 +645,7 @@ HWTEST_F(DistributedDBCloudDBProxyTest, CloudSyncQueue001, TestSize.Level2) EXPECT_CALL(*iCloud, Rollback).WillRepeatedly(testing::Return(E_OK)); EXPECT_CALL(*iCloud, Commit).WillRepeatedly(testing::Return(E_OK)); EXPECT_CALL(*iCloud, StartTransaction).WillRepeatedly(testing::Return(E_OK)); - ASSERT_EQ(cloudSyncer->SetCloudDB(virtualCloudDb_), E_OK); + cloudSyncer->SetCloudDB(virtualCloudDb_); cloudSyncer->SetSyncAction(true, false); cloudSyncer->SetDownloadFunc([cloudSyncer]() { EXPECT_EQ(cloudSyncer->GetQueueCount(), 1u); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp index cda9f0a0..11500180 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp @@ -15,6 +15,7 @@ #include #include "distributeddb_tools_unit_test.h" #include "strategy_factory.h" +#include "virtual_cloud_syncer.h" using namespace std; using namespace testing::ext; @@ -275,6 +276,7 @@ HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest003, TestSize.Level0) EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::UPDATE); deletePrimaryKeySet.clear(); } + /** * @tc.name: TagOpTyeTest004 * @tc.desc: Verify cloud cover local strategy tag operation type function. @@ -302,4 +304,25 @@ HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest004, TestSize.Level0) localInfo.flag = 0x01; EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::INSERT); } + +/** + * @tc.name: TagOpTyeTest005 + * @tc.desc: Verify same data conflict in local. + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest005, TestSize.Level0) +{ + auto syncer = new(std::nothrow) VirtualCloudSyncer(nullptr); + ASSERT_NE(syncer, nullptr); + DataInfoWithLog localInfo; + LogInfo cloudInfo; + OpType result = OpType::INSERT; + EXPECT_EQ(syncer->CallTagStatusByStrategy(true, localInfo, cloudInfo, result), E_OK); + EXPECT_EQ(result, OpType::NOT_HANDLE); + localInfo.logInfo.device = "dev"; + EXPECT_EQ(syncer->CallTagStatusByStrategy(true, localInfo, cloudInfo, result), -E_INTERNAL_ERROR); + RefObject::KillAndDecObjRef(syncer); +} } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_test.cpp index 8fb260e2..764784bd 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_test.cpp @@ -66,7 +66,6 @@ void DistributedDBCloudSyncerDownloadTest::TearDown(void) { } - std::vector GetRetCloudData(uint64_t cnt) { std::vector photo(g_photoCount, 'v'); @@ -98,6 +97,14 @@ struct InvalidCloudDataOpt { bool invalidCursor = true; }; +void GenerateTableSchema(TableSchema &tableSchema) +{ + tableSchema = { + "TestTable1", + {{"name", TYPE_INDEX, true}} + }; +} + std::vector GetInvalidTypeCloudData(uint64_t cnt, InvalidCloudDataOpt fieldOpt) { std::vector photo(g_photoCount, 'v'); @@ -110,7 +117,7 @@ std::vector GetInvalidTypeCloudData(uint64_t cnt, InvalidCloudDataOpt f data.insert_or_assign("married", (bool)0); data.insert_or_assign("photo", photo); data.insert_or_assign("age", 13L); - + if (fieldOpt.invalidGID) { data.insert_or_assign(CloudDbConstant::GID_FIELD, (int64_t)i); } @@ -248,7 +255,7 @@ HWTEST_F(DistributedDBCloudSyncerDownloadTest, DownloadMockTest001, TestSize.Lev EXPECT_CALL(*g_iCloud, GetMetaData(_, _)).WillOnce(Return(-E_SECUREC_ERROR)); errCode = g_cloudSyncer->CallDoDownload(taskId); EXPECT_EQ(errCode, -E_SECUREC_ERROR); - + taskId = 5u; g_cloudSyncer->InitCloudSyncer(taskId, SYNC_MODE_CLOUD_FORCE_PUSH); EXPECT_CALL(*g_iCloud, GetMetaData(_, _)).WillOnce(Return(-E_INVALID_ARGS)); @@ -355,7 +362,7 @@ HWTEST_F(DistributedDBCloudSyncerDownloadTest, DownloadMockQueryTest003, TestSiz EXPECT_CALL(*g_iCloud, ChkSchema(_)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*g_iCloud, TriggerObserverAction(_, _, _)).WillRepeatedly(Return()); EXPECT_CALL(*g_iCloud, GetCloudTableSchema(_, _)).WillRepeatedly(Return(E_OK)); - + g_cloudSyncer->InitCloudSyncer(taskId, SYNC_MODE_CLOUD_MERGE); EXPECT_CALL(*g_idb, Query(_, _, _)) .WillOnce([](const std::string &, VBucket &, std::vector &data) { @@ -569,7 +576,11 @@ HWTEST_F(DistributedDBCloudSyncerDownloadTest, DownloadMockTest006, TestSize.Lev EXPECT_CALL(*g_iCloud, GetMetaData(_, _)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*g_iCloud, ChkSchema(_)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*g_iCloud, TriggerObserverAction(_, _, _)).WillRepeatedly(Return()); - EXPECT_CALL(*g_iCloud, GetCloudTableSchema(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*g_iCloud, GetCloudTableSchema(_, _)) + .WillRepeatedly([](const TableName &, TableSchema &tableSchema) { + GenerateTableSchema(tableSchema); + return E_OK; + }); g_cloudSyncer->InitCloudSyncer(taskId, SYNC_MODE_CLOUD_MERGE); EXPECT_CALL(*g_idb, Query(_, _, _)) @@ -683,7 +694,11 @@ HWTEST_F(DistributedDBCloudSyncerDownloadTest, DownloadMockTest007, TestSize.Lev EXPECT_CALL(*g_iCloud, GetMetaData(_, _)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*g_iCloud, ChkSchema(_)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*g_iCloud, TriggerObserverAction(_, _, _)).WillRepeatedly(Return()); - EXPECT_CALL(*g_iCloud, GetCloudTableSchema(_, _)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*g_iCloud, GetCloudTableSchema(_, _)) + .WillRepeatedly([](const TableName &, TableSchema &tableSchema) { + GenerateTableSchema(tableSchema); + return E_OK; + }); g_cloudSyncer->InitCloudSyncer(taskId, SYNC_MODE_CLOUD_MERGE); ExpectQueryCall(); ExpectGetInfoByPrimaryKeyOrGidCall(); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_upload_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_upload_test.cpp index 4b6cadc8..0170c760 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_upload_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_upload_test.cpp @@ -376,7 +376,8 @@ HWTEST_F(DistributedDBCloudSyncerUploadTest, UploadModeCheck007, TestSize.Level1 // Batch_n CloudSyncData quantity > total count cloudSyncer->InitCloudSyncer(5u, SYNC_MODE_CLOUD_FORCE_PUSH); CloudSyncData uploadData2(cloudSyncer->GetCurrentContextTableName()); - VBucket tmp = {pair(CloudDbConstant::MODIFY_FIELD, 1)}; + VBucket tmp = { pair(CloudDbConstant::MODIFY_FIELD, 1), + pair(CloudDbConstant::CREATE_FIELD, 1) }; uploadData2.insData.record = std::vector(1000, tmp); uploadData2.insData.extend = std::vector(1000, tmp); @@ -386,9 +387,8 @@ HWTEST_F(DistributedDBCloudSyncerUploadTest, UploadModeCheck007, TestSize.Level1 auto token = new (std::nothrow) SQLiteSingleVerRelationalContinueToken(syncTimeRange, queryObject); ContinueToken conStmtToken = static_cast(token); delete token; - EXPECT_CALL(*iCloud, GetCloudData(_, _, _, _)) - .WillOnce([&conStmtToken, &uploadData2](const TableSchema &, const Timestamp &, - ContinueToken &continueStmtToken, CloudSyncData &cloudDataResult) { + EXPECT_CALL(*iCloud, GetCloudData(_, _, _, _)).WillOnce([&conStmtToken, &uploadData2]( + const TableSchema &, const Timestamp &, ContinueToken &continueStmtToken, CloudSyncData &cloudDataResult) { continueStmtToken = conStmtToken; cloudDataResult = uploadData2; return -E_UNFINISHED; @@ -490,7 +490,8 @@ HWTEST_F(DistributedDBCloudSyncerUploadTest, UploadModeCheck009, TestSize.Level1 TaskId taskId = 5u; cloudSyncer->InitCloudSyncer(taskId, SYNC_MODE_CLOUD_FORCE_PUSH); - VBucket tmp = {pair(CloudDbConstant::MODIFY_FIELD, 1)}; + VBucket tmp = { pair(CloudDbConstant::MODIFY_FIELD, 1), + pair(CloudDbConstant::CREATE_FIELD, 1) }; CommonExpectCall(iCloud); EXPECT_CALL(*iCloud, PutMetaData(_, _)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*idb, BatchInsert(_, _, _)).WillRepeatedly(Return(OK)); @@ -661,7 +662,8 @@ HWTEST_F(DistributedDBCloudSyncerUploadTest, UploadModeCheck011, TestSize.Level1 TestCloudSyncer *cloudSyncer = new(std::nothrow) TestCloudSyncer(storageProxy); std::shared_ptr idb = std::make_shared(); cloudSyncer->SetMockICloudDB(idb); - VBucket tmp = {pair(CloudDbConstant::MODIFY_FIELD, 1)}; + VBucket tmp = { pair(CloudDbConstant::MODIFY_FIELD, 1), + pair(CloudDbConstant::CREATE_FIELD, 1) }; cloudSyncer->InitCloudSyncer(6u, SYNC_MODE_CLOUD_FORCE_PUSH); EXPECT_CALL(*iCloud, StartTransaction(_)).WillRepeatedly(Return(E_OK)); @@ -723,7 +725,8 @@ HWTEST_F(DistributedDBCloudSyncerUploadTest, UploadModeCheck012, TestSize.Level1 TestCloudSyncer *cloudSyncer = new(std::nothrow) TestCloudSyncer(storageProxy); std::shared_ptr idb = std::make_shared(); cloudSyncer->SetMockICloudDB(idb); - VBucket tmp = {pair(CloudDbConstant::MODIFY_FIELD, 1)}; + VBucket tmp = { pair(CloudDbConstant::MODIFY_FIELD, 1), + pair(CloudDbConstant::CREATE_FIELD, 1) }; cloudSyncer->InitCloudSyncer(6u, SYNC_MODE_CLOUD_FORCE_PUSH); EXPECT_CALL(*iCloud, StartTransaction(_)).WillRepeatedly(Return(E_OK)); @@ -1062,7 +1065,8 @@ HWTEST_F(DistributedDBCloudSyncerUploadTest, UploadModeCheck018, TestSize.Level1 MockCall(iCloud, idb); // Batch_n CloudSyncData quantity > total count - VBucket tmp = {pair(CloudDbConstant::MODIFY_FIELD, 1)}; + VBucket tmp = { pair(CloudDbConstant::MODIFY_FIELD, 1), + pair(CloudDbConstant::CREATE_FIELD, 1) }; cloudSyncer->InitCloudSyncer(5u, SYNC_MODE_CLOUD_FORCE_PUSH); CloudSyncData uploadData2(cloudSyncer->GetCurrentContextTableName()); uploadData2.insData.record = std::vector(1000, tmp); @@ -1074,9 +1078,8 @@ HWTEST_F(DistributedDBCloudSyncerUploadTest, UploadModeCheck018, TestSize.Level1 auto token = new (std::nothrow) SQLiteSingleVerRelationalContinueToken(syncTimeRange, queryObject); auto conStmtToken = static_cast(token); delete token; - EXPECT_CALL(*iCloud, GetCloudData(_, _, _, _)) - .WillOnce([&conStmtToken, &uploadData2](const TableSchema &, const Timestamp &, - ContinueToken &continueStmtToken, CloudSyncData &cloudDataResult) { + EXPECT_CALL(*iCloud, GetCloudData(_, _, _, _)).WillOnce([&conStmtToken, &uploadData2]( + const TableSchema &, const Timestamp &, ContinueToken &continueStmtToken, CloudSyncData &cloudDataResult) { cloudDataResult = uploadData2; continueStmtToken = conStmtToken; return -E_UNFINISHED; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/mock_icloud_sync_storage_interface.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/mock_icloud_sync_storage_interface.h index 6134e151..149e42ff 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/mock_icloud_sync_storage_interface.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/mock_icloud_sync_storage_interface.h @@ -41,7 +41,8 @@ public: MOCK_METHOD4(CleanCloudData, int(ClearMode mode, const std::vector &tableNameList, const RelationalSchemaObject &localSchema, std::vector &assets)); MOCK_METHOD3(FillCloudAssetForDownload, int(const std::string &, VBucket &, bool)); - MOCK_METHOD2(FillCloudGidAndAsset, int(const OpType &, const CloudSyncData &)); + MOCK_METHOD1(SetLogTriggerStatus, int(bool)); + MOCK_METHOD2(FillCloudGidAndAsset, int(OpType, const CloudSyncData &)); MOCK_CONST_METHOD0(GetIdentify, std::string()); }; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.cpp index c4fdd183..41207e52 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.cpp @@ -97,9 +97,10 @@ Asset VirtualCloudDataTranslate::BlobToAsset(const std::vector &blob) ReadAsset(parcel, asset); return asset; } -Assets VirtualCloudDataTranslate::BlobToAssets(std::vector &blob) +Assets VirtualCloudDataTranslate::BlobToAssets(const std::vector &blob) { - Parcel parcel(blob.data(), blob.size()); + std::vector inputData = blob; + Parcel parcel(inputData.data(), inputData.size()); uint32_t count = 0; parcel.ReadUInt32(count); Assets assets; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.h index dcdfdfda..86b4739d 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.h @@ -26,7 +26,7 @@ public: std::vector AssetToBlob(const Asset &asset) override; std::vector AssetsToBlob(const Assets &assets) override; Asset BlobToAsset(const std::vector &blob) override; - Assets BlobToAssets(std::vector &blob) override; + Assets BlobToAssets(const std::vector &blob) override; }; } #endif // VIRTUAL_CLOUD_DATA_TRANSLATE_H diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.cpp index 576b044e..231ff557 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.cpp @@ -88,4 +88,14 @@ void VirtualCloudSyncer::SetCurrentTaskInfo(const SyncProcessCallback &callback, taskInfo.callback = callback; cloudTaskInfos_[taskId] = taskInfo; } + +int VirtualCloudSyncer::CallTagStatusByStrategy(bool isExist, const DataInfoWithLog &localInfo, + const LogInfo &cloudInfo, OpType &strategyOpResult) +{ + SyncParam param; + DataInfo dataInfo; + dataInfo.localInfo = localInfo; + dataInfo.cloudLogInfo = cloudInfo; + return CloudSyncer::TagStatusByStrategy(isExist, param, dataInfo, strategyOpResult); +} } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.h index 66c10c26..5dc22776 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.h @@ -35,6 +35,9 @@ public: size_t GetQueueCount(); void SetCurrentTaskInfo(const SyncProcessCallback &callback, CloudSyncer::TaskId taskId); + + int CallTagStatusByStrategy(bool isExist, const DataInfoWithLog &localInfo, const LogInfo &cloudInfo, + OpType &strategyOpResult); private: std::function downloadFunc_; std::atomic doDownload_; diff --git a/kv_store/kv_store.gni b/kv_store/kv_store.gni index 930c2f29..d1ae3ee8 100644 --- a/kv_store/kv_store.gni +++ b/kv_store/kv_store.gni @@ -19,6 +19,8 @@ kv_store_api_path = "${kv_store_base_path}/interfaces/inner_api" distributedfilejs_path = "//foundation/distributeddatamgr/distributedfile" +third_party_path = "//third_party" + use_platform_win = "${current_os}_${current_cpu}" == "mingw_x86_64" use_platforn_mac = "${current_os}_${current_cpu}" == "mac_x64" || "${current_os}_${current_cpu}" == "mac_arm64" diff --git a/kv_store/test/distributedtest/single_kvstore_client/BUILD.gn b/kv_store/test/distributedtest/single_kvstore_client/BUILD.gn index 56479110..8af7a096 100644 --- a/kv_store/test/distributedtest/single_kvstore_client/BUILD.gn +++ b/kv_store/test/distributedtest/single_kvstore_client/BUILD.gn @@ -12,128 +12,66 @@ # limitations under the License. import("//build/test.gni") -import("//foundation/distributeddatamgr/data_share/datashare.gni") +import("//foundation/distributeddatamgr/kv_store/kv_store.gni") -module_output_path = "kv_store/distributeddatafwk" +module_output_path = "kv_store/distributed_test" ############################################################################### config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "${datashare_innerapi_path}/common/include", - "${datashare_innerapi_path}/provider/include", - "//commonlibrary/c_utils/base/include", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/include", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/include", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/distributedtest/single_kvstore_client", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/app_distributeddata/include", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/app/include", - "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/mod_securitylabel", - "//test/testfwk/developer_test/aw/distributed", - "//base/hiviewdfx/hitrace/interfaces/native/innerkits/include", + "${kv_store_base_path}/test/distributedtest/single_kvstore_client", + "${kv_store_base_path}/interfaces/innerkits/distributeddata/include", + "${kv_store_base_path}/frameworks/common", + "${kv_store_base_path}/frameworks/distributeddatafwk/include", + "${kv_store_base_path}/frameworks/distributeddatafwk/src", + "${kv_store_base_path}/frameworks/kvdb/include", ] - lib_dirs = [ "//foundation/appexecfwk/libs" ] } -old_source_config = [ - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/blob.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/change_notification.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/distributed_kv_data_manager.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_client_death_observer.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_observer.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_sync_callback.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kv_utils.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client_death_observer.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_datashare_bridge.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_observer_client.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/sync_observer.cpp", - "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include/types.h", +common_deps = [ + "${kv_store_base_path}/frameworks/libs/distributeddb:distributeddb", + "${kv_store_base_path}/interfaces/innerkits/distributeddata:distributeddata_inner", + "${third_party_path}/googletest:gtest", ] -kvdb_source_config = [ - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/auto_sync_timer.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/backup_manager.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/convertor.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/dev_manager.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/device_convertor.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/kv_types_util.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/observer_bridge.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/security_manager.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/single_store_impl.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/store_factory.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/store_manager.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/store_result_set.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/store_util.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/system_api.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/task_executor.cpp", - "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src/task_executor_adapter.cpp", +common_external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "device_manager:devicemanagersdk", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "huks:libhukssdk", + "ipc:ipc_single", + "samgr:samgr_proxy", ] +############################################################################### ohos_distributedtest("DistributedTest") { module_out_path = module_output_path - sources = old_source_config + kvdb_source_config - sources += [ - "distributed_test_helper.cpp", - "distributed_test_helper.h", - ] - sources += [ "distributed_test.cpp" ] + + sources = [ "distributed_test.cpp" ] configs = [ ":module_private_config" ] - external_deps = [ - "c_utils:utils", - "device_manager:devicemanagersdk", - "hilog:libhilog", - "hisysevent:libhisysevent", - "hitrace:hitrace_meter", - "hitrace:libhitracechain", - "huks:libhukssdk", - "ipc:ipc_core", - "samgr:samgr_proxy", - ] + external_deps = common_external_deps - deps = [ - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/:distributeddb", - "//third_party/googletest:gtest", - ] + deps = common_deps } ohos_distributedtest("DistributedTestAgent") { module_out_path = module_output_path - sources = old_source_config + kvdb_source_config - - sources += [ "distributed_test_agent.cpp" ] + sources = [ "distributed_test_agent.cpp" ] configs = [ ":module_private_config" ] - external_deps = [ - "c_utils:utils", - "device_manager:devicemanagersdk", - "hilog:libhilog", - "hisysevent:libhisysevent", - "hitrace:hitrace_meter", - "hitrace:libhitracechain", - "huks:libhukssdk", - "ipc:ipc_core", - "samgr:samgr_proxy", - ] + external_deps = common_external_deps - deps = [ - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/:distributeddb", - "//third_party/googletest:gtest", - ] + deps = common_deps } ############################################################################### diff --git a/kv_store/test/distributedtest/single_kvstore_client/distributed_test.cpp b/kv_store/test/distributedtest/single_kvstore_client/distributed_test.cpp index 9b5bd4a0..f26150d5 100644 --- a/kv_store/test/distributedtest/single_kvstore_client/distributed_test.cpp +++ b/kv_store/test/distributedtest/single_kvstore_client/distributed_test.cpp @@ -12,206 +12,240 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#define LOG_TAG "DistributedTest" #include -#include -#include -#include -#include -#include "dev_manager.h" + +#include "accesstoken_kit.h" +#include "directory_ex.h" #include "distributed_kv_data_manager.h" -#include "types.h" #include "distributed_major.h" -#include "distributed_test_helper.h" -#include "refbase.h" -#include "hilog/log.h" -#include "directory_ex.h" +#include "log_print.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "types.h" -using namespace OHOS; using namespace testing::ext; +using namespace OHOS; using namespace OHOS::DistributedKv; using namespace OHOS::DistributeSystemTest; -using namespace OHOS::HiviewDFX; +using namespace OHOS::Security::AccessToken; +namespace OHOS::Test { +class DistributedTest : public DistributeTest { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; -namespace { -constexpr HiLogLabel LABEL_TEST = {LOG_CORE, 0, "DistributedTest"}; -constexpr HiLogLabel LABEL = {LOG_CORE, 0, "KvStoreSyncCallbackTestImpl"}; + Status GetRemote(const Key &key, Value &value); -class KvStoreSyncCallbackTestImpl : public KvStoreSyncCallback { -public: - void SyncCompleted(const std::map &results); - std::condition_variable cv_; - bool compeleted_ = false; - std::mutex mtx_; + static DistributedKvDataManager manager_; + static std::shared_ptr singleKvStore_; + static constexpr int FILE_PERMISSION = 0777; + static constexpr int WAIT_TIME = 5; }; -class Util { +DistributedKvDataManager DistributedTest::manager_; +std::shared_ptr DistributedTest::singleKvStore_ = nullptr; + +class KvStoreSyncCallbackTestImpl : public KvStoreSyncCallback { public: - static std::string Anonymous(const std::string &name) + static bool IsSyncComplete() { - if (name.length() <= HEAD_SIZE) { - return DEFAULT_ANONYMOUS; - } + bool flag = completed_; + completed_ = false; + return flag; + } - if (name.length() < MIN_SIZE) { - return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN); + void SyncCompleted(const std::map &results) override + { + ZLOGI("SyncCallback Called!"); + for (const auto &result : results) { + if (result.second == SUCCESS) { + completed_ = true; + } + ZLOGI("device: %{public}s, status: 0x%{public}x", result.first.c_str(), result.second); } - - return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN + name.substr(name.length() - END_SIZE, END_SIZE)); } private: - static constexpr int32_t HEAD_SIZE = 3; - static constexpr int32_t END_SIZE = 3; - static constexpr int32_t MIN_SIZE = HEAD_SIZE + END_SIZE + 3; - static constexpr const char *REPLACE_CHAIN = "***"; - static constexpr const char *DEFAULT_ANONYMOUS = "******"; + static bool completed_; }; -void KvStoreSyncCallbackTestImpl::SyncCompleted(const std::map &results) -{ - for (const auto &result : results) { - HiLog::Info(LABEL, "uuid = %{public}s, status = %{public}d", - Util::Anonymous(result.first).c_str(), result.second); - } - std::lock_guard lck(mtx_); - compeleted_ = true; - cv_.notify_one(); -} - -class DistributedTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); +bool KvStoreSyncCallbackTestImpl::completed_ = false; - static std::shared_ptr singleKvStore_; // declare kvstore instance. - static DistributedKvDataManager manager_; - static std::vector detailInfos_; - DistributedTestHelper helper_; - static constexpr int WAIT_FOR_TIME = 3; // wait for synccallback time is 3s. - static constexpr int FILE_PERMISSION = 0777; // 0777 is to modify the permissions of the file. -}; - -std::shared_ptr DistributedTest::singleKvStore_ = nullptr; -DistributedKvDataManager DistributedTest::manager_; -std::vector DistributedTest::detailInfos_; - -void DistributedTest::SetUpTestCase(void) +void DistributedTest::SetUpTestCase() { + const char **perms = new const char *[1]; + perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; + TokenInfoParams info = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "distributed_test", + .aplStr = "system_basic", + }; + auto tokenId = GetAccessTokenId(&info); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; + Options options = { .createIfMissing = true, .encrypt = false, .autoSync = false, .kvStoreType = KvStoreType::SINGLE_VERSION }; options.area = EL1; options.baseDir = std::string("/data/service/el1/public/database/odmf"); AppId appId = { "odmf" }; - StoreId storeId = { "student_single" }; // define kvstore(database) name. + StoreId storeId = { "student" }; mkdir(options.baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); - manager_.GetSingleKvStore(options, appId, storeId, singleKvStore_); - detailInfos_ = DevManager::GetInstance().GetRemoteDevices(); + auto status = manager_.GetSingleKvStore(options, appId, storeId, singleKvStore_); + ASSERT_EQ(status, SUCCESS); + ASSERT_NE(singleKvStore_, nullptr); OHOS::ChangeModeDirectory(options.baseDir, FILE_PERMISSION); + + std::shared_ptr syncCallback = std::make_shared(); + status = singleKvStore_->RegisterSyncCallback(syncCallback); + ASSERT_EQ(status, SUCCESS); } -void DistributedTest::TearDownTestCase(void) +void DistributedTest::TearDownTestCase() { + (void)manager_.CloseAllKvStore({ "odmf" }); + (void)manager_.DeleteKvStore({ "odmf" }, { "student" }, "/data/service/el1/public/database/odmf"); (void)remove("/data/service/el1/public/database/odmf/key"); (void)remove("/data/service/el1/public/database/odmf/kvdb"); (void)remove("/data/service/el1/public/database/odmf"); } -void DistributedTest::SetUp(void) +void DistributedTest::SetUp() {} -void DistributedTest::TearDown(void) +void DistributedTest::TearDown() {} -HWTEST_F(DistributedTest, SyncData001, TestSize.Level1) +Status DistributedTest::GetRemote(const Key &key, Value &value) { - EXPECT_NE(singleKvStore_, nullptr) << "kvStorePtr is null"; - Key key = { "single1_001" }; - Value val = { "value1_001" }; - auto status = singleKvStore_->Put(key, val); - EXPECT_EQ(Status::SUCCESS, status) << "Put failed"; + Status status = ERROR; + std::string message = "get"; + message += ","; + message += key.ToString(); + (void)SendMessage(AGENT_NO::ONE, message, message.size(), + [&](const std::string &returnBuf, int length) -> bool { + auto index = returnBuf.find(","); + status = Status(std::stoi(returnBuf.substr(0, index))); + if (length > static_cast(index + 1)) { + value = Value(returnBuf.substr(index + 1)); + } + return true; + }); + return status; +} - auto syncCallback = std::make_shared(); - status = singleKvStore_->RegisterSyncCallback(syncCallback); - EXPECT_EQ(Status::SUCCESS, status) << "SyncCallback failed"; +/** +* @tc.name: SendMessage001 +* @tc.desc: Verify distributed test framework SendMessage +* @tc.type: FUNC +*/ +HWTEST_F(DistributedTest, SendMessage001, TestSize.Level1) +{ + ZLOGI("SendMessage001 Start"); - std::vector deviceIds; - for (const auto &device : detailInfos_) { - deviceIds.push_back(device.networkId); - } - std::unique_lock lck(syncCallback->mtx_); - status = singleKvStore_->Sync(deviceIds, SyncMode::PUSH); - if (!syncCallback->cv_.wait_for(lck, std::chrono::seconds(WAIT_FOR_TIME), - [&syncCallback]() { return syncCallback->compeleted_; })) { - status = Status::TIME_OUT; - } - EXPECT_EQ(Status::SUCCESS, status) << "Sync failed"; + std::string message = "SendMessage"; + std::string result = ""; + auto flag = SendMessage(AGENT_NO::ONE, message, message.size(), + [&](const std::string &returnBuf, int length) -> bool { + result = returnBuf; + return true; + }); + ASSERT_TRUE(flag); + ASSERT_EQ(result, "Send Message OK!"); - Value value; - status = helper_.GetRemote(key, value); - HiLog::Info(LABEL_TEST, "value = %{public}s", value.ToString().c_str()); - EXPECT_EQ(Status::SUCCESS, status) << "Get failed"; - EXPECT_STREQ(value.ToString().c_str(), val.ToString().c_str())<< "failed"; + ZLOGI("SendMessage001 end"); } -HWTEST_F(DistributedTest, SyncData002, TestSize.Level1) +/** +* @tc.name: RunCommand001 +* @tc.desc: Verify distributed test framework RunCommand +* @tc.type: FUNC +*/ +HWTEST_F(DistributedTest, RunCommand001, TestSize.Level1) { - EXPECT_NE(singleKvStore_, nullptr) << "kvStorePtr is null"; - Key key = { "single1_002" }; - Value val = { "value1_002" }; - auto status = singleKvStore_->Put(key, val); - EXPECT_EQ(Status::SUCCESS, status) << "Put failed"; + ZLOGI("RunCommand001 Start"); - SyncMode mode = SyncMode::PULL; - EXPECT_EQ(Status::SUCCESS, helper_.SyncRemote(mode))<< "Sync failed"; + std::string command = "CommandTest"; + std::string arguments = ""; + std::string result = "0"; + auto flag = RunCmdOnAgent(AGENT_NO::ONE, command, arguments, result); + ASSERT_TRUE(flag); + auto status = GetReturnVal(); + ASSERT_EQ(status, SUCCESS); - Value value; - status = helper_.GetRemote(key, value); - HiLog::Info(LABEL_TEST, "value = %{public}s", value.ToString().c_str()); - EXPECT_EQ(Status::SUCCESS, status) << "Get failed"; - EXPECT_STREQ(value.ToString().c_str(), val.ToString().c_str()) << "failed"; + ZLOGI("RunCommand001 end"); } -HWTEST_F(DistributedTest, SyncData003, TestSize.Level1) +/** +* @tc.name: SyncData001 +* @tc.desc: Sync data with push mode and get data from other device +* @tc.type: FUNC +*/ +HWTEST_F(DistributedTest, SyncData001, TestSize.Level1) { - EXPECT_NE(singleKvStore_, nullptr) << "kvStorePtr is null"; - Key key = { "single1_003" }; - Value val = { "value1_003" }; - auto status = singleKvStore_->Put(key, val); - EXPECT_EQ(Status::SUCCESS, status) << "Put failed"; + ZLOGI("SyncData001 begin"); - SyncMode mode = SyncMode::PULL; - uint32_t delay = 200; - EXPECT_EQ(Status::SUCCESS, helper_.SyncRemote(mode, delay)) << "Sync failed"; - - Value value; - status = helper_.GetRemote(key, value); - HiLog::Info(LABEL_TEST, "value = %{public}s", value.ToString().c_str()); - EXPECT_EQ(Status::SUCCESS, status) << "Get failed"; - EXPECT_STREQ(value.ToString().c_str(), val.ToString().c_str())<< "failed"; + Key key = { "key1" }; + Value valueLocal = { "value1" }; + auto status = singleKvStore_->Put(key, valueLocal); + ASSERT_EQ(status, SUCCESS); + + std::vector devices; + status = singleKvStore_->Sync(devices, SyncMode::PUSH); + ASSERT_EQ(status, SUCCESS); + + sleep(WAIT_TIME); + + auto flag = KvStoreSyncCallbackTestImpl::IsSyncComplete(); + ASSERT_TRUE(flag); + + Value valueRemote; + status = GetRemote(key, valueRemote); + ASSERT_EQ(status, SUCCESS); + ASSERT_EQ(valueLocal.ToString(), valueRemote.ToString()); + + ZLOGI("SyncData001 end"); } -HWTEST_F(DistributedTest, SyncData004, TestSize.Level1) +/** +* @tc.name: SyncData002 +* @tc.desc: Sync data with pull mode by other device and get data from other device +* @tc.type: FUNC +*/ +HWTEST_F(DistributedTest, SyncData002, TestSize.Level1) { - EXPECT_NE(singleKvStore_, nullptr) << "kvStorePtr is null"; - Key key = { "single1_004" }; - Value val = { "value1_004" }; - auto status = singleKvStore_->Put(key, val); - EXPECT_EQ(Status::SUCCESS, status) << "Put failed"; - - std::vector deviceIds; - for (const auto &device : detailInfos_) { - deviceIds.push_back(device.networkId); - } - status = singleKvStore_->Sync(deviceIds, SyncMode::PUSH); - EXPECT_EQ(Status::SUCCESS, status) << "Sync failed"; + ZLOGI("SyncData002 begin"); - status = manager_.DeleteKvStore({ "odmf" }, { "student_single" }, "/data/service/el1/public/database/odmf"); - EXPECT_EQ(Status::SUCCESS, status) << "Sync failed"; -} + Key key = { "key2" }; + Value valueLocal = { "value2" }; + auto status = singleKvStore_->Put(key, valueLocal); + ASSERT_EQ(status, SUCCESS); + + SyncMode mode = SyncMode::PULL; + std::string arguments = std::to_string(mode); + auto flag = RunCmdOnAgent(AGENT_NO::ONE, "sync", arguments, "0"); + ASSERT_TRUE(flag); + status = static_cast(GetReturnVal()); + ASSERT_EQ(status, SUCCESS); + + Value valueRemote; + status = GetRemote(key, valueRemote); + ASSERT_EQ(status, SUCCESS); + ASSERT_EQ(valueLocal.ToString(), valueRemote.ToString()); + + ZLOGI("SyncData002 end"); } +} // namespace OHOS::Test int main(int argc, char *argv[]) { diff --git a/kv_store/test/distributedtest/single_kvstore_client/distributed_test_agent.cpp b/kv_store/test/distributedtest/single_kvstore_client/distributed_test_agent.cpp index 107fda15..66c0a2ac 100644 --- a/kv_store/test/distributedtest/single_kvstore_client/distributed_test_agent.cpp +++ b/kv_store/test/distributedtest/single_kvstore_client/distributed_test_agent.cpp @@ -12,271 +12,219 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#define LOG_TAG "DistributedTestAgent" -#include -#include -#include -#include -#include -#include -#include "dev_manager.h" +#include + +#include + +#include "accesstoken_kit.h" #include "distributed_kv_data_manager.h" #include "types.h" #include "distributed_agent.h" -#include "refbase.h" -#include "hilog/log.h" #include "directory_ex.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "log_print.h" -using namespace testing; +using namespace testing::ext; using namespace OHOS; using namespace OHOS::DistributeSystemTest; using namespace OHOS::DistributedKv; -using namespace OHOS::HiviewDFX; - -namespace { -constexpr HiLogLabel LABEL = {LOG_CORE, 0, "DistributedTestAgent"}; -constexpr HiLogLabel LABEL_TEST = {LOG_CORE, 0, "KvStoreSyncCallbackTestImpl"}; - -class KvStoreSyncCallbackTestImpl : public KvStoreSyncCallback { +using namespace OHOS::Security::AccessToken; +namespace OHOS::Test { +class DistributedTestAgent : public DistributedAgent { public: - void SyncCompleted(const std::map &results); - std::condition_variable cv_; - bool compeleted_ = false; - std::mutex mtx_; -}; + bool SetUp() override; + bool TearDown() override; -class Util { -public: - static std::string Anonymous(const std::string &name) - { - if (name.length() <= HEAD_SIZE) { - return DEFAULT_ANONYMOUS; - } + int OnProcessMsg(const std::string &msg, int len, std::string &ret, int retLen) override; + int OnProcessCmd(const std::string &command, int len, const std::string &args, + int argsLen, const std::string &expectValue, int expectValueLen) override; - if (name.length() < MIN_SIZE) { - return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN); - } + int Get(const std::string &msg, std::string &ret); - return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN + name.substr(name.length() - END_SIZE, END_SIZE)); - } + int Put(const std::string &args); + int Delete(const std::string &args); + int Sync(const std::string &args); private: - static constexpr int32_t HEAD_SIZE = 3; - static constexpr int32_t END_SIZE = 3; - static constexpr int32_t MIN_SIZE = HEAD_SIZE + END_SIZE + 3; - static constexpr const char *REPLACE_CHAIN = "***"; - static constexpr const char *DEFAULT_ANONYMOUS = "******"; + static DistributedKvDataManager manager_; + static std::shared_ptr singleKvStore_; + static constexpr int FILE_PERMISSION = 0777; + static constexpr int WAIT_TIME = 5; + + using MessageFunction = int (DistributedTestAgent::*)(const std::string &msg, std::string &ret); + std::map messageFunctionMap_; + using CommandFunction = int (DistributedTestAgent::*)(const std::string &args); + std::map commandFunctionMap_; }; -void KvStoreSyncCallbackTestImpl::SyncCompleted(const std::map &results) -{ - for (const auto &result : results) { - HiLog::Info(LABEL_TEST, "uuid = %{public}s, status = %{public}d", - Util::Anonymous(result.first).c_str(), result.second); - } - std::lock_guard lck(mtx_); - compeleted_ = true; - cv_.notify_one(); -} +DistributedKvDataManager DistributedTestAgent::manager_; +std::shared_ptr DistributedTestAgent::singleKvStore_ = nullptr; -class DistributedTestAgent : public DistributedAgent { +class KvStoreSyncCallbackTestImpl : public KvStoreSyncCallback { public: - DistributedTestAgent(); - ~DistributedTestAgent(); - virtual bool SetUp(); - virtual bool TearDown(); - virtual int OnProcessMsg(const std::string &msg, int len, std::string &ret, int retLen); - virtual int OnProcessCmd(const std::string &command, int len, const std::string &args, - int argsLen, const std::string &expectValue, int expectValueLen); - int Get(const std::string &msg, std::string &ret) const; - int Put(const std::string &args) const; - int Delete(const std::string &args) const; - int Sync(const std::string &args) const; - int RemoveDeviceData(const std::string &args) const; - int ProcessMsg(const std::string &msg, std::string &ret); - int ProcessCmd(const std::string &command, const std::string &args); - static std::shared_ptr singleKvStore_; // declare kvstore instance - static constexpr int WAIT_FOR_TIME = 3; // wait for synccallback time is 3s. - static constexpr int FILE_PERMISSION = 0777; // 0777 is to modify the permissions of the file. + static bool IsSyncComplete() + { + bool flag = completed_; + completed_ = false; + return flag; + } + + void SyncCompleted(const std::map &results) override + { + ZLOGI("SyncCallback Called!"); + for (const auto &result : results) { + if (result.second == SUCCESS) { + completed_ = true; + } + ZLOGI("device: %{public}s, status: 0x%{public}x", result.first.c_str(), result.second); + } + } private: - DistributedKvDataManager manager_; - std::vector detailInfos_; - using CmdFunc = int (DistributedTestAgent::*)(const std::string &) const; - std::map cmdFunMap_; - using MsgFunc = int (DistributedTestAgent::*)(const std::string &, std::string &) const; - std::map msgFunMap_; + static bool completed_; }; -std::shared_ptr DistributedTestAgent::singleKvStore_ = nullptr; - -DistributedTestAgent::DistributedTestAgent() -{} - -DistributedTestAgent::~DistributedTestAgent() -{} +bool KvStoreSyncCallbackTestImpl::completed_ = false; bool DistributedTestAgent::SetUp() { - msgFunMap_["get"] = &DistributedTestAgent::Get; - cmdFunMap_["put"] = &DistributedTestAgent::Put; - cmdFunMap_["delete"] = &DistributedTestAgent::Delete; - cmdFunMap_["sync"] = &DistributedTestAgent::Sync; - cmdFunMap_["removedevicedata"] = &DistributedTestAgent::RemoveDeviceData; + const char **perms = new const char *[1]; + perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; + TokenInfoParams info = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "distributed_test", + .aplStr = "system_basic", + }; + auto tokenId = GetAccessTokenId(&info); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; Options options = { .createIfMissing = true, .encrypt = false, .autoSync = false, - .kvStoreType = KvStoreType::SINGLE_VERSION }; + .kvStoreType = KvStoreType::SINGLE_VERSION }; options.area = EL1; options.baseDir = std::string("/data/service/el1/public/database/odmf"); AppId appId = { "odmf" }; - StoreId storeId = { "student_single" }; // define kvstore(database) name. + StoreId storeId = { "student" }; mkdir(options.baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); - manager_.GetSingleKvStore(options, appId, storeId, singleKvStore_); - detailInfos_ = DevManager::GetInstance().GetRemoteDevices(); + auto status = manager_.GetSingleKvStore(options, appId, storeId, singleKvStore_); + if (status != SUCCESS || singleKvStore_ == nullptr) { + return false; + } OHOS::ChangeModeDirectory(options.baseDir, FILE_PERMISSION); + + std::shared_ptr syncCallback = std::make_shared(); + status = singleKvStore_->RegisterSyncCallback(syncCallback); + if (status != SUCCESS) { + return false; + } + + messageFunctionMap_["get"] = &DistributedTestAgent::Get; + + commandFunctionMap_["put"] = &DistributedTestAgent::Put; + commandFunctionMap_["sync"] = &DistributedTestAgent::Sync; return true; } bool DistributedTestAgent::TearDown() { + (void)manager_.CloseAllKvStore({ "odmf" }); + (void)manager_.DeleteKvStore({ "odmf" }, { "student" }, "/data/service/el1/public/database/odmf"); (void)remove("/data/service/el1/public/database/odmf/key"); (void)remove("/data/service/el1/public/database/odmf/kvdb"); (void)remove("/data/service/el1/public/database/odmf"); return true; } -int DistributedTestAgent::OnProcessCmd(const std::string &command, int len, - const std::string &args, int argsLen, const std::string &expectValue, int expectValueLen) +int DistributedTestAgent::OnProcessMsg(const std::string &msg, int len, std::string &ret, int retLen) { - return DistributedTestAgent::ProcessCmd(command, args); + if (msg == "SendMessage") { + ret = "Send Message OK!"; + return ret.size(); + } + auto index = msg.find(","); + std::string function = msg.substr(0, index); + auto iter = messageFunctionMap_.find(function); + if (iter != messageFunctionMap_.end()) { + return (this->*messageFunctionMap_[function])(msg.substr(index + 1), ret); + } + return DistributedAgent::OnProcessMsg(msg, len, ret, retLen); } -int DistributedTestAgent::OnProcessMsg(const std::string &msg, int len, - std::string &ret, int retLen) +int DistributedTestAgent::OnProcessCmd(const std::string &command, int len, + const std::string &args, int argsLen, const std::string &expectValue, int expectValueLen) { - return DistributedTestAgent::ProcessMsg(msg, ret); + if (command == "CommandTest") { + return SUCCESS; + } + auto iter = commandFunctionMap_.find(command); + if (iter != commandFunctionMap_.end()) { + return (this->*commandFunctionMap_[command])(args); + } + return DistributedAgent::OnProcessCmd(command, len, args, argsLen, expectValue, expectValueLen); } -int DistributedTestAgent::Get(const std::string &msg, std::string &ret) const +int DistributedTestAgent::Get(const std::string &msg, std::string &ret) { - if (!singleKvStore_) { - HiLog::Error(LABEL, "agent ERROR."); - return Status::INVALID_ARGUMENT; - } - auto index = msg.find(","); - std::string skey = msg.substr(index+1); - Key key(skey); + Key key(msg); Value value; auto status = singleKvStore_->Get(key, value); - HiLog::Info(LABEL, "value = %{public}s", value.ToString().c_str()); - ret = value.ToString(); + ret = std::to_string(status); ret += ","; - ret += std::to_string(status); - HiLog::Info(LABEL, "ret = %{public}s", ret.c_str()); + if (status == SUCCESS) { + ret += value.ToString(); + } return ret.size(); } -int DistributedTestAgent::Put(const std::string &args) const +int DistributedTestAgent::Put(const std::string &args) { - if (!singleKvStore_) { - HiLog::Error(LABEL, "agent ERROR."); - return Status::INVALID_ARGUMENT; - } auto index = args.find(","); - std::string skey = args.substr(0, index); - std::string sval = args.substr(index + 1); - Key key(skey); - Value value(sval); + Key key(args.substr(0, index)); + Value value(args.substr(index + 1)); auto status = singleKvStore_->Put(key, value); return status; } -int DistributedTestAgent::Delete(const std::string &args) const +int DistributedTestAgent::Sync(const std::string &args) { - if (!singleKvStore_) { - HiLog::Error(LABEL, "agent ERROR."); - return Status::INVALID_ARGUMENT; - } - Key key(args); - Status status = singleKvStore_->Delete(key); - return status; -} + SyncMode syncMode = static_cast(std::stoi(args)); + std::vector devices; + auto status = singleKvStore_->Sync(devices, syncMode); -int DistributedTestAgent::RemoveDeviceData(const std::string &args) const -{ - if (!singleKvStore_) { - HiLog::Error(LABEL, "agent ERROR."); - return Status::INVALID_ARGUMENT; - } - HiLog::Info(LABEL, "deviceId = %{public}s", Util::Anonymous(detailInfos_[0].networkId).c_str()); - auto status = singleKvStore_->RemoveDeviceData(detailInfos_[0].networkId); - return status; -} + sleep(WAIT_TIME); -int DistributedTestAgent::Sync(const std::string &args) const -{ - if (!singleKvStore_) { - HiLog::Error(LABEL, "agent ERROR."); - return Status::INVALID_ARGUMENT; - } - auto syncCallback = std::make_shared(); - auto status = singleKvStore_->RegisterSyncCallback(syncCallback); - if (status != Status::SUCCESS) { - HiLog::Info(LABEL, "register sync callback failed."); - return Status::INVALID_ARGUMENT; - } - std::vector deviceIds; - for (const auto &device : detailInfos_) { - deviceIds.push_back(device.networkId); + auto flag = KvStoreSyncCallbackTestImpl::IsSyncComplete(); + if (!flag) { + status = TIME_OUT; } - int32_t delay = std::stoi(args); - HiLog::Info(LABEL, "delay = %{public}d", delay); - std::unique_lock lck(syncCallback->mtx_); - status = singleKvStore_->Sync(deviceIds, SyncMode::PULL, delay); - if (!syncCallback->cv_.wait_for(lck, std::chrono::seconds(WAIT_FOR_TIME), - [&syncCallback]() { return syncCallback->compeleted_; })) { - status = Status::TIME_OUT; - } - HiLog::Info(LABEL, "status = %{public}d", status); return status; } - -int DistributedTestAgent::ProcessMsg(const std::string &msg, std::string &ret) -{ - auto index = msg.find(","); - std::string argsMsg = msg.substr(0, index); - std::map::iterator it = msgFunMap_.find(argsMsg); - if (it != msgFunMap_.end()) { - MsgFunc MsgFunc = msgFunMap_[argsMsg]; - return (this->*MsgFunc)(msg, ret); - } - return Status::INVALID_ARGUMENT; -} - -int DistributedTestAgent::ProcessCmd(const std::string &command, const std::string &args) -{ - std::map::iterator it = cmdFunMap_.find(command); - if (it != cmdFunMap_.end()) { - CmdFunc CmdFunc = cmdFunMap_[command]; - return (this->*CmdFunc)(args); - } - return Status::INVALID_ARGUMENT; -} -} +} // namespace OHOS::Test int main() { - DistributedTestAgent obj; + OHOS::Test::DistributedTestAgent obj; if (obj.SetUp()) { + ZLOGE("Init environment success."); obj.Start("agent.desc"); obj.Join(); } else { - HiLog::Error(LABEL, "Init environment failed."); + ZLOGE("Init environment fail."); } if (obj.TearDown()) { + ZLOGE("Clear environment success."); return 0; } else { - HiLog::Error(LABEL, "Clear environment failed."); + ZLOGE("Clear environment failed."); return -1; } -} +} \ No newline at end of file diff --git a/kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.cpp b/kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.cpp deleted file mode 100644 index 8509e953..00000000 --- a/kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.cpp +++ /dev/null @@ -1,91 +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 "distributed_test_helper.h" - -using namespace OHOS; -using namespace testing::ext; -using namespace OHOS::DistributedKv; -using namespace OHOS::DistributeSystemTest; -using namespace OHOS::HiviewDFX; - -void DistributedTestHelper::SetUpTestCase(void) -{} - -void DistributedTestHelper::TearDownTestCase(void) -{} - -void DistributedTestHelper::SetUp() -{} - -void DistributedTestHelper::TearDown() -{} - -void DistributedTestHelper::TestBody() -{} - -Status DistributedTestHelper::GetRemote(const Key &key, Value &value) -{ - std::string msg = "get"; - msg += ","; - msg += key.ToString(); - Status status; - SendMessage(AGENT_NO::ONE, msg, msg.size(), [&](const std::string &buf, int len)->bool { - auto index = buf.find(","); - std::string temp = buf.substr(0, index); - value = temp; - temp = buf.substr(index + 1); - status = Status(std::stoi(temp)); - return true; - }); - return status; -} - -Status DistributedTestHelper::PutRemote(const Key &key, const Value &value) -{ - std::string command = "put"; - std::string args = key.ToString(); - args += ","; - args += value.ToString(); - RunCmdOnAgent(AGENT_NO::ONE, command, args, "0"); - Status status = Status(GetReturnVal()); - return status; -} - -Status DistributedTestHelper::DeleteRemote(const Key &key) -{ - std::string command = "delete"; - std::string skey = key.ToString(); - RunCmdOnAgent(AGENT_NO::ONE, command, skey, "0"); - Status status = Status(GetReturnVal()); - return status; -} - -Status DistributedTestHelper::RemoveDeviceDataRemote() -{ - std::string command = "removedevicedata"; - RunCmdOnAgent(AGENT_NO::ONE, command, "0", "0"); - Status status = Status(GetReturnVal()); - return status; -} - -Status DistributedTestHelper::SyncRemote(SyncMode mode, uint32_t delay) -{ - std::string command = "sync"; - std::string sdelay = std::to_string(delay); - RunCmdOnAgent(AGENT_NO::ONE, command, sdelay, "0"); - Status status = Status(GetReturnVal()); - return status; -} \ No newline at end of file diff --git a/mock/CMakeLists.txt b/mock/CMakeLists.txt index b5998ac1..a021da83 100644 --- a/mock/CMakeLists.txt +++ b/mock/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(mock) set(CMAKE_CXX_STANDARD 17) @@ -22,15 +22,238 @@ add_definitions(-DL_ENDIAN -DUNICODE -D_UNICODE -DWIN32_LEAN_AND_MEAN -D_MT -DWI add_definitions(-DNAPI_EXPERIMENTAL -DSQLITE_DISTRIBUTE_RELATIONAL) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src mockSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/sqlite/src mockSrc) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/napi) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/napi/src) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/uapi) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/sqlite/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) set(MOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}) include(${CMAKE_CURRENT_SOURCE_DIR}/include/CMakeLists.txt OPTIONAL) set(links secure crypto) add_library(mock SHARED ${mockSrc}) target_link_libraries(mock ${links}) + +target_include_directories(mock PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/) +target_include_directories(mock PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/napi) +target_include_directories(mock PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/napi/src) +target_include_directories(mock PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/uapi) +target_include_directories(mock PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/sqlite/include) +target_include_directories(mock PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}) +target_include_directories(mock PUBLIC ${MOCK_DIR}/napi/src) +target_include_directories(mock PUBLIC ${MOCK_DIR}/libuv/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/miscdevice/vibrator_interface_native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/soc_perf/socperf_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/memmgr/memmgrclient/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/pasteboard_native/pasteboard_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/frame_aware_sched/frame_msg_intf/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/frame_aware_sched/frame_ui_intf/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/multimedia_image_standard/image/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/multimedia_image_standard/image_native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/input/libmmi-client/include/event/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/input/libmmi-client/include/proxy/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/form_fwk/fmskit_native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/form_fwk/form_manager/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/startup_l2/syspara/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/startup_l2/syspara_watchagent/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/distributed_screen/distributed_screen_sink_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/distributed_screen/distributed_screen_source_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/bluetooth/btframework/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/cellular_data/tel_cellular_data_api/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/state_registry/tel_state_registry_api/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/config_policy/configpolicy_util/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/faultloggerd/dfx_signalhandler/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/faultloggerd/libfaultloggerd/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/faultloggerd/lib_dfx_dump_catcher/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/netmanager_base/innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/netmanager_base/innerkits/netconnclient/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/netmanager_base/innerkits/netconnclient/include/proxy) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/netmanager_base/innerkits/netmanagernative/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/netmanager_base/innerkits/netpolicyclient/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/netmanager_base/innerkits/netstatsclient/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/accessibility/accessibilityconfig/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/accessibility/accessibleability/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/accessibility/accessibilityclient/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/accessibility/accessibility_common/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/safwk/system_ability_fwk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hilog_native/libhilog/include/hilog) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hilog_native/libhilog/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/device_auth/deviceauth_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/window_manager/libwindow_extension_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/window_manager/libwm/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/window_manager/libdm/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/battery_manager_native/batterysrv_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hidumper/lib_dump_usage/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hidumper/utils/native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/enterprise_device_management/edmservice_kits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/time_native/time_service/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/time_native/time_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/access_token/libaccesstoken_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/access_token/libnativetoken/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/access_token/libprivacy_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/access_token/token_setproc/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/resource_management/resmgr_napi_core/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/resource_management/global_resmgr/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/graphic_chipsetsdk/surface/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/media_library/media_library/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/media_library/medialibrary/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_base/zuri/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_base/base/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_base/want/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_base/configuration/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/graphic_graphic_2d/libgraphic_utils/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/graphic_graphic_2d/libcomposer/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/graphic_graphic_2d/libvsync_module/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/graphic_graphic_2d/libvsync_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/graphic_graphic_2d/surface/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/graphic_graphic_2d/window_animation/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/device_usage_statistics/usagestatsinner/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hitrace_native/hitrace_meter/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hitrace_native/libhitrace/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hitrace_native/libhitrace/include/hitrace) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hicollie_native/libhicollie/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hicollie_native/libhicollie/include/xcollie) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/battery_statistics_native/batterystats_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/wifi/wifi_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/core_service/libtel_common/include/preferences/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/core_service/libtel_common/include/common/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/core_service/libtel_common/include/log/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/core_service/tel_core_service_api/include/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/core_service/tel_core_service_api/include/ims/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/sensor/sensor_interface_native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/cellular_call/tel_ims_call_callback_proxy/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_peripheral_light/hdi_light/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/storage_service/storage_manager_sa_proxy/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appverify/libhapverify/include/provision) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appverify/libhapverify/include/interfaces) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appverify/libhapverify/include/common) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/webview/libnweb/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/os_account/os_account_innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/os_account/common/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/os_account/libaccountkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/os_account/app_account_innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/inputmethod_native/inputmethod/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/inputmethod_native/inputmethodengine/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_service/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_ability/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/dmsfwk_standard/common_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/dmsfwk_standard/continuation_manager/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/napi/ace_container_scope/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/napi/ace_napi/include/napi) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/device_profile_core/distributed_device_profile_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hiview/libfaultlogger/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/syscap_codec/syscap_interface_shared/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ipc/ipc_single/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ipc/ipc_core/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ipc/libdbinder/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/i18n/zone_util/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/i18n/intl_util/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/i18n/preferred_language/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hichecker_native/libhichecker/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/usb_manager/usbsrv_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/call_manager/tel_call_manager_api/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hiperf/hiperf_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/ability_context_native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/ability_manager/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/ability_manager/include/continuation) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/abilitykit_native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/app_manager/include/appmgr) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/dataobs_manager/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/extension_manager/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/mock) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/napi_base_context/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/napi_common) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/runtime/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/uri_permission/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ability_runtime/wantagent_innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appexecfwk_base/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appexecfwk_base/include/distributed_manager) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appexecfwk_base/include/free_install) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appexecfwk_base/include/quick_fix) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appexecfwk_core/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appexecfwk_core/include/bundlemgr) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/appexecfwk_core/include/default_app) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/dataclassification/data_transit_mgr/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/bundle_framework/appexecfwk_core/include/bundlemgr) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/bundle_framework/appexecfwk_base/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/selinux/libhap_restorecon/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/selinux/librestorecon/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/selinux/libload_policy/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/selinux/libservice_checker/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/selinux/libparaperm_checker/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_peripheral_camera/metadata/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_peripheral_camera/libcamera_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/device_manager/devicemanagersdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/thermal_manager/thermalsrv_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/thermal_manager/thermalmgr_listener/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/display_manager_native/displaymgr/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/common_event_service/cesfwk_services/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/common_event_service/cesfwk_core/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/common_event_service/cesfwk_innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ipc_js/rpc/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/face_auth/faceauth_framework/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/dsoftbus/softbus_client/include/transport) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/dsoftbus/softbus_client/include/discovery) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/dsoftbus/softbus_client/include/bus_center) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/dsoftbus/softbus_client/include/common) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/background_task_mgr/bgtaskmgr_innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/eventhandler/eventhandler_native/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/eventhandler/libeventhandler/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/distributed_camera/distributed_camera_sink_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/distributed_camera/distributed_camera_source_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ace_engine/ace_uicontent/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/profiler/libhidebug/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/device_security_level/dslm_sdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/user_auth_framework/coauth_framework/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/user_auth_framework/userauth/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/user_auth_framework/userauth_napi/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/user_auth_framework/userauth_framework/include/common) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/user_auth_framework/userauth_framework/include/user_auth) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/user_auth_framework/useridm_framework/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/samgr_standard/lsamgr/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/samgr_standard/samgr_proxy/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/samgr_standard/samgr_common/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/power_manager_native/powermgr_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_peripheral_usb/usbd_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hisysevent_native/libhisyseventmanager/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hisysevent_native/libhisysevent/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/init/libbegetutil/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/init/libbegetutil/include/syspara) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/init/libbegetutil/include/fs_manager) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/init/libinit_module_engine/include/init_module_engine/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/init/libbeget_proxy/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/init/libbeget_proxy/include/syspara) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/resource_schedule_service/ressched_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/huks/libhukssdk/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_interface_ril/hril_innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_interface_usb/usbd_client/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/ril_adapter/hril_innerkits/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_peripheral_input/hdi_input/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hdf_core/libhdf_host/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hdf_core/libhdf_ipc_adapter/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hdf_core/libhdf_utils/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/hdf_core/libhdi/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_interface_input/hdi_input/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_peripheral_vibrator/hdi_vibrator/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/drivers_peripheral_sensor/hdi_sensor/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/napi) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/napi/native_engine) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/filemanagement/file_api/interfaces/kits) +target_include_directories(mock PUBLIC ${MOCK_DIR}/innerkits/filemanagement/app_file_service/interfaces/innerkits/native/remote_file_share/include) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/ability_runtime) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit/ability_delegator) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit/ability_delegator/runner_runtime) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit/ability_runtime) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit/ability_runtime/app) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit/app) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit/app/task) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/appkit/ability_runtime/context) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/native/ability_runtime) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/native/continuation/distributed) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/native/continuation/kits) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/native/continuation/remote_register_service) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/native/distributed_ability_runtime) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/native/form_runtime) +target_include_directories(mock PUBLIC ${MOCK_DIR}/kits/ability/native) +target_include_directories(mock PUBLIC ${MOCK_DIR}/sqlite/include) \ No newline at end of file diff --git a/preferences/CMakeLists.txt b/preferences/CMakeLists.txt index f2ad819a..55e0732c 100644 --- a/preferences/CMakeLists.txt +++ b/preferences/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(preferences) set(CMAKE_CXX_STANDARD 17) @@ -6,21 +6,24 @@ 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") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wformat=0") +set(KV_STORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store) set(MOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../mock) add_definitions(-DNAPI_EXPERIMENTAL) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/src preferences_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/common/src preferences_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/platform/src preferences_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/src preferences_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/common/src preferences_src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/common/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/platform/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/safwk/native/include) +include_directories(${KV_STORE_DIR}/frameworks/common) FIND_PACKAGE(LibXml2) IF (LibXml2_FOUND) @@ -35,4 +38,5 @@ include(${MOCK_DIR}/include/CMakeLists.txt OPTIONAL) set(links secure mock relational_store xml2) add_library(preferences SHARED ${preferences_src}) -target_link_libraries(preferences ${links}) \ No newline at end of file +target_link_libraries(preferences ${links}) +target_include_directories(preferences PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/include) \ No newline at end of file diff --git a/preferences/frameworks/common/include/log_print.h b/preferences/frameworks/common/include/log_print.h index eec59284..c55f43e2 100644 --- a/preferences/frameworks/common/include/log_print.h +++ b/preferences/frameworks/common/include/log_print.h @@ -50,22 +50,30 @@ static inline OHOS::HiviewDFX::HiLogLabel LogLabel() } \ } 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__); \ - } \ +#define LOG_RECORD_FILE_NAME(message) \ + do { \ + const char *name = fileName.data(); \ + auto pos = fileName.rfind('/'); \ + pos = (pos != std::string::npos) ? pos + 1 : 0; \ + LOG_DEBUG(message " fileName is %{private}s.", name + pos); \ } 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__); \ - } \ +#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, ...) \ diff --git a/preferences/frameworks/js/napi/common/include/js_logger.h b/preferences/frameworks/js/napi/common/include/js_logger.h deleted file mode 100644 index 8b4ac2bc..00000000 --- a/preferences/frameworks/js/napi/common/include/js_logger.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2021 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 PRE_JSKIT_LOGGER_H -#define PRE_JSKIT_LOGGER_H - -#include -#include - -#include "hilog/log.h" - -namespace OHOS { -namespace PreferencesJsKit { -static const OHOS::HiviewDFX::HiLogLabel PREFIX_LABEL = { LOG_CORE, 0xD001653, "PreferencesJsKit" }; -#define LOG_DEBUG(...) ((void)OHOS::HiviewDFX::HiLog::Debug(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_INFO(...) ((void)OHOS::HiviewDFX::HiLog::Info(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_WARN(...) ((void)OHOS::HiviewDFX::HiLog::Warn(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_ERROR(...) ((void)OHOS::HiviewDFX::HiLog::Error(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_FATAL(...) ((void)OHOS::HiviewDFX::HiLog::Fatal(PREFIX_LABEL, __VA_ARGS__)) -} // namespace PreferencesJsKit -} // namespace OHOS - -#endif diff --git a/preferences/frameworks/js/napi/common/include/js_utils.h b/preferences/frameworks/js/napi/common/include/js_utils.h index 7729f6b3..1b15d858 100644 --- a/preferences/frameworks/js/napi/common/include/js_utils.h +++ b/preferences/frameworks/js/napi/common/include/js_utils.h @@ -49,8 +49,6 @@ int32_t Convert2NativeValue(napi_env env, napi_value jsValue, int64_t &output); int32_t Convert2NativeValue(napi_env env, napi_value jsValue, std::string &output); int32_t Convert2NativeValue(napi_env env, napi_value jsValue, std::monostate &value); -template int32_t Convert2NativeValue(napi_env env, napi_value jsValue, T &output); - template int32_t Convert2NativeValue(napi_env env, napi_value jsValue, std::vector &value); template diff --git a/preferences/frameworks/js/napi/common/src/js_utils.cpp b/preferences/frameworks/js/napi/common/src/js_utils.cpp index 655d5e62..df3f8f62 100644 --- a/preferences/frameworks/js/napi/common/src/js_utils.cpp +++ b/preferences/frameworks/js/napi/common/src/js_utils.cpp @@ -25,30 +25,25 @@ namespace OHOS { namespace PreferencesJsKit { int32_t JSUtils::Convert2NativeValue(napi_env env, napi_value jsValue, std::string &output) { - size_t strBufferSize = 0; - napi_status status = napi_get_value_string_utf8(env, jsValue, nullptr, 0, &strBufferSize); + size_t bufferSize = 0; + napi_status status = napi_get_value_string_utf8(env, jsValue, nullptr, 0, &bufferSize); if (status != napi_ok) { LOG_DEBUG("get std::string failed, status = %{public}d", status); return napi_invalid_arg; } - if (strBufferSize > MAX_VALUE_LENGTH) { + if (bufferSize > MAX_VALUE_LENGTH) { LOG_ERROR("get std::string maximum length."); return EXCEED_MAX_LENGTH; } - char *str = new (std::nothrow) char[strBufferSize + 1]; - if (str == nullptr) { - return napi_invalid_arg; - } - size_t valueSize = 0; - status = napi_get_value_string_utf8(env, jsValue, str, strBufferSize + 1, &valueSize); + char *buffer = (char *)malloc(bufferSize + 1); + status = napi_get_value_string_utf8(env, jsValue, buffer, bufferSize + 1, &bufferSize); if (status != napi_ok) { + free(buffer); LOG_DEBUG("JSUtils::Convert2NativeValue get jsVal failed, status = %{public}d", status); - delete[] str; return napi_invalid_arg; } - str[valueSize] = 0; - output = std::string(str); - delete[] str; + output = buffer; + free(buffer); return napi_ok; } diff --git a/preferences/frameworks/native/common/mock/include/data_preferences_observer_stub.h b/preferences/frameworks/native/common/mock/include/data_preferences_observer_stub.h deleted file mode 100644 index 9d8dad4e..00000000 --- a/preferences/frameworks/native/common/mock/include/data_preferences_observer_stub.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 PREFERENCES_DATA_PREFERENCES_OBSERVER_STUB_H -#define PREFERENCES_DATA_PREFERENCES_OBSERVER_STUB_H - -#include -#include - -#include "preferences_observer.h" - -namespace OHOS { -class Uri { -public: - Uri(const std::string str) - { - } -}; -template -using sptr = std::shared_ptr; -namespace NativePreferences { - -class DataPreferencesObserverStub { -public: - DataPreferencesObserverStub(const std::shared_ptr preferencesObserver); - virtual ~DataPreferencesObserverStub(); - void OnChange(); - void OnChangePreferences(const std::string &key); -public: - std::weak_ptr preferencesObserver_; -}; - -class DataObsMgrClient { -public: - static std::shared_ptr GetInstance(); - DataObsMgrClient(); - ~DataObsMgrClient(); - int RegisterObserver(const Uri &uri, sptr dataObserver); - int UnregisterObserver(const Uri &uri, sptr dataObserver); - int NotifyChange(const Uri &uri); -private: - static std::mutex mutex_; - static std::shared_ptr instance_; -}; -} // End of namespace NativePreferences -} // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_DATA_PREFERENCES_OBSERVER_STUB_H diff --git a/preferences/frameworks/native/common/mock/src/data_preferences_observer_stub.cpp b/preferences/frameworks/native/common/mock/src/data_preferences_observer_stub.cpp deleted file mode 100644 index d40ca47b..00000000 --- a/preferences/frameworks/native/common/mock/src/data_preferences_observer_stub.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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 "data_preferences_observer_stub.h" - -#include "preferences_errno.h" - -namespace OHOS { -namespace NativePreferences { -std::shared_ptr DataObsMgrClient::instance_ = nullptr; -std::mutex DataObsMgrClient::mutex_; - -DataPreferencesObserverStub::DataPreferencesObserverStub(const std::shared_ptr preferencesObserver) - : preferencesObserver_(preferencesObserver) -{ -} - -DataPreferencesObserverStub::~DataPreferencesObserverStub() -{ -} - -void DataPreferencesObserverStub::OnChange() -{ -} - -void DataPreferencesObserverStub::OnChangePreferences(const std::string &key) -{ - std::shared_ptr sharedPreferencesObserver = preferencesObserver_.lock(); - if (sharedPreferencesObserver != nullptr) { - sharedPreferencesObserver->OnChange(key); - } -} - -DataObsMgrClient::DataObsMgrClient() -{ -} - -DataObsMgrClient::~DataObsMgrClient() -{ -} - -std::shared_ptr DataObsMgrClient::GetInstance() -{ - if (instance_ == nullptr) { - std::lock_guard lock(mutex_); - if (instance_ == nullptr) { - instance_ = std::make_shared(); - } - } - return instance_; -} - -int DataObsMgrClient::RegisterObserver(const Uri &uri, sptr dataObserver) -{ - return E_NOT_SUPPORTED; -} - -int DataObsMgrClient::UnregisterObserver(const Uri &uri, sptr dataObserver) -{ - return E_NOT_SUPPORTED; -} - -int DataObsMgrClient::NotifyChange(const Uri &uri) -{ - return E_NOT_SUPPORTED; -} -} // End of namespace NativePreferences -} // End of namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/common/src/data_preferences_observer_stub.cpp b/preferences/frameworks/native/common/src/data_preferences_observer_stub.cpp deleted file mode 100644 index f7754704..00000000 --- a/preferences/frameworks/native/common/src/data_preferences_observer_stub.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 "data_preferences_observer_stub.h" - -namespace OHOS { -namespace NativePreferences { -DataPreferencesObserverStub::DataPreferencesObserverStub( - const std::shared_ptr preferencesObserver) : preferencesObserver_(preferencesObserver) -{ -} - -DataPreferencesObserverStub::~DataPreferencesObserverStub() -{ -} - -void DataPreferencesObserverStub::OnChange() -{ -} - -void DataPreferencesObserverStub::OnChangePreferences(const std::string &key) -{ - std::shared_ptr sharedPreferencesObserver = preferencesObserver_.lock(); - if (sharedPreferencesObserver != nullptr) { - sharedPreferencesObserver->OnChange(key); - } -} -} // End of namespace NativePreferences -} // End of namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/include/executor_pool.h b/preferences/frameworks/native/include/executor_pool.h index b2e11532..7070bcb1 100644 --- a/preferences/frameworks/native/include/executor_pool.h +++ b/preferences/frameworks/native/include/executor_pool.h @@ -22,10 +22,10 @@ #include #include "executor.h" +#include "log_print.h" #include "pool.h" #include "priority_queue.h" - namespace OHOS { namespace NativePreferences { class ExecutorPool { @@ -77,6 +77,7 @@ public: TaskId Execute(Task task) { if (poolStatus != Status::RUNNING) { + LOG_ERROR("execute task failed."); return INVALID_TASK_ID; } diff --git a/preferences/frameworks/native/include/logger.h b/preferences/frameworks/native/include/logger.h deleted file mode 100644 index b5f61f47..00000000 --- a/preferences/frameworks/native/include/logger.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2021 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 NATIVE_PREFERENCES_LOGGER_H -#define NATIVE_PREFERENCES_LOGGER_H - -#include "hilog/log.h" - -namespace OHOS { -namespace NativePreferences { -static const OHOS::HiviewDFX::HiLogLabel DFS_LABEL = { LOG_CORE, 0xD001653, "NativePreferences" }; - -#define LOG_DEBUG(...) ((void)OHOS::HiviewDFX::HiLog::Debug(DFS_LABEL, __VA_ARGS__)) -#define LOG_INFO(...) ((void)OHOS::HiviewDFX::HiLog::Info(DFS_LABEL, __VA_ARGS__)) -#define LOG_WARN(...) ((void)OHOS::HiviewDFX::HiLog::Warn(DFS_LABEL, __VA_ARGS__)) -#define LOG_ERROR(...) ((void)OHOS::HiviewDFX::HiLog::Error(DFS_LABEL, __VA_ARGS__)) -#define LOG_FATAL(...) ((void)OHOS::HiviewDFX::HiLog::Fatal(DFS_LABEL, __VA_ARGS__)) -} // namespace NativePreferences -} // namespace OHOS - -#endif // NATIVE_PREFERENCES_LOGGER_H \ No newline at end of file diff --git a/preferences/frameworks/native/include/preferences_impl.h b/preferences/frameworks/native/include/preferences_impl.h index 1245f60f..6bdf6c4e 100644 --- a/preferences/frameworks/native/include/preferences_impl.h +++ b/preferences/frameworks/native/include/preferences_impl.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -29,22 +29,12 @@ #include "preferences.h" #include "preferences_observer.h" #include "preferences_value.h" -#include "executor_pool.h" - -#if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) || defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) -#include "data_preferences_observer_stub.h" -#else namespace OHOS { -template class sptr; +template class sptr; class Uri; -} // namespace OHOS -#endif - -namespace OHOS { namespace NativePreferences { - class DataPreferencesObserverStub; - +class ExecutorPool; static const char *STR_BROKEN = ".broken"; static const char *STR_BACKUP = ".bak"; static const char *STR_LOCK = ".lock"; @@ -166,6 +156,7 @@ public: int UnRegisterObserver(std::shared_ptr preferencesObserver, RegisterMode mode) override; static std::string MakeFilePath(const std::string &prefPath, const std::string &suffix); + private: explicit PreferencesImpl(const Options &options); class MemoryToDiskRequest { @@ -173,9 +164,7 @@ private: MemoryToDiskRequest(const std::map &writeToDiskMap, const std::list &keysModified, const std::vector> preferencesObservers, int64_t memStataGeneration); - ~MemoryToDiskRequest() - { - } + ~MemoryToDiskRequest() {} void SetDiskWriteResult(bool wasWritten, int result); bool isSyncRequest_; @@ -201,7 +190,7 @@ private: static void LoadFromDisk(std::shared_ptr pref); void AwaitLoadFile(); static void WriteToDiskFile(std::shared_ptr pref, std::shared_ptr mcr); - bool CheckRequestValidForStateGeneration(const MemoryToDiskRequest &mcr); + bool CheckRequestValidForStateGeneration(std::shared_ptr mcr); bool ReadSettingXml(const std::string &prefPath, std::map &prefMap); bool WriteSettingXml(const std::string &prefPath, const std::map &prefMap); diff --git a/preferences/frameworks/native/common/include/data_preferences_observer_stub.h b/preferences/frameworks/native/include/preferences_observer_stub.h similarity index 70% rename from preferences/frameworks/native/common/include/data_preferences_observer_stub.h rename to preferences/frameworks/native/include/preferences_observer_stub.h index 65248ad9..c6e1e9b2 100644 --- a/preferences/frameworks/native/common/include/data_preferences_observer_stub.h +++ b/preferences/frameworks/native/include/preferences_observer_stub.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -25,17 +25,25 @@ namespace NativePreferences { using DataObsMgrClient = AAFwk::DataObsMgrClient; class DataPreferencesObserverStub : public AAFwk::DataAbilityObserverStub { public: - DataPreferencesObserverStub(const std::shared_ptr preferencesObserver); + DataPreferencesObserverStub(const std::shared_ptr preferencesObserver) + : preferencesObserver_(preferencesObserver) + {} - virtual ~DataPreferencesObserverStub(); + virtual ~DataPreferencesObserverStub() {} - void OnChange() override; + void OnChange() override {} - void OnChangePreferences(const std::string &key) override; + void OnChangePreferences(const std::string &key) override + { + std::shared_ptr sharedPreferencesObserver = preferencesObserver_.lock(); + if (sharedPreferencesObserver != nullptr) { + sharedPreferencesObserver->OnChange(key); + } + } public: std::weak_ptr preferencesObserver_; }; } // End of namespace NativePreferences } // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_DATA_PREFERENCES_OBSERVER_STUB_H +#endif // End of #ifndef PREFERENCES_DATA_PREFERENCES_OBSERVER_STUB_H \ No newline at end of file diff --git a/preferences/frameworks/native/include/priority_queue.h b/preferences/frameworks/native/include/priority_queue.h index 6248c6e0..115031d3 100644 --- a/preferences/frameworks/native/include/priority_queue.h +++ b/preferences/frameworks/native/include/priority_queue.h @@ -21,7 +21,6 @@ #include #include #include -#include namespace OHOS { namespace NativePreferences { diff --git a/preferences/frameworks/native/include/task_pool.h b/preferences/frameworks/native/include/task_pool.h deleted file mode 100644 index aeeb0972..00000000 --- a/preferences/frameworks/native/include/task_pool.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2021 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 TASK_POOL_H -#define TASK_POOL_H - -#include -#include -#include -#include -#include - -#include "task_queue.h" - -namespace OHOS { -namespace NativePreferences { -class TaskPool { -public: - // maxThreads > 0. - TaskPool(int maxThreads, int minThreads); - - // Start the task pool. - int Start(); - - // Stop the task pool. - void Stop(); - - // Schedule a task, the task can be ran in any thread. - int Schedule(const Task &task); - - // Schedule tasks one by one. - int Schedule(const std::string &queueTag, const Task &task); - - // Shrink memory associated with the given tag if possible. - void ShrinkMemory(const std::string &tag); - - // Status report. - void Report(); - - ~TaskPool(); - -private: - int SpawnThreads(bool isStart); - bool IdleExit(std::unique_lock &lock); - void SetThreadFree(); - Task ReapTask(TaskQueue *&queue); - int GetTask(Task &task, TaskQueue *&queue); - bool IsGenericWorker() const; - void BecomeGenericWorker(); - void ExitGenericWorker(); - void TaskWorker(); - void FinishExecuteTask(TaskQueue *taskQueue); - void TryToSpawnThreads(); - - // Member Variables - static constexpr int IDLE_WAIT_PERIOD = 1; // wait 1 second before exiting. - std::mutex tasksMutex_; - std::condition_variable hasTasks_; - std::map queuedTasks_; - TaskQueue genericTasks_; - std::thread::id genericThread_; // execute generic task only. - int genericTaskCount_; - int queuedTaskCount_; - bool isStarted_; - bool isStopping_; // Stop() invoked. - bool isGenericThreadIdle_; - std::condition_variable allThreadsExited_; - - // Thread counter. - int maxThreads_; - int minThreads_; - int curThreads_; - int idleThreads_; -}; -} // namespace NativePreferences -} // namespace OHOS -#endif // TASK_POOL_H \ No newline at end of file diff --git a/preferences/frameworks/native/include/task_scheduler.h b/preferences/frameworks/native/include/task_scheduler.h deleted file mode 100644 index cc2f2d6a..00000000 --- a/preferences/frameworks/native/include/task_scheduler.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_PREFERENCES_FRAMEWORKS_COMMON_TASK_SCHEDULER_H -#define OHOS_PREFERENCES_FRAMEWORKS_COMMON_TASK_SCHEDULER_H -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "visibility.h" -namespace OHOS { -class API_LOCAL TaskScheduler { -public: - using TaskId = uint64_t; - using Time = std::chrono::steady_clock::time_point; - using Task = std::function; - inline static constexpr TaskId INVALID_TASK_ID = static_cast(0ULL); - TaskScheduler(const std::string &name) - { - capacity_ = std::numeric_limits::max(); - isRunning_ = true; - taskId_ = INVALID_TASK_ID; - thread_ = std::make_unique([this, name]() { - auto realName = std::string("task_queue_") + name; -#if defined(MAC_PLATFORM) || defined(IOS_PLATFORM) - pthread_setname_np(realName.c_str()); -#else - pthread_setname_np(pthread_self(), realName.c_str()); -#endif - Loop(); - }); - } - - ~TaskScheduler() - { - isRunning_ = false; - { - std::unique_lock lock(mutex_); - indexes_.clear(); - tasks_.clear(); - } - At(std::chrono::steady_clock::now(), []() {}); - thread_->join(); - } - - // execute task at specific time - TaskId At(const Time &time, Task task) - { - std::unique_lock lock(mutex_); - if (tasks_.size() >= capacity_) { - return INVALID_TASK_ID; - } - auto taskId = GenTaskId(); - auto it = tasks_.insert({ time, std::pair{ task, taskId } }); - if (it == tasks_.begin()) { - condition_.notify_one(); - } - indexes_[taskId] = it; - return taskId; - } - - TaskId Execute(Task task) - { - return At(std::chrono::steady_clock::now(), std::move(task)); - } - -private: - using InnerTask = std::pair, uint64_t>; - void Loop() - { - while (isRunning_) { - std::function exec; - { - std::unique_lock lock(mutex_); - condition_.wait(lock, [this] { return !tasks_.empty(); }); - auto it = tasks_.begin(); - exec = it->second.first; - indexes_.erase(it->second.second); - tasks_.erase(it); - } - - if (exec) { - exec(); - } - } - } - - TaskId GenTaskId() - { - auto taskId = ++taskId_; - if (taskId == INVALID_TASK_ID) { - return ++taskId_; - } - return taskId; - } - - volatile bool isRunning_; - size_t capacity_; - std::multimap tasks_; - std::map indexes_; - std::mutex mutex_; - std::unique_ptr thread_; - std::condition_variable condition_; - std::atomic taskId_; -}; -} // namespace OHOS -#endif // OHOS_PREFERENCES_FRAMEWORKS_COMMON_TASK_SCHEDULER_H diff --git a/preferences/frameworks/native/include/visibility.h b/preferences/frameworks/native/include/visibility.h index 7c7726f4..26bf0fdb 100644 --- a/preferences/frameworks/native/include/visibility.h +++ b/preferences/frameworks/native/include/visibility.h @@ -22,5 +22,8 @@ #ifndef API_LOCAL #define API_LOCAL __attribute__((visibility("hidden"))) #endif +#ifndef UNUSED_FUNCTION +#define UNUSED_FUNCTION __attribute__((unused)) +#endif #endif // OHOS_PREFERENCES_FRAMEWORKS_COMMON_VISIBILITY_H diff --git a/preferences/frameworks/native/src/preferences_thread.cpp b/preferences/frameworks/native/mock/ability_base/zuri/include/uri.h similarity index 72% rename from preferences/frameworks/native/src/preferences_thread.cpp rename to preferences/frameworks/native/mock/ability_base/zuri/include/uri.h index 84374420..70dc4ce1 100644 --- a/preferences/frameworks/native/src/preferences_thread.cpp +++ b/preferences/frameworks/native/mock/ability_base/zuri/include/uri.h @@ -12,12 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "preferences_thread.h" + +#ifndef UTILS_NATIVE_INCLUDE_URI_H_ +#define UTILS_NATIVE_INCLUDE_URI_H_ + +#include + namespace OHOS { -namespace NativePreferences { -int PthreadSetNameNp(const std::string name) -{ - return pthread_setname_np(pthread_self(), name.c_str()); -} -} // End of namespace NativePreferences -} // End of namespace OHOS \ No newline at end of file +class Uri { +public: + explicit Uri(const std::string& uriString); + ~Uri(); +}; +} // namespace OHOS +#endif // UTILS_NATIVE_INCLUDE_URI_H_ diff --git a/preferences/frameworks/native/mock/ability_base/zuri/src/uri.cpp b/preferences/frameworks/native/mock/ability_base/zuri/src/uri.cpp new file mode 100644 index 00000000..a3f77559 --- /dev/null +++ b/preferences/frameworks/native/mock/ability_base/zuri/src/uri.cpp @@ -0,0 +1,21 @@ +/* + * 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 "uri.h" + +namespace OHOS { +Uri::Uri(const std::string &uriString) {} +Uri::~Uri() {} +} // namespace OHOS diff --git a/preferences/frameworks/native/include/task_queue.h b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/data_ability_observer_interface.h similarity index 51% rename from preferences/frameworks/native/include/task_queue.h rename to preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/data_ability_observer_interface.h index 1c4e3b3e..b3ce120e 100644 --- a/preferences/frameworks/native/include/task_queue.h +++ b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/data_ability_observer_interface.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -12,32 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_INTERFACE_H +#define OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_INTERFACE_H -#ifndef TASK_QUEUE_H -#define TASK_QUEUE_H - -#include -#include -#include +#include "refbase.h" namespace OHOS { -namespace NativePreferences { -using Task = std::function; - -class TaskQueue { +namespace AAFwk { +class IDataAbilityObserver : public RefBase { public: - explicit TaskQueue(bool lockable = true); - ~TaskQueue(); - void PutTask(const Task &task); - Task GetTaskAutoLock(); - void ReleaseLock(); - bool IsEmptyAndUnlocked(); + virtual void OnChange() = 0; -private: - bool lockable_; - std::thread::id lockThread_; - std::queue tasks_; + virtual void OnChangePreferences(const std::string &key) {} }; -} // namespace NativePreferences +} // namespace AAFwk } // namespace OHOS -#endif // TASK_QUEUE_H +#endif // OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_INTERFACE_H diff --git a/relational_store/interfaces/ndk/src/relational_value_object_impl.h b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/data_ability_observer_stub.h similarity index 54% rename from relational_store/interfaces/ndk/src/relational_value_object_impl.h rename to preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/data_ability_observer_stub.h index c069553f..66af5aec 100644 --- a/relational_store/interfaces/ndk/src/relational_value_object_impl.h +++ b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/data_ability_observer_stub.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -12,24 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_STUB_H +#define OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_STUB_H -#ifndef RELATIONAL_VALUE_OBJECT_IMPL_H -#define RELATIONAL_VALUE_OBJECT_IMPL_H - -#include "oh_value_object.h" -#include #include +#include "data_ability_observer_interface.h" namespace OHOS { -namespace RdbNdk { -constexpr int RDB_VOBJECT_CID = 1234565; // The class id used to uniquely identify the OH_Rdb_VObject class. -class ValueObjectImpl : public OH_VObject { +namespace AAFwk { +class DataAbilityObserverStub : public IDataAbilityObserver { public: - ValueObjectImpl(); - std::vector &getValue(); -private: - std::vector value; + DataAbilityObserverStub(); + virtual ~DataAbilityObserverStub(); }; -} // namespace RdbNdk +} // namespace AAFwk } // namespace OHOS -#endif // RELATIONAL_VALUE_OBJECT_IMPL_H +#endif // OHOS_ABILITY_RUNTIME_DATA_ABILITY_OBSERVER_STUB_H diff --git a/relational_store/interfaces/ndk/src/relational_cursor_impl.h b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/dataobs_mgr_client.h similarity index 47% rename from relational_store/interfaces/ndk/src/relational_cursor_impl.h rename to preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/dataobs_mgr_client.h index 0dc816e4..5b68b4cc 100644 --- a/relational_store/interfaces/ndk/src/relational_cursor_impl.h +++ b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/include/dataobs_mgr_client.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -13,24 +13,27 @@ * limitations under the License. */ -#ifndef RELATIONAL_CURSOR_IMPL_H -#define RELATIONAL_CURSOR_IMPL_H +#ifndef OHOS_ABILITY_RUNTIME_DATAOBS_MGR_CLIENT_H +#define OHOS_ABILITY_RUNTIME_DATAOBS_MGR_CLIENT_H -#include "oh_cursor.h" -#include "result_set.h" -#include +#include "data_ability_observer_interface.h" +#include "refbase.h" +#include "uri.h" namespace OHOS { -namespace RdbNdk { -constexpr int RDB_CURSOR_CID = 1234563; // The class id used to uniquely identify the OH_Cursor class. -class CursorImpl : public OH_Cursor { +namespace AAFwk { +class DataObsMgrClient { public: - explicit CursorImpl(std::shared_ptr resultSet); - std::shared_ptr GetResultSet(); + DataObsMgrClient(); + virtual ~DataObsMgrClient(); + static std::shared_ptr GetInstance(); -private: - std::shared_ptr resultSet_; + int RegisterObserver(const Uri &uri, sptr dataObserver); + + int UnregisterObserver(const Uri &uri, sptr dataObserver); + + int NotifyChange(const Uri &uri); }; -} // namespace RdbNdk +} // namespace AAFwk } // namespace OHOS -#endif // RELATIONAL_CURSOR_IMPL_H +#endif // OHOS_ABILITY_RUNTIME_DATAOBS_MGR_CLIENT_H diff --git a/preferences/frameworks/native/common/mock/src/filelock.cpp b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/src/data_ability_observer_stub.cpp similarity index 68% rename from preferences/frameworks/native/common/mock/src/filelock.cpp rename to preferences/frameworks/native/mock/ability_runtime/dataobs_manager/src/data_ability_observer_stub.cpp index e77be769..8e51d05e 100644 --- a/preferences/frameworks/native/common/mock/src/filelock.cpp +++ b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/src/data_ability_observer_stub.cpp @@ -13,27 +13,16 @@ * limitations under the License. */ -#include "filelock.h" -namespace OHOS { -namespace NativePreferences { - -FileLock::FileLock() -{ - fd_ = -1; -} +#include "data_ability_observer_stub.h" -FileLock::~FileLock() -{ -} - -int FileLock::TryLock(const std::string &fileName) +namespace OHOS { +namespace AAFwk { +DataAbilityObserverStub::DataAbilityObserverStub() { - return E_OK; } -int FileLock::UnLock() +DataAbilityObserverStub::~DataAbilityObserverStub() { - return E_OK; } -} // End of namespace NativePreferences -} // End of namespace OHOS \ No newline at end of file +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/src/dataobs_mgr_client.cpp b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/src/dataobs_mgr_client.cpp new file mode 100644 index 00000000..5e01659a --- /dev/null +++ b/preferences/frameworks/native/mock/ability_runtime/dataobs_manager/src/dataobs_mgr_client.cpp @@ -0,0 +1,48 @@ +/* + * 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 "dataobs_mgr_client.h" + +namespace OHOS { +namespace AAFwk { +DataObsMgrClient::DataObsMgrClient() +{ +} + +DataObsMgrClient::~DataObsMgrClient() +{ +} + +std::shared_ptr DataObsMgrClient::GetInstance() +{ + return nullptr; +} + +int DataObsMgrClient::RegisterObserver(const Uri &uri, sptr dataObserver) +{ + return -1; +} + +int DataObsMgrClient::UnregisterObserver(const Uri &uri, sptr dataObserver) +{ + return -1; +} + +int DataObsMgrClient::NotifyChange(const Uri &uri) +{ + return -1; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/mock/c_utils/utils/base/include/refbase.h b/preferences/frameworks/native/mock/c_utils/utils/base/include/refbase.h new file mode 100644 index 00000000..0f0e87de --- /dev/null +++ b/preferences/frameworks/native/mock/c_utils/utils/base/include/refbase.h @@ -0,0 +1,637 @@ +/* + * 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 UTILS_BASE_REFBASE_H +#define UTILS_BASE_REFBASE_H + +#include +#include + +namespace OHOS { +#define INITIAL_PRIMARY_VALUE (1 << 28) +class RefBase; +class RefCounter { +public: + using RefPtrCallback = std::function; + + RefCounter(); + + explicit RefCounter(RefCounter *counter); + + RefCounter &operator=(const RefCounter &counter); + + virtual ~RefCounter(); + + void SetCallback(const RefPtrCallback &callback); + + void RemoveCallback(); + + int GetRefCount(); + + void IncRefCount(); + + void DecRefCount(); + + bool IsRefPtrValid(); + + int IncStrongRefCount(const void *objectId); + + int DecStrongRefCount(const void *objectId); + + int GetStrongRefCount(); + + int IncWeakRefCount(const void *objectId); + + int DecWeakRefCount(const void *objectId); + + int GetWeakRefCount(); + + void SetAttemptAcquire(); + + bool IsAttemptAcquireSet(); + + void ClearAttemptAcquire(); + + bool AttemptIncStrongRef(const void *objectId, int &outCount); + + bool IsLifeTimeExtended(); + + void ExtendObjectLifetime(); + +private: + std::atomic atomicStrong_; + std::atomic atomicWeak_; + std::atomic atomicRefCount_; + std::atomic atomicFlags_; + std::atomic atomicAttempt_; + RefPtrCallback callback_ = nullptr; + static constexpr unsigned int FLAG_EXTEND_LIFE_TIME = 0x00000002; +}; + +class WeakRefCounter { +public: + WeakRefCounter(RefCounter *counter, void *cookie); + + virtual ~WeakRefCounter(); + + void *GetRefPtr(); + + void IncWeakRefCount(const void *objectId); + + void DecWeakRefCount(const void *objectId); + + bool AttemptIncStrongRef(const void *objectId); + +private: + std::atomic atomicWeak_; + RefCounter *refCounter_ = nullptr; + void *cookie_ = nullptr; +}; + +class RefBase { +public: + RefBase(); + + RefBase(const RefBase &other); + + RefBase &operator=(const RefBase &other); + + RefBase(RefBase &&other) noexcept; + + RefBase &operator=(RefBase &&other) noexcept; + + virtual ~RefBase(); + + virtual void RefPtrCallback(); + + void ExtendObjectLifetime(); + + void IncStrongRef(const void *objectId); + + void DecStrongRef(const void *objectId); + + int GetSptrRefCount(); + + WeakRefCounter *CreateWeakRef(void *cookie); + + void IncWeakRef(const void *objectId); + + void DecWeakRef(const void *objectId); + + int GetWptrRefCount(); + + bool AttemptAcquire(const void *objectId); + + bool AttemptIncStrongRef(const void *objectId); + + bool IsAttemptAcquireSet(); + + bool IsExtendLifeTimeSet(); + + virtual void OnFirstStrongRef(const void *objectId); + + virtual void OnLastStrongRef(const void *objectId); + + virtual void OnLastWeakRef(const void *objectId); + + virtual bool OnAttemptPromoted(const void *objectId); + +private: + RefCounter *refs_ = nullptr; +}; + +template class wptr; + +template + +class sptr { + friend class wptr; + +public: + sptr(); + + ~sptr(); + + sptr(T *other); + + sptr(const sptr &other); + + sptr(sptr &&other); + + sptr &operator=(sptr &&other); + + template sptr(const sptr &other); + + inline sptr(WeakRefCounter *p, bool force); + + inline T *GetRefPtr() const + { + return refs_; + } + + inline void ForceSetRefPtr(T *other); + + void clear(); + + inline operator T *() const + { + return refs_; + } + + inline T &operator*() const + { + return *refs_; + } + + inline T *operator->() const + { + return refs_; + } + + inline bool operator!() const + { + return refs_ == nullptr; + } + + sptr &operator=(T *other); + + sptr &operator=(const sptr &other); + + sptr &operator=(const wptr &other); + + template sptr &operator=(const sptr &other); + + bool operator==(const T *other) const; + + inline bool operator!=(const T *other) const + { + return !operator==(other); + } + + bool operator==(const wptr &other) const; + + inline bool operator!=(const wptr &other) const + { + return !operator==(other); + } + + bool operator==(const sptr &other) const; + + inline bool operator!=(const sptr &other) const + { + return !operator==(other); + } + +private: + T *refs_ = nullptr; +}; + +template inline void sptr::ForceSetRefPtr(T *other) +{ + refs_ = other; +} + +template inline sptr::sptr() +{ + refs_ = nullptr; +} + +template inline sptr::sptr(T *other) +{ + refs_ = other; +} + +template inline sptr::sptr(const sptr &other) +{ + refs_ = other.GetRefPtr(); + if (refs_ != nullptr) { + refs_->IncStrongRef(this); + } +} + +template sptr::sptr(sptr &&other) +{ + refs_ = other.GetRefPtr(); + other.ForceSetRefPtr(nullptr); +} + +template sptr &sptr::operator=(sptr &&other) +{ + if (refs_ != nullptr) { + refs_->DecStrongRef(this); + } + refs_ = other.GetRefPtr(); + other.ForceSetRefPtr(nullptr); + return *this; +} + +template template sptr::sptr(const sptr &other) : refs_(other.GetRefPtr()) +{ + if (refs_ != nullptr) { + refs_->IncStrongRef(this); + } +} + +template inline sptr &sptr::operator=(T *other) +{ + if (other != nullptr) { + other->IncStrongRef(this); + } + + if (refs_ != nullptr) { + refs_->DecStrongRef(this); + } + + refs_ = other; + return *this; +} + +template inline sptr &sptr::operator=(const sptr &other) +{ + T *otherRef(other.GetRefPtr()); + if (otherRef != nullptr) { + otherRef->IncStrongRef(this); + } + + if (refs_ != nullptr) { + refs_->DecStrongRef(this); + } + + refs_ = otherRef; + return *this; +} + +template inline sptr &sptr::operator=(const wptr &other) +{ + if ((other != nullptr) && other.AttemptIncStrongRef(this)) { + refs_ = other.GetRefPtr(); + } else { + refs_ = nullptr; + } + + return *this; +} + +template template sptr &sptr::operator=(const sptr &other) +{ + T *otherRef(other.GetRefPtr()); + if (otherRef != nullptr) { + otherRef->IncStrongRef(this); + } + + if (refs_ != nullptr) { + refs_->DecStrongRef(this); + } + + refs_ = otherRef; + return *this; +} + +template inline bool sptr::operator==(const T *other) const +{ + return other == refs_; +} + +template inline bool sptr::operator==(const wptr &other) const +{ + return refs_ == other.GetRefPtr(); +} + +template inline bool sptr::operator==(const sptr &other) const +{ + return refs_ == other.GetRefPtr(); +} + +template void sptr::clear() +{ + if (refs_) { + refs_->DecStrongRef(this); + refs_ = 0; + } +} + +template inline sptr::~sptr() +{ +} + +template inline sptr::sptr(WeakRefCounter *p, bool /* force */) +{ + if ((p != nullptr) && p->AttemptIncStrongRef(this)) { + refs_ = reinterpret_cast(p->GetRefPtr()); + } else { + refs_ = nullptr; + } +} + +template class wptr { + template friend class wptr; + +public: + wptr(); + + wptr(T *other); + + wptr(const wptr &other); + + wptr(const sptr &other); + + template wptr(const wptr &other); + + template wptr(const sptr &other); + + wptr &operator=(T *other); + + template wptr &operator=(O *other); + + wptr &operator=(const wptr &other); + + wptr &operator=(const sptr &other); + + template wptr &operator=(const wptr &other); + + template wptr &operator=(const sptr &other); + + inline T *operator*() const + { + return *refs_; + } + inline T *operator->() const + { + return reinterpret_cast(refs_->GetRefPtr()); + } + + bool operator==(const T *other) const; + + inline bool operator!=(const T *other) const + { + return !operator==(other); + }; + + bool operator==(const wptr &other) const; + + inline bool operator!=(const wptr &other) const + { + return !operator==(other); + } + + bool operator==(const sptr &other) const; + + inline bool operator!=(const sptr &other) const + { + return !operator==(other); + } + + T *GetRefPtr() const; + + inline bool AttemptIncStrongRef(const void *objectId) const + { + return refs_->AttemptIncStrongRef(objectId); + } + + const sptr promote() const; + + ~wptr(); + +private: + WeakRefCounter *refs_ = nullptr; +}; + +template inline T *wptr::GetRefPtr() const +{ + return (refs_ != nullptr) ? reinterpret_cast(refs_->GetRefPtr()) : nullptr; +} + +template wptr::wptr() +{ + refs_ = nullptr; +} + +template wptr::wptr(T *other) +{ + if (other != nullptr) { + refs_ = other->CreateWeakRef(other); + if (refs_ != nullptr) { + refs_->IncWeakRefCount(this); + } + } else { + refs_ = nullptr; + } +} + +template wptr::wptr(const wptr &other) +{ + refs_ = other.refs_; + if (refs_ != nullptr) { + refs_->IncWeakRefCount(this); + } +} + +template wptr::wptr(const sptr &other) +{ + if (other.GetRefPtr() != nullptr) { + refs_ = other->CreateWeakRef(other.GetRefPtr()); + if (refs_ != nullptr) { + refs_->IncWeakRefCount(this); + } + } +} + +template template wptr::wptr(const wptr &other) +{ + refs_ = other.refs_; + if (refs_ != nullptr) { + refs_->IncWeakRefCount(this); + } +} + +template template wptr::wptr(const sptr &other) +{ + if (other.GetRefPtr() != nullptr) { + refs_ = other->CreateWeakRef(other.GetRefPtr()); + if (refs_ != nullptr) { + refs_->IncWeakRefCount(this); + } + } +} + +template wptr &wptr::operator=(T *other) +{ + WeakRefCounter *newWeakRef = nullptr; + if (other != nullptr) { + newWeakRef = other->CreateWeakRef(other); + if (newWeakRef != nullptr) { + newWeakRef->IncWeakRefCount(this); + } + } + + if (refs_ != nullptr) { + refs_->DecWeakRefCount(this); + } + + refs_ = newWeakRef; + return *this; +} + +template template wptr &wptr::operator=(O *other) +{ + T *object = reinterpret_cast(other); + WeakRefCounter *newWeakRef = nullptr; + if (object != nullptr) { + newWeakRef = object->CreateWeakRef(object); + if (newWeakRef != nullptr) { + newWeakRef->IncWeakRefCount(this); + } + } + + if (refs_ != nullptr) { + refs_->DecWeakRefCount(this); + } + + refs_ = newWeakRef; + return *this; +} + +template inline wptr &wptr::operator=(const wptr &other) +{ + if (other.refs_ != nullptr) { + other.refs_->IncWeakRefCount(this); + } + + if (refs_ != nullptr) { + refs_->DecWeakRefCount(this); + } + + refs_ = other.refs_; + return *this; +} + +template inline wptr &wptr::operator=(const sptr &other) +{ + WeakRefCounter *newWeakRef = nullptr; + if (other.GetRefPtr() != nullptr) { + newWeakRef = other->CreateWeakRef(other.GetRefPtr()); + if (newWeakRef != nullptr) { + newWeakRef->IncWeakRefCount(this); + } + } + + if (refs_ != nullptr) { + refs_->DecWeakRefCount(this); + } + + refs_ = newWeakRef; + return *this; +} + +template template wptr &wptr::operator=(const wptr &other) +{ + if (other.refs_ != nullptr) { + other.refs_->IncWeakRefCount(this); + } + + if (refs_ != nullptr) { + refs_->DecWeakRefCount(this); + } + + refs_ = other.refs_; + return *this; +} + +template template wptr &wptr::operator=(const sptr &other) +{ + WeakRefCounter *newWeakRef = nullptr; + if (other.GetRefPtr() != nullptr) { + newWeakRef = other->CreateWeakRef(other->GetRefPtr()); + if (newWeakRef != nullptr) { + newWeakRef->IncWeakRefCount(this); + } + } + + if (refs_ != nullptr) { + refs_->DecWeakRefCount(this); + } + + refs_ = newWeakRef; + return *this; +} + +template inline bool wptr::operator==(const T *other) const +{ + return GetRefPtr() == other; +} + +template inline bool wptr::operator==(const wptr &other) const +{ + return GetRefPtr() == other.GetRefPtr(); +} + +template inline bool wptr::operator==(const sptr &other) const +{ + return GetRefPtr() == other.GetRefPtr(); +} + +template inline const sptr wptr::promote() const +{ + return sptr(refs_, true); +} + +template inline wptr::~wptr() +{ + if (refs_ != nullptr) { + refs_->DecWeakRefCount(this); + } +} +} // namespace OHOS +#endif diff --git a/preferences/frameworks/native/mock/c_utils/utils/base/src/refbase.cpp b/preferences/frameworks/native/mock/c_utils/utils/base/src/refbase.cpp new file mode 100644 index 00000000..7c8b879d --- /dev/null +++ b/preferences/frameworks/native/mock/c_utils/utils/base/src/refbase.cpp @@ -0,0 +1,438 @@ +/* + * 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 "refbase.h" +namespace OHOS { +WeakRefCounter::WeakRefCounter(RefCounter *counter, void *cookie) + : atomicWeak_(0), refCounter_(counter), cookie_(cookie) +{ + if (refCounter_ != nullptr) { + refCounter_->IncRefCount(); + } +} + +WeakRefCounter::~WeakRefCounter() +{ + if (refCounter_ != nullptr) { + refCounter_->DecRefCount(); + } +} + +void *WeakRefCounter::GetRefPtr() +{ + if ((cookie_ != nullptr) && (!refCounter_->IsRefPtrValid())) { + cookie_ = nullptr; + } + return cookie_; +} + +void WeakRefCounter::IncWeakRefCount(const void *objectId) +{ + if (atomicWeak_.fetch_add(1, std::memory_order_relaxed) == 0) { + refCounter_->IncWeakRefCount(objectId); + } +} + +void WeakRefCounter::DecWeakRefCount(const void *objectId) +{ + if (atomicWeak_.fetch_sub(1, std::memory_order_release) == 1) { + refCounter_->DecWeakRefCount(objectId); + delete this; + } +} + +bool WeakRefCounter::AttemptIncStrongRef(const void *objectId) +{ + int unuse = 0; + return refCounter_->AttemptIncStrongRef(objectId, unuse); +} + +RefCounter::RefCounter() + : atomicStrong_(INITIAL_PRIMARY_VALUE), atomicWeak_(0), atomicRefCount_(0), atomicFlags_(0), atomicAttempt_(0) +{ +} +int RefCounter::GetRefCount() +{ + return atomicRefCount_.load(std::memory_order_relaxed); +} + +void RefCounter::IncRefCount() +{ + atomicRefCount_.fetch_add(1, std::memory_order_relaxed); +} + +void RefCounter::DecRefCount() +{ + if (atomicRefCount_.load(std::memory_order_relaxed) > 0) { + if (atomicRefCount_.fetch_sub(1, std::memory_order_release) == 1) { + delete (this); + } + } +} + +void RefCounter::SetCallback(const RefPtrCallback &callback) +{ + callback_ = callback; +} + +void RefCounter::RemoveCallback() +{ + callback_ = nullptr; +} + +bool RefCounter::IsRefPtrValid() +{ + return callback_ != nullptr; +} + +RefCounter::~RefCounter() +{ +} + +int RefCounter::IncStrongRefCount(const void *objectId) +{ + int curCount = atomicStrong_.load(std::memory_order_relaxed); + if (curCount >= 0) { + curCount = atomicStrong_.fetch_add(1, std::memory_order_relaxed); + if (curCount == INITIAL_PRIMARY_VALUE) { + atomicStrong_.fetch_sub(INITIAL_PRIMARY_VALUE, std::memory_order_release); + } + } + return curCount; +} + +int RefCounter::DecStrongRefCount(const void *objectId) +{ + int curCount = GetStrongRefCount(); + if (curCount == INITIAL_PRIMARY_VALUE) { + // unexpected case: there had never a strong reference. + } else if (curCount > 0) { + // we should update the current count here. + // it may be changed after last operation. + curCount = atomicStrong_.fetch_sub(1, std::memory_order_release); + } + return curCount; +} + +int RefCounter::GetStrongRefCount() +{ + return atomicStrong_.load(std::memory_order_relaxed); +} + +int RefCounter::IncWeakRefCount(const void *objectId) +{ + return atomicWeak_.fetch_add(1, std::memory_order_relaxed); +} + +int RefCounter::DecWeakRefCount(const void *objectId) +{ + int curCount = GetWeakRefCount(); + if (curCount > 0) { + curCount = atomicWeak_.fetch_sub(1, std::memory_order_release); + } + + int strongRefCount = GetStrongRefCount(); + if ((curCount == 1) || (strongRefCount == 0 && !IsLifeTimeExtended())) { + if (callback_) { + callback_(); + } + } + return curCount; +} + +int RefCounter::GetWeakRefCount() +{ + return atomicWeak_.load(std::memory_order_relaxed); +} + +void RefCounter::SetAttemptAcquire() +{ + (void)atomicAttempt_.fetch_add(1, std::memory_order_relaxed); +} + +bool RefCounter::IsAttemptAcquireSet() +{ + return static_cast(atomicAttempt_.load(std::memory_order_relaxed) > 0); +} + +void RefCounter::ClearAttemptAcquire() +{ + atomicAttempt_.fetch_sub(1, std::memory_order_relaxed); +} + +void RefCounter::ExtendObjectLifetime() +{ + atomicFlags_.fetch_or(FLAG_EXTEND_LIFE_TIME, std::memory_order_relaxed); +} + +bool RefCounter::IsLifeTimeExtended() +{ + return static_cast(atomicFlags_.load(std::memory_order_relaxed) & FLAG_EXTEND_LIFE_TIME); +} + +bool RefCounter::AttemptIncStrongRef(const void *objectId, int &outCount) +{ + int curCount = GetStrongRefCount(); + IncWeakRefCount(objectId); + + // if the object already had strong references.just promoting it. + while ((curCount > 0) && (curCount != INITIAL_PRIMARY_VALUE)) { + if (atomicStrong_.compare_exchange_weak(curCount, curCount + 1, std::memory_order_relaxed)) { + goto ATTEMPT_SUCCESS; + } + // someone else changed the counter.re-acquire the counter value. + curCount = atomicStrong_.load(std::memory_order_relaxed); + } + + if ((curCount == INITIAL_PRIMARY_VALUE) && !IsLifeTimeExtended()) { + // this object has a "normal" life-time, + while (curCount > 0) { + if (atomicStrong_.compare_exchange_weak(curCount, curCount + 1, std::memory_order_relaxed)) { + goto ATTEMPT_SUCCESS; + } + curCount = atomicStrong_.load(std::memory_order_relaxed); + } + } + + if (IsLifeTimeExtended()) { + curCount = atomicStrong_.fetch_add(1, std::memory_order_relaxed); + } + +ATTEMPT_SUCCESS: + if (curCount >= INITIAL_PRIMARY_VALUE) { + outCount = curCount; + atomicStrong_.fetch_sub(INITIAL_PRIMARY_VALUE, std::memory_order_release); + return true; + } + + if (curCount < 0 || (!IsLifeTimeExtended() && curCount == 0)) { + // the object destroyed on strong reference count reduce to zero. + DecWeakRefCount(objectId); + return false; + } + + return true; +} + +RefBase::RefBase() : refs_(new RefCounter()) +{ + refs_->IncRefCount(); + refs_->SetCallback(std::bind(&RefBase::RefPtrCallback, this)); +} + +RefBase::RefBase(const RefBase &other) +{ + refs_ = new RefCounter(); + if (refs_ != nullptr) { + refs_->IncRefCount(); + refs_->SetCallback(std::bind(&RefBase::RefPtrCallback, this)); + } +} + +void RefBase::RefPtrCallback() +{ + delete this; +} + +RefBase &RefBase::operator=(const RefBase &other) +{ + if (refs_ != nullptr) { + refs_->RemoveCallback(); + refs_->DecRefCount(); + } + + refs_ = new RefCounter(); + if (refs_ != nullptr) { + refs_->IncRefCount(); + refs_->SetCallback(std::bind(&RefBase::RefPtrCallback, this)); + } + + return *this; +} + +RefBase::RefBase(RefBase &&other) noexcept +{ + refs_ = other.refs_; + if (other.refs_ != nullptr) { + other.refs_ = nullptr; + } +} + +RefBase &RefBase::operator=(RefBase &&other) noexcept +{ + if (refs_ == other.refs_) { + return *this; + } + + if (refs_ != nullptr) { + refs_->RemoveCallback(); + refs_->DecRefCount(); + } + + refs_ = other.refs_; + if (other.refs_ != nullptr) { + other.refs_ = nullptr; + } + return *this; +} + +RefBase::~RefBase() +{ + if (refs_ != nullptr) { + refs_->RemoveCallback(); + refs_->DecRefCount(); + refs_ = nullptr; + } +} + +void RefBase::ExtendObjectLifetime() +{ + refs_->ExtendObjectLifetime(); +} + +void RefBase::IncStrongRef(const void *objectId) +{ + if (refs_ == nullptr) { + return; + } + + const int curCount = refs_->IncStrongRefCount(objectId); + IncWeakRef(objectId); + if (curCount == INITIAL_PRIMARY_VALUE) { + OnFirstStrongRef(objectId); + } + if (refs_->IsAttemptAcquireSet()) { + refs_->ClearAttemptAcquire(); + refs_->DecStrongRefCount(objectId); + refs_->DecWeakRefCount(objectId); + } +} + +void RefBase::DecStrongRef(const void *objectId) +{ + if (refs_ == nullptr) { + return; + } + + const int curCount = refs_->DecStrongRefCount(objectId); + if (curCount == 1) { + OnLastStrongRef(objectId); + } + DecWeakRef(objectId); +} + +int RefBase::GetSptrRefCount() +{ + if (refs_ == nullptr) { + return 0; + } + return refs_->GetStrongRefCount(); +} + +WeakRefCounter *RefBase::CreateWeakRef(void *cookie) +{ + if (refs_ != nullptr) { + return new WeakRefCounter(refs_, cookie); + } + return nullptr; +} + +void RefBase::IncWeakRef(const void *objectId) +{ + if (refs_ != nullptr) { + refs_->IncWeakRefCount(objectId); + } +} + +void RefBase::DecWeakRef(const void *objectId) +{ + if (refs_ != nullptr) { + refs_->DecWeakRefCount(objectId); + } +} + +int RefBase::GetWptrRefCount() +{ + if (refs_ == nullptr) { + return 0; + } + return refs_->GetWeakRefCount(); +} + +bool RefBase::AttemptAcquire(const void *objectId) +{ + if (refs_ == nullptr) { + return false; + } + + int count = 0; + if (refs_->AttemptIncStrongRef(objectId, count)) { + refs_->SetAttemptAcquire(); + if (count == INITIAL_PRIMARY_VALUE) { + OnFirstStrongRef(objectId); + } + + return true; + } + return false; +} + +bool RefBase::AttemptIncStrongRef(const void *objectId) +{ + if ((refs_ != nullptr) && (OnAttemptPromoted(objectId))) { + int count = 0; + bool ret = refs_->AttemptIncStrongRef(objectId, count); + if (count == INITIAL_PRIMARY_VALUE) { + OnFirstStrongRef(objectId); + } + return ret; + } + + return false; +} + +bool RefBase::IsAttemptAcquireSet() +{ + if (refs_ == nullptr) { + return false; + } + return refs_->IsAttemptAcquireSet(); +} + +bool RefBase::IsExtendLifeTimeSet() +{ + if (refs_ == nullptr) { + return false; + } + return refs_->IsLifeTimeExtended(); +} + +void RefBase::OnFirstStrongRef(const void *objectId) +{ +} + +void RefBase::OnLastStrongRef(const void *objectId) +{ +} + +void RefBase::OnLastWeakRef(const void *objectId) +{ +} + +bool RefBase::OnAttemptPromoted(const void *objectId) +{ + return true; +} +} // namespace OHOS diff --git a/preferences/frameworks/native/include/filelock.h b/preferences/frameworks/native/platform/include/preferences_file_lock.h similarity index 90% rename from preferences/frameworks/native/include/filelock.h rename to preferences/frameworks/native/platform/include/preferences_file_lock.h index 743f3aa8..ddcb43f7 100644 --- a/preferences/frameworks/native/include/filelock.h +++ b/preferences/frameworks/native/platform/include/preferences_file_lock.h @@ -21,10 +21,10 @@ #include "preferences_errno.h" namespace OHOS { namespace NativePreferences { -class FileLock final { +class PreferencesFileLock final { public: - FileLock(); - ~FileLock(); + PreferencesFileLock(); + ~PreferencesFileLock(); int TryLock(const std::string &fileName); int UnLock(); private: diff --git a/preferences/frameworks/native/include/adaptor.h b/preferences/frameworks/native/platform/include/preferences_file_operation.h similarity index 38% rename from preferences/frameworks/native/include/adaptor.h rename to preferences/frameworks/native/platform/include/preferences_file_operation.h index b69ef0a6..0709e7f3 100644 --- a/preferences/frameworks/native/include/adaptor.h +++ b/preferences/frameworks/native/platform/include/preferences_file_operation.h @@ -12,61 +12,61 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef PREFERENCES_ADAPTOR_H -#define PREFERENCES_ADAPTOR_H +#ifndef PREFERENCES_FILE_OPERATION_H +#define PREFERENCES_FILE_OPERATION_H -#ifndef FILE_MODE -#define FILE_MODE 0771 -#endif - -#ifndef FILE_EXIST -#define FILE_EXIST 0 -#endif - -#define DO_NOTHING - -#ifdef WINDOWS_PLATFORM #include #include -#include -#define REALPATH(filePath, realPath, ...) (_fullpath(realPath, filePath, ##__VA_ARGS__)) -#define MKDIR(filePath) (mkdir(filePath)) -#define ACCESS(filePath) (_access(filePath, FILE_EXIST)) -#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING +#include +#include "visibility.h" -#elif defined(MAC_PLATFORM) -#include -#include -#include -#define REALPATH(filePath, realPath, ...) (realpath(filePath, realPath)) -#define MKDIR(filePath) (mkdir(filePath, FILE_MODE)) -#define ACCESS(filePath) (access(filePath, FILE_EXIST)) -#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING +#if defined(WINDOWS_PLATFORM) -#elif defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) -#include -#include -#include -#define REALPATH(filePath, realPath, ...) (realpath(filePath, realPath)) -#define MKDIR(filePath) (mkdir(filePath, FILE_MODE)) -#define ACCESS(filePath) (access(filePath, FILE_EXIST)) -#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING +#include #else + #include -#include -#include + +#if !(defined(MAC_PLATFORM) || defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM)) + #include -#include "hitrace.h" -#define REALPATH(filePath, realPath, ...) (realpath(filePath, realPath)) -#define MKDIR(filePath) (mkdir(filePath, FILE_MODE)) -#define ACCESS(filePath) (access(filePath, FILE_EXIST)) -#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING // HiTrace hitrace(trace) #endif +#endif + +#ifndef FILE_MODE +#define FILE_MODE 0771 +#endif + +#ifndef FILE_EXIST +#define FILE_EXIST 0 +#endif + #ifndef INT_MAX #define INT_MAX 2147483647 #endif -#endif // PREFERENCES_ADAPTOR_H \ No newline at end of file +namespace OHOS { +namespace NativePreferences { +static UNUSED_FUNCTION int Mkdir(const std::string &filePath) +{ +#if defined(WINDOWS_PLATFORM) + return mkdir(filePath.c_str()); +#else + return mkdir(filePath.c_str(), FILE_MODE); +#endif +} + +static UNUSED_FUNCTION int Access(const std::string &filePath) +{ +#if defined(WINDOWS_PLATFORM) + return _access(filePath.c_str(), FILE_EXIST); +#else + return access(filePath.c_str(), FILE_EXIST); +#endif +} +} // namespace NativePreferences +} // namespace OHOS +#endif // PREFERENCES_FILE_OPERATION_H \ No newline at end of file diff --git a/preferences/frameworks/native/include/preferences_thread.h b/preferences/frameworks/native/platform/include/preferences_thread.h similarity index 100% rename from preferences/frameworks/native/include/preferences_thread.h rename to preferences/frameworks/native/platform/include/preferences_thread.h diff --git a/preferences/frameworks/native/src/filelock.cpp b/preferences/frameworks/native/platform/src/preferences_file_lock.cpp similarity index 80% rename from preferences/frameworks/native/src/filelock.cpp rename to preferences/frameworks/native/platform/src/preferences_file_lock.cpp index bfe0291a..6cbfe6bf 100644 --- a/preferences/frameworks/native/src/filelock.cpp +++ b/preferences/frameworks/native/platform/src/preferences_file_lock.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "filelock.h" +#include "preferences_file_lock.h" #include #include @@ -26,20 +26,23 @@ #include "log_print.h" namespace OHOS { namespace NativePreferences { + +#if !defined(WINDOWS_PLATFORM) static const std::chrono::microseconds WAIT_CONNECT_TIMEOUT(20); static const int ATTEMPTS = 5; -FileLock::FileLock() + +PreferencesFileLock::PreferencesFileLock() { } -FileLock::~FileLock() +PreferencesFileLock::~PreferencesFileLock() { if (fd_ > 0) { close(fd_); } } -int FileLock::TryLock(const std::string &fileName) +int PreferencesFileLock::TryLock(const std::string &fileName) { int fd = open(fileName.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (fd == -1) { @@ -63,7 +66,7 @@ int FileLock::TryLock(const std::string &fileName) return E_ERROR; } -int FileLock::UnLock() +int PreferencesFileLock::UnLock() { int errCode = E_OK; if (fd_ > 0) { @@ -82,5 +85,26 @@ int FileLock::UnLock() return errCode; } +#else + +PreferencesFileLock::PreferencesFileLock() +{ + fd_ = -1; +} + +PreferencesFileLock::~PreferencesFileLock() +{ +} + +int PreferencesFileLock::TryLock(const std::string &fileName) +{ + return E_OK; +} + +int PreferencesFileLock::UnLock() +{ + return E_OK; +} +#endif } // End of namespace NativePreferences } // End of namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/common/mock/src/preferences_thread.cpp b/preferences/frameworks/native/platform/src/preferences_thread.cpp similarity index 77% rename from preferences/frameworks/native/common/mock/src/preferences_thread.cpp rename to preferences/frameworks/native/platform/src/preferences_thread.cpp index e65bc5d0..fc537086 100644 --- a/preferences/frameworks/native/common/mock/src/preferences_thread.cpp +++ b/preferences/frameworks/native/platform/src/preferences_thread.cpp @@ -4,7 +4,7 @@ * 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 + * 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, @@ -17,7 +17,11 @@ namespace OHOS { namespace NativePreferences { int PthreadSetNameNp(const std::string name) { - return pthread_setname_np(name.c_str()); + return pthread_setname_np( +#if !(defined(MAC_PLATFORM) || defined(IOS_PLATFORM)) + pthread_self(), +#endif + name.c_str()); } } // End of namespace NativePreferences } // End of namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/src/preferences_helper.cpp b/preferences/frameworks/native/src/preferences_helper.cpp index 498a6065..797ce444 100644 --- a/preferences/frameworks/native/src/preferences_helper.cpp +++ b/preferences/frameworks/native/src/preferences_helper.cpp @@ -15,16 +15,15 @@ #include "preferences_helper.h" +#include #include #include - -#include #include -#include "adaptor.h" #include "log_print.h" #include "preferences.h" #include "preferences_errno.h" +#include "preferences_file_operation.h" #include "preferences_impl.h" #include "securec.h" @@ -63,7 +62,7 @@ std::string PreferencesHelper::GetRealPath(const std::string &path, int &errorCo } std::string filePath = path.substr(0, pos); #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - if (ACCESS(filePath.c_str()) != 0 && MKDIR(filePath.c_str())) { + if (Access(filePath) != 0 && Mkdir(filePath)) { LOG_ERROR("Failed to create path"); errorCode = E_INVALID_FILE_PATH; return ""; @@ -81,10 +80,8 @@ std::string PreferencesHelper::GetRealPath(const std::string &path, int &errorCo std::shared_ptr PreferencesHelper::GetPreferences(const Options &options, int &errCode) { - DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::string realPath = GetRealPath(options.filePath, errCode); if (realPath == "" || errCode != E_OK) { - LOG_ERROR("fails to get real path, errCode %{public}d", errCode); return nullptr; } @@ -98,7 +95,6 @@ std::shared_ptr PreferencesHelper::GetPreferences(const Options &op std::shared_ptr pref = PreferencesImpl::GetPreferences(options); errCode = pref->Init(); if (errCode != E_OK) { - LOG_ERROR("Preferences Init failed."); return nullptr; } prefsCache_.insert(make_pair(realPath, pref)); @@ -107,7 +103,6 @@ std::shared_ptr PreferencesHelper::GetPreferences(const Options &op int PreferencesHelper::DeletePreferences(const std::string &path) { - DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); int errCode = E_OK; std::string realPath = GetRealPath(path, errCode); if (realPath == "" || errCode != E_OK) { @@ -137,7 +132,6 @@ int PreferencesHelper::DeletePreferences(const std::string &path) int PreferencesHelper::RemovePreferencesFromCache(const std::string &path) { - DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); int errCode = E_OK; std::string realPath = GetRealPath(path, errCode); if (realPath == "" || errCode != E_OK) { diff --git a/preferences/frameworks/native/src/preferences_impl.cpp b/preferences/frameworks/native/src/preferences_impl.cpp index d9811b35..aff55641 100644 --- a/preferences/frameworks/native/src/preferences_impl.cpp +++ b/preferences/frameworks/native/src/preferences_impl.cpp @@ -4,7 +4,7 @@ * 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 + * 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, @@ -16,36 +16,69 @@ #include "preferences_impl.h" #include -#include -#include #include -#include #include -#include "adaptor.h" -#include "data_preferences_observer_stub.h" +#include "executor_pool.h" #include "log_print.h" #include "preferences_errno.h" +#include "preferences_observer_stub.h" #include "preferences_xml_utils.h" -#include "securec.h" namespace OHOS { namespace NativePreferences { +template std::string GetTypeName() +{ + return "unknown"; +} -ExecutorPool PreferencesImpl::executorPool_ = ExecutorPool(1, 0); +template<> std::string GetTypeName() +{ + return "int"; +} -static bool IsFileExist(const std::string &inputPath) +template<> std::string GetTypeName() { - char path[PATH_MAX + 1] = { 0x00 }; + return "bool"; +} - if (strlen(inputPath.c_str()) > PATH_MAX || REALPATH(inputPath.c_str(), path, PATH_MAX) == nullptr) { - return false; - } - const char *pathString = path; - struct stat buffer; - return (stat(pathString, &buffer) == 0); +template<> std::string GetTypeName() +{ + return "long"; +} + +template<> std::string GetTypeName() +{ + return "float"; +} + +template<> std::string GetTypeName() +{ + return "double"; +} + +template<> std::string GetTypeName() +{ + return "string"; +} + +template<> std::string GetTypeName>() +{ + return "stringArray"; +} + +template<> std::string GetTypeName>() +{ + return "doubleArray"; +} + +template<> std::string GetTypeName>() +{ + return "boolArray"; } +ExecutorPool PreferencesImpl::executorPool_ = ExecutorPool(1, 0); + PreferencesImpl::PreferencesImpl(const Options &options) : loaded_(false), options_(options) { currentMemoryStateGeneration_ = 0; @@ -102,24 +135,7 @@ void PreferencesImpl::LoadFromDisk(std::shared_ptr pref) if (pref->loaded_) { return; } - - std::string backupPath = MakeFilePath(pref->options_.filePath, STR_BACKUP); - if (IsFileExist(backupPath)) { - if (std::remove(pref->options_.filePath.c_str())) { - LOG_ERROR("Couldn't delete file %{private}s when LoadFromDisk and backup exist.", - pref->options_.filePath.c_str()); - } - if (std::rename(backupPath.c_str(), pref->options_.filePath.c_str())) { - LOG_ERROR("Couldn't rename backup file %{private}s to file %{private}s,when LoadFromDisk and backup " - "exist.", backupPath.c_str(), pref->options_.filePath.c_str()); - } else { - PreferencesXmlUtils::LimitXmlPermission(pref->options_.filePath); - } - } - - if (IsFileExist(pref->options_.filePath)) { - pref->ReadSettingXml(pref->options_.filePath, pref->map_); - } + pref->ReadSettingXml(pref->options_.filePath, pref->map_); pref->loaded_ = true; pref->cond_.notify_all(); } @@ -134,64 +150,30 @@ void PreferencesImpl::AwaitLoadFile() void PreferencesImpl::WriteToDiskFile(std::shared_ptr pref, std::shared_ptr mcr) { - std::string backupPath = MakeFilePath(pref->options_.filePath, STR_BACKUP); - if (IsFileExist(pref->options_.filePath)) { - bool needWrite = pref->CheckRequestValidForStateGeneration(*mcr); - if (!needWrite) { - mcr->SetDiskWriteResult(false, E_OK); - return; - } - if (IsFileExist(backupPath)) { - if (std::remove(pref->options_.filePath.c_str())) { - LOG_ERROR("Couldn't delete file %{private}s when writeToFile and backup exist.", - pref->options_.filePath.c_str()); - } - } else { - if (std::rename(pref->options_.filePath.c_str(), backupPath.c_str())) { - LOG_ERROR("Couldn't rename file %{private}s to backup file %{private}s", - pref->options_.filePath.c_str(), backupPath.c_str()); - mcr->SetDiskWriteResult(false, E_ERROR); - return; - } else { - PreferencesXmlUtils::LimitXmlPermission(backupPath); - } - } + if (!pref->CheckRequestValidForStateGeneration(mcr)) { + mcr->SetDiskWriteResult(true, E_OK); + return; } + if (pref->WriteSettingXml(pref->options_.filePath, mcr->writeToDiskMap_)) { - if (IsFileExist(backupPath) && std::remove(backupPath.c_str())) { - LOG_ERROR("Couldn't delete backup file %{private}s when writeToFile finish.", backupPath.c_str()); - } pref->diskStateGeneration_ = mcr->memoryStateGeneration_; mcr->SetDiskWriteResult(true, E_OK); } else { - // restore backup if write fails - if (IsFileExist(pref->options_.filePath)) { - if (std::remove(pref->options_.filePath.c_str())) { - LOG_ERROR("Couldn't clean up partially-written file %{private}s", pref->options_.filePath.c_str()); - } - } - if (std::rename(backupPath.c_str(), pref->options_.filePath.c_str())) { - LOG_ERROR("Couldn't rename backup file %{private}s to file %{private}s", backupPath.c_str(), - pref->options_.filePath.c_str()); - } mcr->SetDiskWriteResult(false, E_ERROR); } } -bool PreferencesImpl::CheckRequestValidForStateGeneration(const MemoryToDiskRequest &mcr) +bool PreferencesImpl::CheckRequestValidForStateGeneration(std::shared_ptr mcr) { - bool valid = false; + if (diskStateGeneration_ >= mcr->memoryStateGeneration_) { + LOG_INFO("DiskStateGeneration should be less than memoryStateGeneration."); + return false; + } - if (diskStateGeneration_ < mcr.memoryStateGeneration_) { - if (mcr.isSyncRequest_) { - valid = true; - } else { - if (currentMemoryStateGeneration_ == mcr.memoryStateGeneration_) { - valid = true; - } - } + if (mcr->isSyncRequest_ || currentMemoryStateGeneration_ == mcr->memoryStateGeneration_) { + return true; } - return valid; + return false; } PreferencesValue PreferencesImpl::Get(const std::string &key, const PreferencesValue &defValue) @@ -212,148 +194,118 @@ PreferencesValue PreferencesImpl::Get(const std::string &key, const PreferencesV std::map PreferencesImpl::GetAll() { AwaitLoadFile(); - return map_; } -void ReadXmlArrayElement(const Element &element, std::map &prefMap) +template static void Convert2PrefValue(const Element &element, T &value) { - if (element.tag_.compare("doubleArray") == 0) { - std::vector values; - for (auto &child : element.children_) { - std::stringstream ss; - ss << child.value_; - double value = 0.0; - ss >> value; - values.push_back(value); - } - prefMap.insert(std::make_pair(element.key_, PreferencesValue(values))); - } else if (element.tag_.compare("stringArray") == 0) { - std::vector values; - for (auto &child : element.children_) { - values.push_back(child.value_); - } - prefMap.insert(std::make_pair(element.key_, PreferencesValue(values))); - } else if (element.tag_.compare("boolArray") == 0) { - std::vector values; - for (auto &child : element.children_) { - std::stringstream ss; - ss << child.value_; - int32_t value = 0; - ss >> value; - values.push_back(value); - } - prefMap.insert(std::make_pair(element.key_, PreferencesValue(values))); + if constexpr (std::is_same::value) { + value = (element.value_.compare("true") == 0) ? true : false; + } else if constexpr (std::is_same::value) { + value = element.value_; + } else { + std::stringstream ss; + ss << element.value_; + ss >> value; } } -void ReadXmlElement( - const Element &element, std::map &prefMap, const std::string &prefPath) +template static void Convert2PrefValue(const Element &element, std::vector &values) { - if (element.tag_.compare("int") == 0) { - std::stringstream ss; - ss << element.value_; - int value = 0; - ss >> value; - prefMap.insert(std::make_pair(element.key_, PreferencesValue(value))); - } else if (element.tag_.compare("bool") == 0) { - bool value = (element.value_.compare("true") == 0) ? true : false; - prefMap.insert(std::make_pair(element.key_, PreferencesValue(value))); - } else if (element.tag_.compare("long") == 0) { - std::stringstream ss; - ss << element.value_; - int64_t value = 0; - ss >> value; - prefMap.insert(std::make_pair(element.key_, PreferencesValue(value))); - } else if (element.tag_.compare("float") == 0) { - std::stringstream ss; - ss << element.value_; - float value = 0.0; - ss >> value; - prefMap.insert(std::make_pair(element.key_, PreferencesValue(value))); - } else if (element.tag_.compare("double") == 0) { - std::stringstream ss; - ss << element.value_; - double value = 0.0; - ss >> value; - prefMap.insert(std::make_pair(element.key_, PreferencesValue(value))); - } else if (element.tag_.compare("string") == 0) { - prefMap.insert(std::make_pair(element.key_, PreferencesValue(element.value_))); - } else if (element.tag_.compare("doubleArray") == 0 || element.tag_.compare("stringArray") == 0 - || element.tag_.compare("boolArray") == 0) { - ReadXmlArrayElement(element, prefMap); - } else { - LOG_WARN("ReadSettingXml:%{private}s, unknown element tag:%{public}s.", prefPath.c_str(), element.tag_.c_str()); + for (const auto &child : element.children_) { + T value; + Convert2PrefValue(child, value); + values.push_back(value); } } -bool PreferencesImpl::ReadSettingXml( - const std::string &prefPath, std::map &prefMap) +template bool GetPrefValue(const Element &element, T &value) +{ + LOG_WARN("unknown element type. the key is %{public}s", element.key_.c_str()); + return false; +} + +template bool GetPrefValue(const Element &element, T &value) +{ + if (element.tag_ == GetTypeName()) { + First val; + Convert2PrefValue(element, val); + value = val; + return true; + } + return GetPrefValue(element, value); +} + +template bool Convert2PrefValue(const Element &element, std::variant &value) +{ + return GetPrefValue(element, value); +} + +void ReadXmlElement(const Element &element, std::map &prefMap) +{ + PreferencesValue value(static_cast(0)); + if (Convert2PrefValue(element, value.value_)) { + prefMap.insert(std::make_pair(element.key_, value)); + } +} + +bool PreferencesImpl::ReadSettingXml(const std::string &prefPath, std::map &prefMap) { std::vector settings; if (!PreferencesXmlUtils::ReadSettingXml(prefPath, settings)) { - LOG_ERROR("ReadSettingXml:%{private}s failed!", options_.filePath.c_str()); return false; } - + for (const auto &element : settings) { - ReadXmlElement(element, prefMap, prefPath); + ReadXmlElement(element, prefMap); } return true; } -void WriteXmlElement(Element &elem, const PreferencesValue &value, const std::string &filePath) +template void Convert2Element(Element &elem, const T &value) { - if (value.IsDoubleArray()) { - elem.tag_ = std::string("doubleArray"); - auto values = (std::vector)value; - for (double val : values) { - Element element; - element.tag_ = std::string("double"); - element.value_ = std::to_string((double)val); - elem.children_.push_back(element); - } - } else if (value.IsBoolArray()) { - elem.tag_ = std::string("boolArray"); - auto values = (std::vector)value; - for (bool val : values) { - Element element; - element.tag_ = std::string("bool"); - std::string tmpVal = std::to_string((bool)val); - element.value_ = tmpVal == "1" ? "true" : "false"; - elem.children_.push_back(element); - } - } else if (value.IsStringArray()) { - elem.tag_ = std::string("stringArray"); - auto values = (std::vector)value; - for (std::string &val : values) { - Element element; - element.tag_ = std::string("string"); - element.value_ = val; - elem.children_.push_back(element); - } - } else if (value.IsInt()) { - elem.tag_ = std::string("int"); - elem.value_ = std::to_string((int)value); - } else if (value.IsBool()) { - elem.tag_ = std::string("bool"); - std::string tmpVal = std::to_string((bool)value); - elem.value_ = tmpVal == "1" ? "true" : "false"; - } else if (value.IsLong()) { - elem.tag_ = std::string("long"); - elem.value_ = std::to_string((int64_t)value); - } else if (value.IsFloat()) { - elem.tag_ = std::string("float"); - elem.value_ = std::to_string((float)value); - } else if (value.IsDouble()) { - elem.tag_ = std::string("double"); - elem.value_ = std::to_string((double)value); - } else if (value.IsString()) { - elem.tag_ = std::string("string"); - elem.value_ = std::string(value); + elem.tag_ = GetTypeName(); + if constexpr (std::is_same::value) { + elem.value_ = ((bool)value) ? "true" : "false"; + } else if constexpr (std::is_same::value) { + elem.value_ = value; } else { - LOG_WARN("WriteSettingXml:%{private}s, unknown element type.", filePath.c_str()); + elem.value_ = std::to_string(value); + } +} + +template void Convert2Element(Element &elem, const std::vector &value) +{ + elem.tag_ = GetTypeName(); + for (auto val : value) { + Element element; + Convert2Element(element, val); + elem.children_.push_back(element); + } +} + +template void GetElement(Element &elem, const T &value) +{ + LOG_WARN("unknown element type. the key is %{public}s", elem.key_.c_str()); +} + +template void GetElement(Element &elem, const T &value) +{ + auto *val = std::get_if(&value); + if (val != nullptr) { + return Convert2Element(elem, *val); } + return GetElement(elem, value); +} + +template void Convert2Element(Element &elem, const std::variant &value) +{ + return GetElement(elem, value); +} + +void WriteXmlElement(Element &elem, const PreferencesValue &value) +{ + Convert2Element(elem, value.value_); } bool PreferencesImpl::WriteSettingXml( @@ -365,7 +317,7 @@ bool PreferencesImpl::WriteSettingXml( elem.key_ = it->first; PreferencesValue value = it->second; - WriteXmlElement(elem, value, options_.filePath); + WriteXmlElement(elem, value); settings.push_back(elem); } @@ -527,7 +479,6 @@ int PreferencesImpl::Clear() void PreferencesImpl::Flush() { - DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::shared_ptr request = commitToMemory(); request->isSyncRequest_ = false; ExecutorPool::Task task = std::bind(PreferencesImpl::WriteToDiskFile, shared_from_this(), request); @@ -543,7 +494,7 @@ int PreferencesImpl::FlushSync() std::unique_lock lock(request->reqMutex_); PreferencesImpl::WriteToDiskFile(shared_from_this(), request); if (request->wasWritten_) { - LOG_DEBUG("%{private}s:%{public}" PRId64 " written", options_.filePath.c_str(), + LOG_DEBUG("Successfully written to disk file, memory state generation is %{public}" PRId64 "", request->memoryStateGeneration_); } notifyPreferencesObserver(*request); @@ -583,7 +534,7 @@ void PreferencesImpl::notifyPreferencesObserver(const PreferencesImpl::MemoryToD sharedPreferencesObserver->OnChange(*key); } } - + if (dataObsMgrClient == nullptr) { continue; } diff --git a/preferences/frameworks/native/src/preferences_xml_utils.cpp b/preferences/frameworks/native/src/preferences_xml_utils.cpp index b1d440c1..830374e5 100644 --- a/preferences/frameworks/native/src/preferences_xml_utils.cpp +++ b/preferences/frameworks/native/src/preferences_xml_utils.cpp @@ -22,8 +22,7 @@ #include "libxml/parser.h" #include "log_print.h" - -#include "adaptor.h" +#include "preferences_impl.h" namespace OHOS { namespace NativePreferences { @@ -35,29 +34,96 @@ static xmlNode *CreateElementNode(Element &element); static xmlNode *CreatePrimitiveNode(Element &element); static xmlNode *CreateStringNode(Element &element); static xmlNode *CreateArrayNode(Element &element); + +static bool IsFileExist(const std::string &inputPath) +{ + if (inputPath.length() > PATH_MAX) { + return false; + } + struct stat buffer; + return (stat(inputPath.c_str(), &buffer) == 0); +} + +static void RemoveBackupFile(const std::string &fileName) +{ + std::string backupFileName = PreferencesImpl::MakeFilePath(fileName, STR_BACKUP); + if (IsFileExist(backupFileName) && std::remove(backupFileName.c_str())) { + LOG_WARN("failed to delete backup file %{public}d.", errno); + } +} + +static bool RenameFromBackupFile(const std::string &fileName) +{ + std::string backupFileName = PreferencesImpl::MakeFilePath(fileName, STR_BACKUP); + if (!IsFileExist(backupFileName)) { + LOG_INFO("the backup file does not exist."); + return false; + } + if (std::rename(backupFileName.c_str(), fileName.c_str())) { + LOG_ERROR("failed to restore backup errno %{public}d.", errno); + return false; + } + return true; +} + +static bool RenameFile(const std::string &fileName, const std::string &fileType) +{ + std::string name = PreferencesImpl::MakeFilePath(fileName, fileType); + if (std::rename(fileName.c_str(), name.c_str())) { + LOG_ERROR("failed to rename file to %{public}s file %{public}d.", fileType.c_str(), errno); + return false; + } + return true; +} + +static bool RenameToBackupFile(const std::string &fileName) +{ + return RenameFile(fileName, STR_BACKUP); +} + +static bool RenameToBrokenFile(const std::string &fileName) +{ + return RenameFile(fileName, STR_BROKEN); +} + +static xmlDoc *ReadFile(const std::string &fileName) +{ + return xmlReadFile(fileName.c_str(), "UTF-8", XML_PARSE_NOBLANKS); +} + +static xmlDoc *XmlReadFile(const std::string &fileName) +{ + xmlDoc *doc = nullptr; + if (IsFileExist(fileName)) { + doc = ReadFile(fileName); + if (doc != nullptr) { + return doc; + } + if (RenameToBrokenFile(fileName)) { + return doc; + } + } + if (RenameFromBackupFile(fileName)) { + return ReadFile(fileName); + } + return nullptr; +} + /* static */ bool PreferencesXmlUtils::ReadSettingXml(const std::string &fileName, std::vector &settings) { - LOG_DEBUG("Read setting xml %{private}s start.", fileName.c_str()); + LOG_RECORD_FILE_NAME("Read setting xml start."); if (fileName.size() == 0) { LOG_ERROR("The length of the file name is 0."); return false; } - char path[PATH_MAX + 1] = { 0x00 }; - if (strlen(fileName.c_str()) > PATH_MAX || REALPATH(fileName.c_str(), path, PATH_MAX) == nullptr) { - LOG_ERROR("The file name is incorrect."); - return false; - } - const char *pathString = path; - xmlDoc *doc = xmlReadFile(pathString, "UTF-8", XML_PARSE_NOBLANKS); + auto doc = std::shared_ptr(XmlReadFile(fileName), [](xmlDoc *doc) { xmlFreeDoc(doc); }); if (doc == nullptr) { - LOG_ERROR("The file name is incorrect."); return false; } - xmlNode *root = xmlDocGetRootElement(doc); + xmlNode *root = xmlDocGetRootElement(doc.get()); if (!root || xmlStrcmp(root->name, reinterpret_cast("preferences"))) { - xmlFreeDoc(doc); LOG_ERROR("Failed to obtain the XML root element."); return false; } @@ -77,8 +143,7 @@ bool PreferencesXmlUtils::ReadSettingXml(const std::string &fileName, std::vecto } /* free the document */ - xmlFreeDoc(doc); - LOG_DEBUG("Read setting xml %{private}s end.", fileName.c_str()); + LOG_RECORD_FILE_NAME("Read setting xml end."); return success; } @@ -208,60 +273,76 @@ bool ParseArrayNodeElement(const xmlNode *node, Element &element) return success; } +static bool SaveFormatFileEnc(const std::string &fileName, xmlDoc *doc) +{ + return xmlSaveFormatFileEnc(fileName.c_str(), doc, "UTF-8", 1) > 0; +} + +bool XmlSaveFormatFileEnc(const std::string &fileName, xmlDoc *doc) +{ + if (IsFileExist(fileName) && !RenameToBackupFile(fileName)) { + return false; + } + + if (!SaveFormatFileEnc(fileName, doc)) { + LOG_ERROR("Failed to save XML format file, attempting to restore backup"); + if (IsFileExist(fileName)) { + RenameToBrokenFile(fileName); + } + RenameFromBackupFile(fileName); + return false; + } + + RemoveBackupFile(fileName); + PreferencesXmlUtils::LimitXmlPermission(fileName); + LOG_DEBUG("successfully saved the XML format file"); + return true; +} + /* static */ bool PreferencesXmlUtils::WriteSettingXml(const std::string &fileName, std::vector &settings) { - LOG_DEBUG("Write setting xml %{private}s start.", fileName.c_str()); + LOG_RECORD_FILE_NAME("Write setting xml start."); if (fileName.size() == 0) { LOG_ERROR("The length of the file name is 0."); return false; } // define doc and root Node - xmlDoc *doc = xmlNewDoc(BAD_CAST "1.0"); + auto doc = std::shared_ptr(xmlNewDoc(BAD_CAST "1.0"), [](xmlDoc *doc) { xmlFreeDoc(doc); }); if (doc == nullptr) { LOG_ERROR("Failed to initialize the xmlDoc."); return false; } - xmlNode *root_node = xmlNewNode(NULL, BAD_CAST "preferences"); - if (root_node == nullptr) { + xmlNode *rootNode = xmlNewNode(NULL, BAD_CAST "preferences"); + if (rootNode == nullptr) { LOG_ERROR("The xmlDoc failed to initialize the root node."); - xmlFreeDoc(doc); return false; } - xmlNewProp(root_node, BAD_CAST "version", BAD_CAST "1.0"); + xmlNewProp(rootNode, BAD_CAST "version", BAD_CAST "1.0"); // set root node - xmlDocSetRootElement(doc, root_node); + xmlDocSetRootElement(doc.get(), rootNode); // set children node for (Element element : settings) { xmlNode *node = CreateElementNode(element); if (node == nullptr) { LOG_ERROR("The xmlDoc failed to initialize the element node."); - xmlFreeDoc(doc); return false; } - if (root_node == nullptr || xmlAddChild(root_node, node) == nullptr) { + if (xmlAddChild(rootNode, node) == nullptr) { /* free node in case of error */ LOG_ERROR("The xmlDoc failed to add the child node."); xmlFreeNode(node); - xmlFreeDoc(doc); return false; } } /* 1: formatting spaces are added. */ - int result = xmlSaveFormatFileEnc(fileName.c_str(), doc, "UTF-8", 1); - - xmlFreeDoc(doc); - - if (result > 0) { - LimitXmlPermission(fileName); - } - - LOG_DEBUG("Write setting xml %{private}s end.", fileName.c_str()); - return (result > 0) ? true : false; + bool result = XmlSaveFormatFileEnc(fileName.c_str(), doc.get()); + LOG_RECORD_FILE_NAME("Write setting xml end."); + return result; } /* static */ diff --git a/preferences/frameworks/native/src/task_executor.cpp b/preferences/frameworks/native/src/task_executor.cpp deleted file mode 100644 index 2bfb6a07..00000000 --- a/preferences/frameworks/native/src/task_executor.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -* 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 "task_executor.h" - -namespace OHOS { -namespace NativePreferences { -TaskExecutor &TaskExecutor::GetInstance() -{ - static TaskExecutor instance; - return instance; -} - -bool TaskExecutor::Execute(TaskScheduler::Task &&task) -{ - if (pool_ == nullptr) { - return false; - } - pool_->Execute(std::move(task)); - return true; -} - -TaskExecutor::TaskExecutor() -{ - pool_ = std::make_shared("preferences"); -} - -TaskExecutor::~TaskExecutor() -{ -} -} // namespace NativePreferences -} // namespace OHOS diff --git a/preferences/frameworks/native/src/task_pool.cpp b/preferences/frameworks/native/src/task_pool.cpp deleted file mode 100644 index 93489d49..00000000 --- a/preferences/frameworks/native/src/task_pool.cpp +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (c) 2021 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 "task_pool.h" -#include -#include "logger.h" -#include "preferences_errno.h" -#include "pthread.h" - -namespace OHOS { -namespace NativePreferences { -constexpr int TaskPool::IDLE_WAIT_PERIOD; - -TaskPool::TaskPool(int maxThreads, int minThreads) - : genericTasks_(false), genericTaskCount_(0), queuedTaskCount_(0), isStarted_(false), isStopping_(false), - isGenericThreadIdle_(false), maxThreads_(maxThreads), minThreads_(minThreads), curThreads_(0), idleThreads_(0) -{ -} - -TaskPool::~TaskPool() -{ -} - -int TaskPool::Start() -{ - if (maxThreads_ < minThreads_) { - LOG_ERROR("Start task pool failed, maxThreads(%d) < minThreads(%d).", maxThreads_, minThreads_); - return E_INVALID_ARGS; - } - if (maxThreads_ <= 0) { - LOG_ERROR("Start task pool failed, maxThreads(%d) <= 0.", maxThreads_); - return E_INVALID_ARGS; - } - if (minThreads_ < 0) { - LOG_ERROR("Start task pool failed, minThreads(%d) < 0.", minThreads_); - return E_INVALID_ARGS; - } - - std::lock_guard guard(tasksMutex_); - isStarted_ = true; // parameters checked ok. - isStopping_ = false; - int errCode = SpawnThreads(true); - if (errCode != E_OK) { - LOG_WARN("Spawn threads failed when starting the task pool."); - // ignore the error, we will try when schedule(). - } - return E_OK; -} - -void TaskPool::Stop() -{ - std::unique_lock lock(tasksMutex_); - if (!isStarted_) { - return; - } - isStopping_ = true; - hasTasks_.notify_all(); - allThreadsExited_.wait(lock, [this]() { return this->curThreads_ <= 0; }); - isStarted_ = false; -} - -int TaskPool::Schedule(const Task &task) -{ - if (!task) { - return E_INVALID_ARGS; - } - std::lock_guard guard(tasksMutex_); - if (!isStarted_) { - LOG_ERROR("Schedule failed, the task pool is not started."); - return E_NOT_PERMIT; - } - if (isStopping_) { - LOG_ERROR("Schedule failed, the task pool is stopping."); - return E_STALE; - } - if (genericTaskCount_ == INT_MAX) { - LOG_ERROR("Schedule failed, the task pool is full."); - return E_ERROR; - } - genericTasks_.PutTask(task); - ++genericTaskCount_; - hasTasks_.notify_one(); - TryToSpawnThreads(); - return E_OK; -} - -int TaskPool::Schedule(const std::string &queueTag, const Task &task) -{ - if (!task) { - return E_INVALID_ARGS; - } - std::lock_guard guard(tasksMutex_); - if (!isStarted_) { - LOG_ERROR("Schedule failed, the task pool is not started."); - return E_NOT_PERMIT; - } - if (isStopping_) { - LOG_ERROR("Schedule failed, the task pool is stopping."); - return E_STALE; - } - if (queuedTaskCount_ == INT_MAX) { - LOG_ERROR("Schedule failed, the task pool is full."); - return E_ERROR; - } - queuedTasks_[queueTag].PutTask(task); - ++queuedTaskCount_; - hasTasks_.notify_all(); - TryToSpawnThreads(); - return E_OK; -} - -void TaskPool::ShrinkMemory(const std::string &tag) -{ - std::lock_guard guard(tasksMutex_); - auto iter = queuedTasks_.find(tag); - if (iter != queuedTasks_.end()) { - if (iter->second.IsEmptyAndUnlocked()) { - queuedTasks_.erase(iter); - } - } -} - -void TaskPool::Report() -{ - std::lock_guard guard(tasksMutex_); - LOG_INFO("[Task pool report:1] maxThreads:%d, minThreads:%d, curThreads:%d, " - "idleThreads:%d, genericTaskCount:%d, queuedTaskCount:%d.", - maxThreads_, minThreads_, curThreads_, idleThreads_, genericTaskCount_, queuedTaskCount_); - LOG_INFO("[Task pool report:2] taskQueueCount:%zu.", queuedTasks_.size()); -} - -bool TaskPool::IdleExit(std::unique_lock &lock) -{ - if (isStopping_) { - return true; - } - ++idleThreads_; - bool isGenericWorker = IsGenericWorker(); - if (!isGenericWorker && (curThreads_ > minThreads_)) { - std::cv_status status = hasTasks_.wait_for(lock, std::chrono::seconds(IDLE_WAIT_PERIOD)); - if (status == std::cv_status::timeout && genericTaskCount_ <= 0) { - --idleThreads_; - return true; - } - } else { - if (isGenericWorker) { - isGenericThreadIdle_ = true; - hasTasks_.notify_all(); - } - hasTasks_.wait(lock); - if (isGenericWorker) { - isGenericThreadIdle_ = false; - } - } - --idleThreads_; - return false; -} - -void TaskPool::SetThreadFree() -{ - for (auto &pair : queuedTasks_) { - TaskQueue *tq = &pair.second; - tq->ReleaseLock(); - } -} - -Task TaskPool::ReapTask(TaskQueue *&queue) -{ - Task task = genericTasks_.GetTaskAutoLock(); - if (task != nullptr) { - queue = nullptr; - return task; - } - - queue = nullptr; - if (IsGenericWorker() && (curThreads_ > 1)) { // 1 indicates self. - SetThreadFree(); - return nullptr; - } - - for (auto &pair : queuedTasks_) { - TaskQueue *tq = &pair.second; - task = tq->GetTaskAutoLock(); - if (task != nullptr) { - queue = tq; - return task; - } - } - return nullptr; -} - -int TaskPool::GetTask(Task &task, TaskQueue *&queue) -{ - std::unique_lock lock(tasksMutex_); - - while (true) { - task = ReapTask(queue); - if (task != nullptr) { - return E_OK; - } - - if (IdleExit(lock)) { - break; - } - } - return E_OK; -} - -int TaskPool::SpawnThreads(bool isStart) -{ - if (!isStarted_) { - LOG_ERROR("Spawn task pool threads failed, pool is not started."); - return E_NOT_PERMIT; - } - if (curThreads_ >= maxThreads_) { - // the pool is full of threads. - return E_OK; - } - - int limits = isStart ? minThreads_ : (curThreads_ + 1); - while (curThreads_ < limits) { - ++curThreads_; - std::thread thread([this]() { -#if defined(MAC_PLATFORM) - pthread_setname_np("Preferences_TaskWorker"); -#else - pthread_setname_np(pthread_self(), "Preferences_TaskWorker"); -#endif - TaskWorker(); - }); - LOG_INFO("Spawn task pool threads, min:%d cur:%d max:%d", minThreads_, curThreads_, maxThreads_); - thread.detach(); - } - return E_OK; -} - -bool TaskPool::IsGenericWorker() const -{ - return genericThread_ == std::this_thread::get_id(); -} - -void TaskPool::BecomeGenericWorker() -{ - std::lock_guard guard(tasksMutex_); - if (genericThread_ == std::thread::id()) { - genericThread_ = std::this_thread::get_id(); - } -} - -void TaskPool::ExitGenericWorker() -{ - std::lock_guard guard(tasksMutex_); - if (IsGenericWorker()) { - genericThread_ = std::thread::id(); - } - --curThreads_; - allThreadsExited_.notify_all(); - LOG_INFO("Task pool thread exit, min:%d cur:%d max:%d, genericTaskCount:%d, queuedTaskCount:%d.", minThreads_, - curThreads_, maxThreads_, genericTaskCount_, queuedTaskCount_); -} - -void TaskPool::TaskWorker() -{ - BecomeGenericWorker(); - while (true) { - TaskQueue *taskQueue = nullptr; - Task task = nullptr; - - int errCode = GetTask(task, taskQueue); - if (errCode != E_OK) { - LOG_ERROR("Thread worker gets task failed, err:'%d'.", errCode); - break; - } - if (task == nullptr) { - // Idle thread exit. - break; - } - - task(); - FinishExecuteTask(taskQueue); - } - - ExitGenericWorker(); -} - -void TaskPool::FinishExecuteTask(TaskQueue *taskQueue) -{ - std::lock_guard guard(tasksMutex_); - if (taskQueue != nullptr) { - taskQueue->ReleaseLock(); - --queuedTaskCount_; - } else { - --genericTaskCount_; - } -} - -void TaskPool::TryToSpawnThreads() -{ - if ((curThreads_ >= maxThreads_) || (curThreads_ >= (queuedTaskCount_ + genericTaskCount_))) { - return; - } - SpawnThreads(false); -} -} // namespace NativePreferences -} // namespace OHOS diff --git a/preferences/frameworks/native/src/task_queue.cpp b/preferences/frameworks/native/src/task_queue.cpp deleted file mode 100644 index 52b79618..00000000 --- a/preferences/frameworks/native/src/task_queue.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2021 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 "task_queue.h" - -namespace OHOS { -namespace NativePreferences { -TaskQueue::TaskQueue(bool lockable) : lockable_(lockable) -{ -} - -TaskQueue::~TaskQueue() -{ -} - -void TaskQueue::PutTask(const Task &task) -{ - if (!task) { - return; - } - tasks_.push(task); -} - -Task TaskQueue::GetTaskAutoLock() -{ - if (lockable_) { - std::thread::id thisId = std::this_thread::get_id(); - if (thisId != lockThread_) { - if (lockThread_ == std::thread::id()) { - lockThread_ = thisId; - } else { - return nullptr; - } - } - } - if (tasks_.empty()) { - ReleaseLock(); - return nullptr; - } - // copy and return - Task task = tasks_.front(); - tasks_.pop(); - return task; -} - -void TaskQueue::ReleaseLock() -{ - if (!lockable_) { - return; - } - if (lockThread_ == std::this_thread::get_id()) { - lockThread_ = std::thread::id(); - } -} - -bool TaskQueue::IsEmptyAndUnlocked() -{ - if (lockable_) { - if (lockThread_ != std::thread::id()) { - return false; - } - } - return tasks_.empty(); -} -} // namespace NativePreferences -} // namespace OHOS diff --git a/preferences/interfaces/inner_api/BUILD.gn b/preferences/interfaces/inner_api/BUILD.gn index 3c13f425..c1a7e6b6 100644 --- a/preferences/interfaces/inner_api/BUILD.gn +++ b/preferences/interfaces/inner_api/BUILD.gn @@ -18,11 +18,18 @@ config("native_preferences_config") { "include", "${preferences_base_path}/frameworks/common/include", "${preferences_native_path}/include", + "${preferences_native_path}/platform/include/", ] - if (is_ohos) { - include_dirs += [ "${preferences_native_path}/common/include" ] - } else { - include_dirs += [ "${preferences_native_path}/common/mock/include" ] +} + +config("mock_config") { + include_dirs = [ + "${preferences_native_path}/mock/ability_runtime/dataobs_manager/include", + "${preferences_native_path}/mock/ability_base/zuri/include", + ] + if (!is_android) { + include_dirs += + [ "${preferences_native_path}/mock/c_utils/utils/base/include" ] } } @@ -36,6 +43,8 @@ config("adaptor_config") { } base_sources = [ + "${preferences_native_path}/platform/src/preferences_file_lock.cpp", + "${preferences_native_path}/platform/src/preferences_thread.cpp", "${preferences_native_path}/src/preferences_helper.cpp", "${preferences_native_path}/src/preferences_impl.cpp", "${preferences_native_path}/src/preferences_observer.cpp", @@ -43,14 +52,22 @@ base_sources = [ "${preferences_native_path}/src/preferences_xml_utils.cpp", ] +if (!is_ohos) { + mock_sources = [ + "${preferences_native_path}/mock/ability_base/zuri/src/uri.cpp", + "${preferences_native_path}/mock/ability_runtime/dataobs_manager/src/data_ability_observer_stub.cpp", + "${preferences_native_path}/mock/ability_runtime/dataobs_manager/src/dataobs_mgr_client.cpp", + ] + if (!is_android) { + mock_sources += + [ "${preferences_native_path}/mock/c_utils/utils/base/src/refbase.cpp" ] + } +} + if (is_ohos) { ohos_shared_library("native_preferences") { all_dependent_configs = [ ":native_preferences_public_config" ] sources = base_sources - sources += [ - "${preferences_native_path}/common/src/data_preferences_observer_stub.cpp", - "${preferences_native_path}/src/preferences_thread.cpp", - ] innerapi_tags = [ "platformsdk" ] @@ -74,24 +91,22 @@ if (is_ohos) { ohos_shared_library("native_preferences") { all_dependent_configs = [ ":native_preferences_public_config" ] sources = base_sources - sources += [ "${preferences_native_path}/common/mock/src/data_preferences_observer_stub.cpp" ] + sources += mock_sources innerapi_tags = [ "platformsdk" ] configs = [ ":native_preferences_config" ] + configs += [ ":mock_config" ] configs += [ ":adaptor_config" ] + cflags_cc = [ "-std=c++17", "-stdlib=libc++", ] if (is_mac) { - sources += [ - "${preferences_native_path}/common/mock/src/preferences_thread.cpp", - ] buildos = "mac" defines = [ "MAC_PLATFORM" ] } else { - sources += [ "${preferences_native_path}/src/preferences_thread.cpp" ] buildos = "windows" defines = [ "WINDOWS_PLATFORM" ] ldflags = [ "-lws2_32" ] @@ -109,14 +124,12 @@ if (is_ohos) { ohos_source_set("native_preferences") { all_dependent_configs = [ ":native_preferences_public_config" ] sources = base_sources - sources += [ - "${preferences_native_path}/common/mock/src/data_preferences_observer_stub.cpp", - "${preferences_native_path}/src/preferences_thread.cpp", - ] + sources += mock_sources defines = [ "ANDROID_PLATFORM" ] configs = [ ":native_preferences_config" ] + configs += [ ":mock_config" ] cflags_cc = [ "-fvisibility=hidden" ] deps = [ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog_android", @@ -131,13 +144,11 @@ if (is_ohos) { ohos_source_set("native_preferences") { all_dependent_configs = [ ":native_preferences_public_config" ] sources = base_sources - sources += [ - "${preferences_native_path}/common/mock/src/data_preferences_observer_stub.cpp", - "${preferences_native_path}/common/mock/src/preferences_thread.cpp", - ] + sources += mock_sources defines = [ "IOS_PLATFORM" ] configs = [ ":native_preferences_config" ] + configs += [ ":mock_config" ] cflags_cc = [ "-fvisibility=hidden" ] deps = [ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog_${target_os}", @@ -154,21 +165,20 @@ ohos_static_library("native_preferences_static") { all_dependent_configs = [ ":native_preferences_public_config" ] sources = base_sources configs = [ ":native_preferences_config" ] + if (is_mingw || is_mac) { - sources += [ "${preferences_native_path}/common/mock/src/data_preferences_observer_stub.cpp" ] + configs += [ ":mock_config" ] configs += [ ":adaptor_config" ] + + sources += mock_sources cflags_cc = [ "-std=c++17", "-stdlib=libc++", ] if (is_mac) { - sources += [ - "${preferences_native_path}/common/mock/src/preferences_thread.cpp", - ] buildos = "mac" defines = [ "MAC_PLATFORM" ] } else { - sources += [ "${preferences_native_path}/src/preferences_thread.cpp" ] buildos = "windows" defines = [ "WINDOWS_PLATFORM" ] ldflags = [ "-lws2_32" ] @@ -178,14 +188,6 @@ ohos_static_library("native_preferences_static") { "//third_party/libxml2:static_libxml2", ] } else { - if (is_ios) { - sources += [ - "${preferences_native_path}/common/mock/src/preferences_thread.cpp", - ] - } else { - sources += [ "${preferences_native_path}/src/preferences_thread.cpp" ] - } - sources += [ "${preferences_native_path}/common/src/data_preferences_observer_stub.cpp" ] deps = [ "//third_party/libxml2:libxml2" ] external_deps = [ "ability_base:zuri", diff --git a/preferences/test/js/performance/preferences/src/PreferencesInstanceSyncJsPref.test.js b/preferences/test/js/performance/preferences/src/PreferencesInstanceSyncJsPref.test.js index 023e9f30..bdc46f5b 100644 --- a/preferences/test/js/performance/preferences/src/PreferencesInstanceSyncJsPref.test.js +++ b/preferences/test/js/performance/preferences/src/PreferencesInstanceSyncJsPref.test.js @@ -43,34 +43,62 @@ describe("PreferencesInstanceSyncJsPref", async function () { console.info(`${TAG}afterAll`) }) + /** + * @tc.desc PreferencesInstanceSyncJsPref_ GetPreferencesSync to obtain the same preferences instance + */ + it("getPreferencesSync_0001", 0, function () { + let startTime = new Date().getTime(); // time unit is ms + for (let index = 0; index < BASE_COUNT; index++) { + dataPreferences.getPreferencesSync(context, { name: NAME }); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(`${TAG}getPreferencesSync_0001 averageTime: ${averageTime} us`); + expect(averageTime < BASELINE).assertTrue(); + }) + + /** + * @tc.desc PreferencesInstanceSyncJsPref_ GetPreferencesSync to obtain different instances of preferences + */ + it("getPreferencesSync_0002", 0, function () { + let startTime = new Date().getTime(); // time unit is ms + for (let index = 0; index < BASE_COUNT; index++) { + dataPreferences.getPreferencesSync(context, { name: `${NAME}${index}` }); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(`${TAG}getPreferencesSync_0002 averageTime: ${averageTime} us`); + expect(averageTime < BASELINE).assertTrue(); + }) + /** * @tc.desc PreferencesInstanceSyncJsPref_RemovePreferencesFromCacheSync with repeating one pref */ - it("removePreferencesFromCacheSync_0001", 0, async function () { - let startTime = new Date().getTime(); // time unit is mm + it("removePreferencesFromCacheSync_0003", 0, function () { + let startTime = new Date().getTime(); // time unit is ms for (let index = 0; index < BASE_COUNT; index++) { - dataPreferences.removePreferencesFromCacheSync(context, NAME); + dataPreferences.removePreferencesFromCacheSync(context, { name: NAME }); } let endTime = new Date().getTime(); let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(`${TAG}removePreferencesFromCacheSync_0001 averageTime: ${averageTime} us`); + console.info(`${TAG}removePreferencesFromCacheSync_0003 averageTime: ${averageTime} us`); expect(averageTime < BASELINE).assertTrue(); }) /** * @tc.desc PreferencesInstanceSyncJsPref_RemovePreferencesFromCacheSync with diff pref */ - it("removePreferencesFromCacheSync_0002", 0, async function () { + it("removePreferencesFromCacheSync_0004", 0, function () { for (let index = 0; index < BASE_COUNT; index++) { - dataPreferences.getPreferences(context, `${NAME}${index}`); // put prefs into cache + dataPreferences.getPreferencesSync(context, { name: `${NAME}${index}` }); // put prefs into cache } - let startTime = new Date().getTime(); // time unit is mm + let startTime = new Date().getTime(); // time unit is ms for (let index = 0; index < BASE_COUNT; index++) { - await dataPreferences.removePreferencesFromCacheSync(context, `${NAME}${index}`); + dataPreferences.removePreferencesFromCacheSync(context, { name: `${NAME}${index}` }); } let endTime = new Date().getTime(); let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(`${TAG}removePreferencesFromCacheSync_0002 averageTime: ${averageTime} us`); + console.info(`${TAG}removePreferencesFromCacheSync_0004 averageTime: ${averageTime} us`); expect(averageTime < BASELINE).assertTrue(); }) }) \ No newline at end of file diff --git a/preferences/test/js/unittest/preferences/src/PreferencesHelperSyncJsunit.test.js b/preferences/test/js/unittest/preferences/src/PreferencesHelperSyncJsunit.test.js index 9a947b3c..28cf9084 100644 --- a/preferences/test/js/unittest/preferences/src/PreferencesHelperSyncJsunit.test.js +++ b/preferences/test/js/unittest/preferences/src/PreferencesHelperSyncJsunit.test.js @@ -30,13 +30,26 @@ describe('preferencesSyncTest', function () { console.info('afterAll') }) + /** + * @tc.name GetPreferencesSync + * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_GetPreferencesSync_001 + * @tc.desc test GetPreferencesSync if success + */ + it('testPreferencesGetPreferencesSync001', 0, function () { + let preferences = data_preferences.getPreferencesSync(context, { name: NAME }); + preferences.putSync(KEY_TEST_STRING_ELEMENT, "132"); + expect(preferences.hasSync(KEY_TEST_STRING_ELEMENT)).assertTrue(); + let val = preferences.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue"); + expect("132").assertEqual(val); + }) + /** * @tc.name RemovePreferencesFromCacheSync * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_RemovePreferencesFromCacheSync_001 * @tc.desc test RemovePreferencesFromCacheSync if success */ - it('testPreferencesRemovePreferencesFromCacheSync0001', 0, async function (done) { - let preferences = await data_preferences.getPreferences(context, NAME); + it('testPreferencesRemovePreferencesFromCacheSync001', 0, function () { + let preferences = data_preferences.getPreferencesSync(context, NAME); preferences.putSync(KEY_TEST_STRING_ELEMENT, "132"); expect(preferences.hasSync(KEY_TEST_STRING_ELEMENT)).assertTrue(); let val = preferences.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue"); @@ -45,8 +58,26 @@ describe('preferencesSyncTest', function () { data_preferences.removePreferencesFromCacheSync(context, NAME); - let preferences1 = await data_preferences.getPreferences(context, NAME); + let preferences1 = data_preferences.getPreferencesSync(context, NAME); + expect(preferences1.hasSync(KEY_TEST_STRING_ELEMENT)).assertFalse(); + }) + + /** + * @tc.name RemovePreferencesFromCacheSync + * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_RemovePreferencesFromCacheSync_002 + * @tc.desc test RemovePreferencesFromCacheSync if success + */ + it('testPreferencesRemovePreferencesFromCacheSync002', 0, function () { + let preferences = data_preferences.getPreferencesSync(context, { name: NAME }); + preferences.putSync(KEY_TEST_STRING_ELEMENT, "132"); + expect(preferences.hasSync(KEY_TEST_STRING_ELEMENT)).assertTrue(); + let val = preferences.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue"); + expect("132").assertEqual(val); + preferences = null; + + data_preferences.removePreferencesFromCacheSync(context, { name: NAME }); + + let preferences1 = data_preferences.getPreferencesSync(context, { name: NAME }); expect(preferences1.hasSync(KEY_TEST_STRING_ELEMENT)).assertFalse(); - done(); }) }) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/PreferencesCallBackJsunit.test.js b/preferences/test/js/unittest/src/PreferencesCallBackJsunit.test.js deleted file mode 100644 index 0a681840..00000000 --- a/preferences/test/js/unittest/src/PreferencesCallBackJsunit.test.js +++ /dev/null @@ -1,433 +0,0 @@ -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import data_preferences from '@ohos.data.preferences' -import featureAbility from '@ohos.ability.featureAbility'; - -const NAME = 'test_preferences'; -const KEY_TEST_INT_ELEMENT = 'key_test_int'; -const KEY_TEST_LONG_ELEMENT = 'key_test_long'; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const KEY_TEST_BOOLEAN_ELEMENT = 'key_test_boolean'; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const KEY_TEST_NUMBER_ARRAY_ELEMENT = 'key_test_number_array'; -const KEY_TEST_STRING_ARRAY_ELEMENT = 'key_test_string_array'; -const KEY_TEST_BOOL_ARRAY_ELEMENT = 'key_test_bool_array'; -var mPreferences; -var context; - -const TAG = '[PREFERENCES_CALLBACK_JSUNIT_TEST]' - -describe('preferencesTest', function () { - beforeAll(async function () { - console.info('beforeAll') - context = featureAbility.getContext() - mPreferences = await data_preferences.getPreferences(context, NAME); - }) - - afterAll(async function () { - console.info('afterAll') - await data_preferences.deletePreferences(context, NAME); - }) - - /** - * @tc.name clear callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0010 - * @tc.desc clear callback interface test - */ - it('testPreferencesClear0012', 0, async function (done) { - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "test"); - await mPreferences.flush(); - await mPreferences.clear(async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue") - expect("defaultvalue").assertEqual(pre); - done(); - }); - }) - - /** - * @tc.name has string callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0020 - * @tc.desc has string callback interface test - */ - it('testPreferencesHasKey0032', 0, async function (done) { - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "test"); - await mPreferences.has(KEY_TEST_STRING_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has int callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0130 - * @tc.desc has int callback interface test - */ - it('testPreferencesHasKey0033', 0, async function (done) { - await mPreferences.put(KEY_TEST_INT_ELEMENT, 1); - await mPreferences.has(KEY_TEST_INT_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has float callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0140 - * @tc.desc has float callback interface test - */ - it('testPreferencesHasKey0034', 0, async function (done) { - await mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 1.1); - await mPreferences.has(KEY_TEST_FLOAT_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has long callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0150 - * @tc.desc has long callback interface test - */ - it('testPreferencesHasKey0035', 0, async function (done) { - await mPreferences.put(KEY_TEST_LONG_ELEMENT, 0); - await mPreferences.has(KEY_TEST_LONG_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has boolean callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0160 - * @tc.desc has boolean callback interface test - */ - it('testPreferencesHasKey0036', 0, async function (done) { - await mPreferences.put(KEY_TEST_BOOLEAN_ELEMENT, false); - await mPreferences.has(KEY_TEST_BOOLEAN_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get defaultValue callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0030 - * @tc.desc get defaultValue callback interface test - */ - it('testPreferencesGetDefValue0062', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultValue", function (err, ret) { - expect('defaultValue').assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get float callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0040 - * @tc.desc get float callback interface test - */ - it('testPreferencesGetFloat0072', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 3.0); - await mPreferences.get(KEY_TEST_FLOAT_ELEMENT, 0.0, function (err, ret) { - expect(3.0).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get int callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0050 - * @tc.desc get int callback interface test - */ - it('testPreferencesGetInt0082', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_INT_ELEMENT, 3); - await mPreferences.get(KEY_TEST_INT_ELEMENT, 0.0, function (err, ret) { - expect(3).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get long callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0060 - * @tc.desc get long callback interface test - */ - it('testPreferencesGetLong0092', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_LONG_ELEMENT, 3); - let pref = await mPreferences.get(KEY_TEST_LONG_ELEMENT, 0) - expect(3).assertEqual(pref); - await mPreferences.get(KEY_TEST_LONG_ELEMENT, 0, function (err, ret) { - expect(3).assertEqual(ret); - done(); - }); - }) - - /** - * @tc.name get String callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0070 - * @tc.desc get String callback interface test - */ - it('testPreferencesGetString102', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "test"); - await mPreferences.flush(); - await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, ret) { - expect('test').assertEqual(ret); - done(); - }); - }) - - /** - * @tc.name put boolean callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0080 - * @tc.desc put boolean callback interface test - */ - it('testPreferencesPutBoolean0122', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_BOOLEAN_ELEMENT, true, async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_BOOLEAN_ELEMENT, false); - expect(true).assertEqual(pre); - await mPreferences.flush(); - let pre2 = await mPreferences.get(KEY_TEST_BOOLEAN_ELEMENT, false) - expect(true).assertEqual(pre2); - done(); - }); - }) - - /** - * @tc.name put float callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0090 - * @tc.desc put float callback interface test - */ - it('testPreferencesPutFloat0132', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 4.0, async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_FLOAT_ELEMENT, 0.0); - expect(4.0).assertEqual(pre); - await mPreferences.flush(); - let pre2 = await mPreferences.get(KEY_TEST_FLOAT_ELEMENT, 0.0); - expect(4.0).assertEqual(pre2); - done(); - }); - }) - - /** - * @tc.name put int callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0100 - * @tc.desc put int callback interface test - */ - it('testPreferencesPutInt0142', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_INT_ELEMENT, 4, async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_INT_ELEMENT, 0); - expect(4).assertEqual(pre); - await mPreferences.flush(); - let pre2 = await mPreferences.get(KEY_TEST_INT_ELEMENT, 0); - expect(4).assertEqual(pre2); - done(); - }); - }) - - /** - * @tc.name put long callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0110 - * @tc.desc put long callback interface test - */ - it('testPreferencesPutLong0152', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_LONG_ELEMENT, 4); - await mPreferences.put(KEY_TEST_LONG_ELEMENT, 4, async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_LONG_ELEMENT, 0); - expect(4).assertEqual(pre); - await mPreferences.flush(); - let pre2 = await mPreferences.get(KEY_TEST_LONG_ELEMENT, 0); - expect(4).assertEqual(pre2); - done(); - }); - }) - - /** - * @tc.name put String callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0120 - * @tc.desc put String callback interface test - */ - it('testPreferencesPutString0162', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_STRING_ELEMENT, '', async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue") - expect('').assertEqual(pre); - await mPreferences.flush(); - let pre2 = await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue") - expect('').assertEqual(pre2); - done(); - }); - }) - - /** - * @tc.name clear、put、get、flush String callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0120 - * @tc.desc flush String callback interface test - */ - it('testPreferencesCallback0172', 0, function (done) { - console.log(TAG + "testPreferencesCallback0172 begin."); - mPreferences.clear(function (err, val) { - if(err){ - expect(null).assertEqual(); - } - mPreferences.put(KEY_TEST_STRING_ELEMENT, '', function (err, ret) { - if(err){ - expect(null).assertEqual(); - } - mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, pre) { - if(err){ - expect(null).assertEqual(); - } - expect('').assertEqual(pre); - mPreferences.flush(function (err, val) { - if(err){ - expect(null).assertEqual(); - } - mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, pre2) { - if(err){ - expect(null).assertEqual(); - } - expect('').assertEqual(pre2); - done(); - console.log(TAG + "testPreferencesCallback0172 end."); - }) - }); - }) - }); - }); - }) - - /** - * @tc.name put StringArray callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0001 - * @tc.desc put String callback interface test - */ - it('testPreferencesPutStringArray0001', 0, async function (done) { - await mPreferences.clear(); - var stringArr = ['11', '22', '33'] - await mPreferences.put(KEY_TEST_STRING_ARRAY_ELEMENT, stringArr, async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_STRING_ARRAY_ELEMENT, ['123', '321']) - for (let i = 0; i < stringArr.length; i++) { - expect(stringArr[i]).assertEqual(pre[i]); - } - - done(); - }); - }) - - /** - * @tc.name put NumberArray callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0002 - * @tc.desc put String callback interface test - */ - it('testPreferencesPutNumArray0001', 0, async function (done) { - await mPreferences.clear(); - var doubleArr = [11, 22, 33] - await mPreferences.put(KEY_TEST_NUMBER_ARRAY_ELEMENT, doubleArr, async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_NUMBER_ARRAY_ELEMENT, [123, 321]) - for (let i = 0; i < doubleArr.length; i++) { - expect(doubleArr[i]).assertEqual(pre[i]); - } - - done(); - }); - }) - - /** - * @tc.name put BoolArray callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0003 - * @tc.desc put String callback interface test - */ - it('testPreferencesPutBoolArray0001', 0, async function (done) { - await mPreferences.clear(); - let boolArr = [true, false, false, true] - await mPreferences.put(KEY_TEST_BOOL_ARRAY_ELEMENT, boolArr, async function (err, ret) { - let pre = await mPreferences.get(KEY_TEST_BOOL_ARRAY_ELEMENT, [true, false]) - for (let i = 0; i < boolArr.length; i++) { - expect(boolArr[i]).assertEqual(pre[i]); - } - - done(); - }); - }) - - /** - * @tc.name getAll callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0004 - * @tc.desc getAll callback interface test - */ - it('testPreferencesGetAll0001', 0, async function (done) { - await mPreferences.clear(); - let doubleArr = [11, 22, 33] - let stringArr = ['11', '22', '33'] - let boolArr = [true, false, false, true] - await mPreferences.put(KEY_TEST_STRING_ARRAY_ELEMENT, stringArr) - await mPreferences.put(KEY_TEST_BOOL_ARRAY_ELEMENT, boolArr) - await mPreferences.put(KEY_TEST_NUMBER_ARRAY_ELEMENT, doubleArr) - await mPreferences.put(KEY_TEST_BOOLEAN_ELEMENT, false) - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "123") - await mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 123.1) - - await mPreferences.flush() - - await mPreferences.getAll(function (err, obj) { - expect(false).assertEqual(obj.key_test_boolean) - expect("123").assertEqual(obj.key_test_string) - expect(123.1).assertEqual(obj.key_test_float) - let sArr = obj.key_test_string_array - for (let i = 0; i < sArr.length; i++) { - expect(sArr[i]).assertEqual(stringArr[i]); - } - - let bArr = obj.key_test_bool_array - for (let i = 0; i < bArr.length; i++) { - expect(bArr[i]).assertEqual(boolArr[i]); - } - - let nArr = obj.key_test_number_array - for (let i = 0; i < nArr.length; i++) { - expect(nArr[i]).assertEqual(doubleArr[i]); - } - - done() - }) - }) - - /** - * @tc.name get empty array callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0131 - * @tc.desc get empty array callback interface test - */ - it('testPreferencesGetEmptyArray0001', 0, function (done) { - let defaultValue = new Array(); - mPreferences.get("mytest", defaultValue, (err, value) => { - if (err) { - expect(null).assertFail(); - done(); - } - expect(value).assertEqual(defaultValue); - done(); - }); - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/PreferencesHelperJsunit.test.js b/preferences/test/js/unittest/src/PreferencesHelperJsunit.test.js deleted file mode 100644 index 6c9c42b9..00000000 --- a/preferences/test/js/unittest/src/PreferencesHelperJsunit.test.js +++ /dev/null @@ -1,147 +0,0 @@ -// @ts-nocheck -/* -* 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. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import data_preferences from '@ohos.data.preferences' -import featureAbility from '@ohos.ability.featureAbility'; - -const NAME = 'test_preferences'; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -var mPreferences; -var context; -describe('preferencesTest', function () { - beforeAll(async function () { - console.info('beforeAll') - context = featureAbility.getContext() - mPreferences = await data_preferences.getPreferences(context, NAME); - }) - - afterAll(async function () { - console.info('afterAll') - await data_preferences.deletePreferences(context, NAME); - }) - - /** - * @tc.name getPreferencesSync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0010 - * @tc.desc getPreferencesSync interface test - */ - it('testGetPreferencesHelper001', 0, async function () { - mPreferences = await data_preferences.getPreferences(context, NAME); - await mPreferences.put('test', 2); - await mPreferences.flush(); - var value = await mPreferences.get('test', 0); - expect(value).assertEqual(2); - }) - - /** - * @tc.name getPreferences interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0020 - * @tc.desc getPreferences interface test - */ - it('testGetPreferencesHelper002', 0, async function (done) { - const promise = data_preferences.getPreferences(context, NAME); - promise.then(async (pref) => { - await pref.put('test', 2); - await pref.flush(); - var value = await mPreferences.get('test', 0); - done(); - expect(value).assertEqual(2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - }) - - /** - * @tc.name removePreferencesFromCache interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0030 - * @tc.desc removePreferencesFromCache interface test - */ - it('testRemovePreferencesFromCache001', 0, async function (done) { - let perf = await data_preferences.getPreferences(context, NAME); - perf = null; - const promise = data_preferences.removePreferencesFromCache(context, NAME); - promise.then((pref) => { - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name deletePreferences interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0060 - * @tc.desc deletePreferences interface test - */ - it('testDeletePreferencesHelper002', 0, async function (done) { - let perf = await data_preferences.getPreferences(context, NAME); - perf = null; - const promise = data_preferences.deletePreferences(context, NAME); - promise.then((pref) => { - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name put interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_0140 - * @tc.desc put interface test - */ - it('testPreferencesRegisterObserver001', 0, async function () { - await mPreferences.clear(); - var observer = function (key) { - console.info('testPreferencesRegisterObserver001 key' + key); - expect('abcd').assertEqual(key); - }; - await mPreferences.on('change', observer); - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "abcd"); - }) - - /** - * @tc.name repeat on interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_0150 - * @tc.desc repeat on interface test - */ - it('testPreferencesRegisterObserver002', 0, async function () { - await mPreferences.clear(); - var observer = function (key) { - console.info('testPreferencesRegisterObserver002 key' + key); - expect('abc').assertEqual(key); - }; - await mPreferences.on('change', observer); - await mPreferences.on('change', observer); - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "abc"); - }) - - /** - * @tc.name off interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_0160 - * @tc.desc off interface test - */ - it('testPreferencesUnRegisterObserver001', 0, async function () { - var observer = function (key) { - console.info('testPreferencesUnRegisterObserver001 key' + key); - expect('').assertEqual(key); - }; - await mPreferences.on('change', observer); - await mPreferences.off('change', observer); - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "abc"); - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/PreferencesPromiseJsunit.test.js b/preferences/test/js/unittest/src/PreferencesPromiseJsunit.test.js deleted file mode 100644 index 6d9fdd89..00000000 --- a/preferences/test/js/unittest/src/PreferencesPromiseJsunit.test.js +++ /dev/null @@ -1,469 +0,0 @@ -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' -import data_preferences from '@ohos.data.preferences' -import featureAbility from '@ohos.ability.featureAbility'; - -const NAME = 'test_preferences'; -const KEY_TEST_INT_ELEMENT = 'key_test_int'; -const KEY_TEST_LONG_ELEMENT = 'key_test_long'; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const KEY_TEST_BOOLEAN_ELEMENT = 'key_test_boolean'; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const KEY_TEST_NUMBER_ARRAY_ELEMENT = 'key_test_number_array' -const KEY_TEST_STRING_ARRAY_ELEMENT = 'key_test_string_array' -const KEY_TEST_BOOL_ARRAY_ELEMENT = 'key_test_bool_array' -var mPreferences; -var context; - -describe('preferencesTest', function () { - beforeAll(async function () { - console.info('beforeAll') - context = featureAbility.getContext() - mPreferences = await data_preferences.getPreferences(context, NAME); - }) - - afterAll(async function () { - console.info('afterAll') - await data_preferences.deletePreferences(context, NAME); - }) - - /** - * @tc.name put StringArray promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0131 - * @tc.desc put StringArray promise interface test - */ - it('testPreferencesPutStringArray0131', 0, async function (done) { - await mPreferences.clear(); - var stringArr = ['1', '2', '3'] - let promise1 = mPreferences.put(KEY_TEST_STRING_ARRAY_ELEMENT, stringArr) - await promise1 - let promise2 = mPreferences.get(KEY_TEST_STRING_ARRAY_ELEMENT, ['123', '321']) - promise2.then((pre) => { - for (let i = 0; i < stringArr.length; i++) { - expect(stringArr[i]).assertEqual(pre[i]); - } - - }).catch((err) => { - expect(null).assertFail(); - }) - await promise2 - - done(); - }); - - /** - * @tc.name put NumberArray promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0132 - * @tc.desc put NumberArray promise interface test - */ - it('testPreferencesPutNumberArray0132', 0, async function (done) { - await mPreferences.clear(); - var numberArr = [11, 22, 33, 44, 55] - let promise1 = mPreferences.put(KEY_TEST_NUMBER_ARRAY_ELEMENT, numberArr) - await promise1 - let promise2 = mPreferences.get(KEY_TEST_NUMBER_ARRAY_ELEMENT, [123, 321]) - promise2.then((pre) => { - for (let i = 0; i < numberArr.length; i++) { - expect(numberArr[i]).assertEqual(pre[i]); - } - }).catch((err) => { - expect(null).assertFail(); - }) - await promise2 - - done(); - }); - - /** - * @tc.name put BoolArray promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0133 - * @tc.desc put BoolArray promise interface test - */ - it('testPreferencesPutBoolArray0133', 0, async function (done) { - await mPreferences.clear(); - var boolArr = [true, true, false] - let promise1 = mPreferences.put(KEY_TEST_BOOL_ARRAY_ELEMENT, boolArr) - await promise1 - let promise2 = mPreferences.get(KEY_TEST_BOOL_ARRAY_ELEMENT, [false, true]) - promise2.then((pre) => { - for (let i = 0; i < boolArr.length; i++) { - expect(boolArr[i]).assertEqual(pre[i]); - } - }).catch((err) => { - expect(null).assertFail(); - }) - await promise2 - - done(); - }); - - /** - * @tc.name getAll promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0133 - * @tc.desc getAll promise interface test - */ - it('testPreferencesGetAll0001', 0, async function (done) { - await mPreferences.clear(); - let doubleArr = [11, 22, 33] - let stringArr = ['11', '22', '33'] - let boolArr = [true, false, false, true] - await mPreferences.put(KEY_TEST_STRING_ARRAY_ELEMENT, stringArr) - await mPreferences.put(KEY_TEST_BOOL_ARRAY_ELEMENT, boolArr) - await mPreferences.put(KEY_TEST_NUMBER_ARRAY_ELEMENT, doubleArr) - await mPreferences.put(KEY_TEST_BOOLEAN_ELEMENT, false) - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "123") - await mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 123.1) - - await mPreferences.flush() - - let promise = mPreferences.getAll() - promise.then((obj) => { - expect(false).assertEqual(obj.key_test_boolean) - expect("123").assertEqual(obj.key_test_string) - expect(123.1).assertEqual(obj.key_test_float) - let sArr = obj.key_test_string_array - for (let i = 0; i < sArr.length; i++) { - expect(sArr[i]).assertEqual(stringArr[i]); - } - - let bArr = obj.key_test_bool_array - for (let i = 0; i < bArr.length; i++) { - expect(bArr[i]).assertEqual(boolArr[i]); - } - - let nArr = obj.key_test_number_array - for (let i = 0; i < nArr.length; i++) { - expect(nArr[i]).assertEqual(doubleArr[i]); - } - }).catch((err) => { - expect(null).assertFail(); - }) - await promise - - done(); - }) - - /** - * @tc.name clear promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Promise_0010 - * @tc.desc clear promise interface test - */ - it('testPreferencesClear0011', 0, async function (done) { - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "test"); - await mPreferences.flush(); - const promise = mPreferences.clear(); - promise.then(async (ret) => { - let per = await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue"); - done(); - expect("defaultvalue").assertEqual(per); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - }) - - /** - * @tc.name has string interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0020 - * @tc.desc has string interface test - */ - it('testPreferencesHasKey0031', 0, async function (done) { - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "test"); - const promise = mPreferences.has(KEY_TEST_STRING_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has int interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0140 - * @tc.desc has int interface test - */ - it('testPreferencesHasKey0032', 0, async function (done) { - await mPreferences.put(KEY_TEST_INT_ELEMENT, 1); - const promise = mPreferences.has(KEY_TEST_INT_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has float interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0150 - * @tc.desc has float interface test - */ - it('testPreferencesHasKey0033', 0, async function (done) { - await mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 2.0); - const promise = mPreferences.has(KEY_TEST_FLOAT_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has boolean interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0160 - * @tc.desc has boolean interface test - */ - it('testPreferencesHasKey0034', 0, async function (done) { - await mPreferences.put(KEY_TEST_BOOLEAN_ELEMENT, false); - const promise = mPreferences.has(KEY_TEST_BOOLEAN_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has long interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0170 - * @tc.desc has long interface test - */ - it('testPreferencesHasKey0035', 0, async function (done) { - await mPreferences.put(KEY_TEST_LONG_ELEMENT, 0); - const promise = mPreferences.has(KEY_TEST_LONG_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get string promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0030 - * @tc.desc get string promise interface test - */ - it('testPreferencesGetDefValue0061', 0, async function (done) { - await mPreferences.clear(); - const promise = mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultValue"); - promise.then((ret) => { - expect('defaultValue').assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get float promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0040 - * @tc.desc get float promise interface test - */ - it('testPreferencesGetFloat0071', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 3.0); - const promise = mPreferences.get(KEY_TEST_FLOAT_ELEMENT, 0.0); - promise.then((ret) => { - expect(3.0).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get int promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0050 - * @tc.desc get int promise interface test - */ - it('testPreferencesGetInt0081', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_INT_ELEMENT, 3); - const promise = mPreferences.get(KEY_TEST_INT_ELEMENT, 0.0); - promise.then((ret) => { - expect(3).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get long promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0060 - * @tc.desc get long promise interface test - */ - it('testPreferencesGetLong0091', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_LONG_ELEMENT, 3); - const promise = mPreferences.get(KEY_TEST_LONG_ELEMENT, 0); - promise.then((ret) => { - expect(3).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get String promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0070 - * @tc.desc get String promise interface test - */ - it('tesPreferencesGetString101', 0, async function (done) { - await mPreferences.clear(); - await mPreferences.put(KEY_TEST_STRING_ELEMENT, "test"); - await mPreferences.flush(); - const promise = mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue"); - promise.then((ret) => { - expect('test').assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name put boolean promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0090 - * @tc.desc put boolean promise interface test - */ - it('testPreferencesPutBoolean0121', 0, async function (done) { - const promise = mPreferences.put(KEY_TEST_BOOLEAN_ELEMENT, true); - promise.then(async (ret) => { - let per = await mPreferences.get(KEY_TEST_BOOLEAN_ELEMENT, false); - expect(true).assertEqual(per); - await mPreferences.flush(); - let per2 = await mPreferences.get(KEY_TEST_BOOLEAN_ELEMENT, false); - done(); - expect(true).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - }) - - /** - * @tc.name put float promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0100 - * @tc.desc put float promise interface test - */ - it('testPreferencesPutFloat0131', 0, async function (done) { - const promise = mPreferences.put(KEY_TEST_FLOAT_ELEMENT, 4.0); - promise.then(async (ret) => { - let per = await mPreferences.get(KEY_TEST_FLOAT_ELEMENT, 0.0); - expect(4.0).assertEqual(per); - await mPreferences.flush(); - let per2 = await mPreferences.get(KEY_TEST_FLOAT_ELEMENT, 0.0); - done(); - expect(4.0).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - }) - - /** - * @tc.name put int promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0110 - * @tc.desc put int promise interface test - */ - it('testPreferencesPutInt0141', 0, async function (done) { - const promise = mPreferences.put(KEY_TEST_INT_ELEMENT, 4); - promise.then(async (ret) => { - let per = await mPreferences.get(KEY_TEST_INT_ELEMENT, 0); - expect(4).assertEqual(per); - await mPreferences.flush(); - let per2 = await mPreferences.get(KEY_TEST_INT_ELEMENT, 0); - done(); - expect(4).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - }) - - /** - * @tc.name put long promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0120 - * @tc.desc put long promise interface test - */ - it('testPreferencesPutLong0151', 0, async function (done) { - const promise = mPreferences.put(KEY_TEST_LONG_ELEMENT, 4); - promise.then(async (ret) => { - let per = await mPreferences.get(KEY_TEST_LONG_ELEMENT, 0); - expect(4).assertEqual(per); - await mPreferences.flush(); - let per2 = await mPreferences.get(KEY_TEST_LONG_ELEMENT, 0); - done(); - expect(4).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - }) - - /** - * @tc.name put String promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0130 - * @tc.desc put String promise interface test - */ - it('testPreferencesPutString0161', 0, async function (done) { - const promise = mPreferences.put(KEY_TEST_STRING_ELEMENT, ''); - promise.then(async (ret) => { - let per = await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue") - expect('').assertEqual(per); - await mPreferences.flush(); - let per2 = await mPreferences.get(KEY_TEST_STRING_ELEMENT, "defaultvalue") - done(); - expect('').assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - }) - - /** - * @tc.name get empty array promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Preferences_0131 - * @tc.desc get empty array promise interface test - */ - it('testPreferencesGetEmptyArray0161', 0, function (done) { - let defaultValue = new Array(); - let data = mPreferences.get("mytest", defaultValue); - data.then((value) => { - expect(value).assertEqual(defaultValue); - done(); - }).catch((err)=> { - expect(null).assertFail(); - done(); - }) - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/StorageCallBackJsunit.test.js b/preferences/test/js/unittest/src/StorageCallBackJsunit.test.js deleted file mode 100644 index 1cf484e4..00000000 --- a/preferences/test/js/unittest/src/StorageCallBackJsunit.test.js +++ /dev/null @@ -1,494 +0,0 @@ -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import storage from '@ohos.data.storage' - -const PATH = "/data/storage/el2/database/test_storage"; -const KEY_TEST_INT_ELEMENT = 'key_test_int'; -const KEY_TEST_LONG_ELEMENT = 'key_test_long'; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const KEY_TEST_BOOLEAN_ELEMENT = 'key_test_boolean'; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -var mPref; - -describe('storageTest', function () { - beforeAll(function () { - console.info('beforeAll') - mPref = storage.getStorageSync(PATH); - }) - - afterAll(function () { - console.info('afterAll') - storage.deleteStorageSync(PATH); - }) - - /** - * @tc.name clear callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0010 - * @tc.desc clear callback interface test - */ - it('testClear0012', 0, async function (done) { - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - mPref.flushSync(); - await mPref.clear(function (err, ret) { - expect("defaultvalue").assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - done(); - }); - }) - - /** - * @tc.name has string callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0020 - * @tc.desc has string callback interface test - */ - it('testHasKey0032', 0, async function (done) { - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - await mPref.has(KEY_TEST_STRING_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has int callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0130 - * @tc.desc has int callback interface test - */ - it('testHasKey0033', 0, async function (done) { - mPref.putSync(KEY_TEST_INT_ELEMENT, 1); - await mPref.has(KEY_TEST_INT_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has float callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0140 - * @tc.desc has float callback interface test - */ - it('testHasKey0034', 0, async function (done) { - mPref.putSync(KEY_TEST_FLOAT_ELEMENT, 1.1); - await mPref.has(KEY_TEST_FLOAT_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has long callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0150 - * @tc.desc has long callback interface test - */ - it('testHasKey0035', 0, async function (done) { - mPref.putSync(KEY_TEST_LONG_ELEMENT, 0); - await mPref.has(KEY_TEST_LONG_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name has boolean callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0160 - * @tc.desc has boolean callback interface test - */ - it('testHasKey0036', 0, async function (done) { - mPref.putSync(KEY_TEST_BOOLEAN_ELEMENT, false); - await mPref.has(KEY_TEST_BOOLEAN_ELEMENT, function (err, ret) { - expect(true).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get defaultValue callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0030 - * @tc.desc get defaultValue callback interface test - */ - it('testGetDefValue0062', 0, async function (done) { - mPref.clearSync(); - await mPref.get(KEY_TEST_STRING_ELEMENT, "defaultValue", function (err, ret) { - expect('defaultValue').assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get float callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0040 - * @tc.desc get float callback interface test - */ - it('testGetFloat0072', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_FLOAT_ELEMENT, 3.0); - await mPref.get(KEY_TEST_FLOAT_ELEMENT, 0.0, function (err, ret) { - expect(3.0).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get int callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0050 - * @tc.desc get int callback interface test - */ - it('testGetInt0082', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_INT_ELEMENT, 3); - await mPref.get(KEY_TEST_INT_ELEMENT, 0.0, function (err, ret) { - expect(3).assertEqual(ret); - done(); - }) - }) - - /** - * @tc.name get long callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0060 - * @tc.desc get long callback interface test - */ - it('testGetLong0092', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_LONG_ELEMENT, 3); - expect(3).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - await mPref.get(KEY_TEST_LONG_ELEMENT, 0, function (err, ret) { - expect(3).assertEqual(ret); - done(); - }); - }) - - /** - * @tc.name get String callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0070 - * @tc.desc get String callback interface test - */ - it('testGetString102', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - mPref.flushSync(); - await mPref.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, ret) { - expect('test').assertEqual(ret); - done(); - }); - }) - - /** - * @tc.name put boolean callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0080 - * @tc.desc put boolean callback interface test - */ - it('testPutBoolean0122', 0, async function (done) { - mPref.clearSync(); - await mPref.put(KEY_TEST_BOOLEAN_ELEMENT, true, function (err, ret) { - expect(true).assertEqual(mPref.getSync(KEY_TEST_BOOLEAN_ELEMENT, false)); - mPref.flushSync(); - expect(true).assertEqual(mPref.getSync(KEY_TEST_BOOLEAN_ELEMENT, false)); - done(); - }); - }) - - /** - * @tc.name put float callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0090 - * @tc.desc put float callback interface test - */ - it('testPutFloat0132', 0, async function (done) { - mPref.clearSync(); - await mPref.put(KEY_TEST_FLOAT_ELEMENT, 4.0, function (err, ret) { - expect(4.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 0.0)); - mPref.flushSync(); - expect(4.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 0.0)); - done(); - }); - }) - - /** - * @tc.name put int callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0100 - * @tc.desc put int callback interface test - */ - it('testPutInt0142', 0, async function (done) { - mPref.clearSync(); - await mPref.put(KEY_TEST_INT_ELEMENT, 4, function (err, ret) { - expect(4).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0)); - mPref.flushSync(); - expect(4).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0)); - done(); - }); - }) - - /** - * @tc.name put long callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0110 - * @tc.desc put long callback interface test - */ - it('testPutLong0152', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_LONG_ELEMENT, 4); - await mPref.put(KEY_TEST_LONG_ELEMENT, 4, function (err, ret) { - expect(4).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - mPref.flushSync(); - expect(4).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - done(); - }); - }) - - /** - * @tc.name put String callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0120 - * @tc.desc put String callback interface test - */ - it('testPutString0162', 0, async function (done) { - mPref.clearSync(); - await mPref.put(KEY_TEST_STRING_ELEMENT, '', function (err, ret) { - expect('').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - mPref.flushSync(); - expect('').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - done(); - }); - }) - - /** - * @tc.name clear、put、get、flush String callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0120 - * @tc.desc flush String callback interface test - */ - it('testCallback0172', 0, function (done) { - console.log("*******************testCallback0172 begin."); - mPref.clear(function (err, val) { - if(err){ - console.log("*******************clear error: " + err); - expect(false).assertTrue(); - } - mPref.put(KEY_TEST_STRING_ELEMENT, '', function (err, ret) { - if(err){ - console.log("*******************put error: " + err); - expect(false).assertTrue(); - } - console.log("*******************put done."); - mPref.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, pre) { - if(err){ - console.log("*******************get error: " + err); - expect(false).assertTrue(); - } - expect('').assertEqual(pre); - mPref.flush(function (err, val) { - if(err){ - console.log("*******************flush error: " + err); - expect(false).assertTrue(); - } - mPref.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, pre2) { - if(err){ - console.log("*******************get error: " + err); - expect(false).assertTrue(); - } - expect('').assertEqual(pre2); - done(); - console.log("*******************testCallback0172 end."); - }) - }); - }) - }); - }); - }) - - /** - * @tc.name test put interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0121 - * @tc.desc test put interface input parameter is illegal. - */ - it('testPutIllegal001', 0, async function (done) { - let illegalKey = false; - let legalValue = "test"; - try { - mPref.put(illegalKey, legalValue, (ret) => { - done(); - }); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0122 - * @tc.desc test put interface input parameter is illegal. - */ - it('testPutIllegal002', 0, async function (done) { - let illegalKey = 123; - let legalValue = "test"; - try { - mPref.put(illegalKey, legalValue, (ret) => { - done(); - }); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0123 - * @tc.desc test put interface input parameter value exceed 8192byte. - */ - it('testPutIllegal003', 0, async function (done) { - let phoneStr = "1"; - phoneStr = phoneStr.repeat(8193); - try { - mPref.put("phoneNum", phoneStr, (ret) => { - done(); - }); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0124 - * @tc.desc test put interface input parameter value is legal. - */ - it('testPutIllegal004', 0, async function (done) { - let phoneStr = "1"; - phoneStr = phoneStr.repeat(8192); - try { - mPref.put("phoneNum", phoneStr, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0125 - * @tc.desc test put interface input parameter key exceed 80byte. - */ - it('testPutIllegal005', 0, async function (done) { - let phoneNum = "1"; - phoneNum = phoneNum.repeat(81); - try { - mPref.put(phoneNum, "123456", (ret) => { - done(); - }); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0126 - * @tc.desc test put interface input parameter key is legal. - */ - it('testPutIllegal006', 0, async function (done) { - let phoneNum = "1"; - phoneNum = phoneNum.repeat(80); - try { - mPref.put(phoneNum, "123456", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0127 - * @tc.desc test get interface input parameter is illegal. - */ - it('testGetIllegal001', 0, async function (done) { - let illegalKey = 123; - try { - mPref.get(illegalKey, "defaultValue", (ret) => { - done(); - }); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0127 - * @tc.desc test get interface input parameter is illegal. - */ - it('testGetIllegal002', 0, async function (done) { - let illegalKey = true; - try { - mPref.get(illegalKey, "defaultValue", (ret) => { - done(); - }); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0128 - * @tc.desc test get interface input parameter key exceed 80byte. - */ - it('testGetIllegal003', 0, async function (done) { - let illegalKey = "1"; - illegalKey = illegalKey.repeat(81); - try { - mPref.get(illegalKey, "defaultValue", (ret) => { - done(); - }); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0129 - * @tc.desc test get interface input parameter key is legal. - */ - it('testGetIllegal004', 0, async function (done) { - let legalKey = "1"; - legalKey = legalKey.repeat(80); - try { - mPref.get(legalKey, "defaultValue", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - done(); - } - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/StorageHelperJsunit.test.js b/preferences/test/js/unittest/src/StorageHelperJsunit.test.js deleted file mode 100644 index 369c87f8..00000000 --- a/preferences/test/js/unittest/src/StorageHelperJsunit.test.js +++ /dev/null @@ -1,134 +0,0 @@ -// @ts-nocheck -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import storage from '@ohos.data.storage' - -const PATH = "/data/storage/el2/database/test_storage"; -var mPref; - -describe('storageTest', function () { - beforeAll(function () { - console.info('beforeAll') - mPref = storage.getStorageSync(PATH); - }) - - afterAll(function () { - console.info('afterAll') - storage.deleteStorageSync(PATH); - }) - - /** - * @tc.name getStorageSync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0010 - * @tc.desc getStorageSync interface test - */ - it('testGetStorageHelper001', 0, function () { - mPref = storage.getStorageSync(PATH); - mPref.putSync('test', 2); - mPref.flushSync(); - var value = mPref.getSync('test', 0); - expect(value).assertEqual(2); - }) - - /** - * @tc.name getStorage interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0020 - * @tc.desc getStorage interface test - */ - it('testGetStorageHelper002', 0, async function (done) { - const promise = storage.getStorage(PATH); - promise.then((pref) => { - pref.putSync('test', 2); - pref.flushSync(); - var value = mPref.getSync('test', 0); - expect(value).assertEqual(2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name removeStorageFromCacheSync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0030 - * @tc.desc removeStorageFromCacheSync interface test - */ - it('testRemoveStorageFromCache001', 0, function () { - let perf = storage.getStorageSync('/data/test_storage1'); - perf.putSync('test', 2); - try { - storage.removeStorageFromCacheSync('/data/test_storage1'); - } catch (e) { - expect(null).assertFail(); - } - var value = mPref.getSync('test', 0); - expect(value).assertEqual(2); - }) - - /** - * @tc.name removeStorageFromCache interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0040 - * @tc.desc removeStorageFromCache interface test - */ - it('testRemoveStorageFromCache002', 0, async function (done) { - let perf = storage.getStorageSync('/data/test_storage2'); - perf = null; - const promise = storage.removeStorageFromCache('/data/test_storage2'); - promise.then((pref) => { - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name deleteStorageSync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0050 - * @tc.desc deleteStorageSync interface test - */ - it('testDeleteStorageHelper001', 0, function () { - let perf = storage.getStorageSync('/data/test_storage3'); - try { - storage.deleteStorageSync('/data/test_storage3'); - } catch (e) { - expect(null).assertFail(); - } - try { - perf.putSync("int", 3); - } catch (e) { - expect(null).assertFail(); - } - }) - - /** - * @tc.name deleteStorage interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0060 - * @tc.desc deleteStorage interface test - */ - it('testDeleteStorageHelper002', 0, async function (done) { - let perf = storage.getStorageSync('/data/test_storage4'); - perf = null; - const promise = storage.deleteStorage('/data/test_storage4'); - promise.then((pref) => { - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/StoragePromiseJsunit.test.js b/preferences/test/js/unittest/src/StoragePromiseJsunit.test.js deleted file mode 100644 index 688ee134..00000000 --- a/preferences/test/js/unittest/src/StoragePromiseJsunit.test.js +++ /dev/null @@ -1,326 +0,0 @@ -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import storage from '@ohos.data.storage' - -const PATH = "/data/storage/el2/database/test_storage"; -const KEY_TEST_INT_ELEMENT = 'key_test_int'; -const KEY_TEST_LONG_ELEMENT = 'key_test_long'; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const KEY_TEST_BOOLEAN_ELEMENT = 'key_test_boolean'; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -var mPref; - -describe('storageTest', function () { - beforeAll(function () { - console.info('beforeAll') - mPref = storage.getStorageSync(PATH); - }) - - afterAll(function () { - console.info('afterAll') - storage.deleteStorageSync(PATH); - }) - - /** - * @tc.name clear promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Promise_0010 - * @tc.desc clear promise interface test - */ - it('testClear0011', 0, async function (done) { - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - mPref.flushSync(); - const promise = mPref.clear(); - promise.then((ret) => { - expect("defaultvalue").assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has string interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0020 - * @tc.desc has string interface test - */ - it('testHasKey0031', 0, async function (done) { - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - const promise = mPref.has(KEY_TEST_STRING_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has int interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0140 - * @tc.desc has int interface test - */ - it('testHasKey0032', 0, async function (done) { - mPref.putSync(KEY_TEST_INT_ELEMENT, 1); - const promise = mPref.has(KEY_TEST_INT_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has float interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0150 - * @tc.desc has float interface test - */ - it('testHasKey0033', 0, async function (done) { - mPref.putSync(KEY_TEST_FLOAT_ELEMENT, 2.0); - const promise = mPref.has(KEY_TEST_FLOAT_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has boolean interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0160 - * @tc.desc has boolean interface test - */ - it('testHasKey0034', 0, async function (done) { - mPref.putSync(KEY_TEST_BOOLEAN_ELEMENT, false); - const promise = mPref.has(KEY_TEST_BOOLEAN_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name has long interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0170 - * @tc.desc has long interface test - */ - it('testHasKey0035', 0, async function (done) { - mPref.putSync(KEY_TEST_LONG_ELEMENT, 0); - const promise = mPref.has(KEY_TEST_LONG_ELEMENT); - promise.then((ret) => { - expect(true).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get string promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0030 - * @tc.desc get string promise interface test - */ - it('testGetDefValue0061', 0, async function (done) { - mPref.clearSync(); - const promise = mPref.get(KEY_TEST_STRING_ELEMENT, "defaultValue"); - promise.then((ret) => { - expect('defaultValue').assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get float promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0040 - * @tc.desc get float promise interface test - */ - it('testGetFloat0071', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_FLOAT_ELEMENT, 3.0); - const promise = mPref.get(KEY_TEST_FLOAT_ELEMENT, 0.0); - promise.then((ret) => { - expect(3.0).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get int promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0050 - * @tc.desc get int promise interface test - */ - it('testGetInt0081', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_INT_ELEMENT, 3); - const promise = mPref.get(KEY_TEST_INT_ELEMENT, 0.0); - promise.then((ret) => { - expect(3).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get long promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0060 - * @tc.desc get long promise interface test - */ - it('testGetLong0091', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_LONG_ELEMENT, 3); - const promise = mPref.get(KEY_TEST_LONG_ELEMENT, 0); - promise.then((ret) => { - expect(3).assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name get String promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0070 - * @tc.desc get String promise interface test - */ - it('testGetString101', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - mPref.flushSync(); - const promise = mPref.get(KEY_TEST_STRING_ELEMENT, "defaultvalue"); - promise.then((ret) => { - expect('test').assertEqual(ret); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name put boolean promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0090 - * @tc.desc put boolean promise interface test - */ - it('testPutBoolean0121', 0, async function (done) { - mPref.clearSync(); - const promise = mPref.put(KEY_TEST_BOOLEAN_ELEMENT, true); - promise.then((ret) => { - expect(true).assertEqual(mPref.getSync(KEY_TEST_BOOLEAN_ELEMENT, false)); - mPref.flushSync(); - expect(true).assertEqual(mPref.getSync(KEY_TEST_BOOLEAN_ELEMENT, false)); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name put float promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0100 - * @tc.desc put float promise interface test - */ - it('testPutFloat0131', 0, async function (done) { - mPref.clearSync(); - const promise = mPref.put(KEY_TEST_FLOAT_ELEMENT, 4.0); - promise.then((ret) => { - expect(4.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 0.0)); - mPref.flushSync(); - expect(4.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 0.0)); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name put int promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0110 - * @tc.desc put int promise interface test - */ - it('testPutInt0141', 0, async function (done) { - mPref.clearSync(); - const promise = mPref.put(KEY_TEST_INT_ELEMENT, 4); - promise.then((ret) => { - expect(4).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0)); - mPref.flushSync(); - expect(4).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0)); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name put long promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0120 - * @tc.desc put long promise interface test - */ - it('testPutLong0151', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_LONG_ELEMENT, 4); - const promise = mPref.put(KEY_TEST_LONG_ELEMENT, 4); - promise.then((ret) => { - expect(4).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - mPref.flushSync(); - expect(4).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @tc.name put String promise interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Storage_0130 - * @tc.desc put String promise interface test - */ - it('testPutString0161', 0, async function (done) { - mPref.clearSync(); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "abc"); - const promise = mPref.put(KEY_TEST_STRING_ELEMENT, ''); - promise.then((ret) => { - expect('').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - mPref.flushSync(); - expect('').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/StorageSyncJsunit.test.js b/preferences/test/js/unittest/src/StorageSyncJsunit.test.js deleted file mode 100644 index 19239949..00000000 --- a/preferences/test/js/unittest/src/StorageSyncJsunit.test.js +++ /dev/null @@ -1,449 +0,0 @@ -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import storage from '@ohos.data.storage' - -const PATH = "/data/storage/el2/database/test_storage"; -const KEY_TEST_INT_ELEMENT = 'key_test_int'; -const KEY_TEST_LONG_ELEMENT = 'key_test_long'; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const KEY_TEST_BOOLEAN_ELEMENT = 'key_test_boolean'; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - -var mPref; - -describe('storageTest', function () { - beforeAll(function() { - console.info('beforeAll') - mPref = storage.getStorageSync(PATH); - }) - - afterAll(function () { - console.info('afterAll') - storage.deleteStorageSync(PATH); - }) - - it('testClear001', 0, function () { - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - mPref.putSync(KEY_TEST_INT_ELEMENT, 3); - mPref.flushSync(); - mPref.clearSync(); - expect("defaultvalue").assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - expect(0).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0)); - }) - - /** - * @tc.name Constructor test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0010 - * @tc.desc Constructor test - */ - it('testConstructor002', 0, function () { - expect('to:' + mPref).assertEqual('to:[object Object]'); - }) - - /** - * @tc.name put string sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0020 - * @tc.desc put string sync interface test - */ - it('testHasKey003', 0, function () { - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - expect(true).assertEqual(mPref.hasSync(KEY_TEST_STRING_ELEMENT)); - }) - - /** - * @tc.name put int sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0170 - * @tc.desc put int sync interface test - */ - it('testHasKey004', 0, function () { - mPref.putSync(KEY_TEST_INT_ELEMENT, 1); - expect(true).assertEqual(mPref.hasSync(KEY_TEST_INT_ELEMENT)); - }) - - /** - * @tc.name put boolean sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0180 - * @tc.desc put boolean sync interface test - */ - it('testHasKey005', 0, function () { - mPref.putSync(KEY_TEST_BOOLEAN_ELEMENT, false); - expect(true).assertEqual(mPref.hasSync(KEY_TEST_BOOLEAN_ELEMENT)); - }) - - /** - * @tc.name put long sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0190 - * @tc.desc put long sync interface test - */ - it('testHasKey006', 0, function () { - mPref.putSync(KEY_TEST_LONG_ELEMENT, 0); - expect(true).assertEqual(mPref.hasSync(KEY_TEST_LONG_ELEMENT)); - }) - - /** - * @tc.name put float sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0200 - * @tc.desc put float sync interface test - */ - it('testHasKey007', 0, function () { - mPref.putSync(KEY_TEST_FLOAT_ELEMENT, 1.1); - expect(true).assertEqual(mPref.hasSync(KEY_TEST_FLOAT_ELEMENT)); - }) - - /** - * @tc.name put boolean sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0030 - * @tc.desc put boolean sync interface test - */ - it('testGetBoolean005', 0, function () { - mPref.putSync(KEY_TEST_LONG_ELEMENT, true); - expect(true).assertEqual(mPref.hasSync(KEY_TEST_LONG_ELEMENT)); - }) - - /** - * @tc.name get defaultValue sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0040 - * @tc.desc get defaultValue sync interface test - */ - it('testGetDefValue006', 0, function () { - mPref.clearSync(); - expect(-1).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, -1)); - expect(1.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 1.0)); - expect(10000).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 10000)); - expect(true).assertEqual(mPref.getSync(KEY_TEST_BOOLEAN_ELEMENT, true)); - expect('defaultValue').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultValue")); - }) - - /** - * @tc.name put float sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0050 - * @tc.desc put float sync interface test - */ - it('testGetFloat007', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_FLOAT_ELEMENT, 3.0); - expect(3.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 0.0)); - expect(0.0).assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, 0.0)); - }) - - /** - * @tc.name put int sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0060 - * @tc.desc put int sync interface test - */ - it('testGetInt008', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_INT_ELEMENT, 3); - expect(3).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0.0)); - }) - - /** - * @tc.name put long sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0070 - * @tc.desc put long sync interface test - */ - it('testGetLong009', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_LONG_ELEMENT, 3); - expect(3).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - expect(0).assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, 0)); - }) - - /** - * @tc.name put String & int sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0080 - * @tc.desc put String & int sync interface test - */ - it('testGetString10', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "test"); - mPref.putSync(KEY_TEST_INT_ELEMENT, 3); - mPref.flushSync(); - expect('test').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - expect('defaultvalue').assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, "defaultvalue")); - }) - - /** - * @tc.name put boolean sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0090 - * @tc.desc put boolean sync interface test - */ - it('testPutBoolean012', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_BOOLEAN_ELEMENT, true); - expect(true).assertEqual(mPref.getSync(KEY_TEST_BOOLEAN_ELEMENT, false)); - mPref.flushSync(); - expect(true).assertEqual(mPref.getSync(KEY_TEST_BOOLEAN_ELEMENT, false)); - }) - - /** - * @tc.name put float sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0100 - * @tc.desc put float sync interface test - */ - it('testPutFloat013', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_FLOAT_ELEMENT, 4.0); - expect(4.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 0.0)); - mPref.flushSync(); - expect(4.0).assertEqual(mPref.getSync(KEY_TEST_FLOAT_ELEMENT, 0.0)); - }) - - /** - * @tc.name put int sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0110 - * @tc.desc put int sync interface test - */ - it('testPutInt014', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_INT_ELEMENT, 4); - expect(4).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0)); - mPref.flushSync(); - expect(4).assertEqual(mPref.getSync(KEY_TEST_INT_ELEMENT, 0)); - }) - - /** - * @tc.name put long sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0120 - * @tc.desc put long sync interface test - */ - it('testPutLong015', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_LONG_ELEMENT, 4); - expect(4).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - mPref.flushSync(); - expect(4).assertEqual(mPref.getSync(KEY_TEST_LONG_ELEMENT, 0)); - }) - - /** - * @tc.name put String sync interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0130 - * @tc.desc put String sync interface test - */ - it('testPutString016', 0, function () { - mPref.clearSync(); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "abc"); - mPref.putSync(KEY_TEST_STRING_ELEMENT, ''); - expect('').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - mPref.flushSync(); - expect('').assertEqual(mPref.getSync(KEY_TEST_STRING_ELEMENT, "defaultvalue")); - }) - - /** - * @tc.name put interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0140 - * @tc.desc put interface test - */ - it('testRegisterObserver001', 0, function () { - mPref.clearSync(); - var observer = function (key) { - expect('abcd').assertEqual(key); - }; - mPref.on('change', observer); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "abcd"); - }) - - /** - * @tc.name repeat on interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0150 - * @tc.desc repeat on interface test - */ - it('testRegisterObserver002', 0, function () { - mPref.clearSync(); - var observer = function (key) { - console.info('testRegisterObserver001 key' + key); - expect('abc').assertEqual(key); - }; - mPref.on('change', observer); - mPref.on('change', observer); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "abc"); - }) - - /** - * @tc.name off interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0160 - * @tc.desc off interface test - */ - it('testUnRegisterObserver001', 0, function () { - var observer = function (key) { - console.info('testUnRegisterObserver001 key' + key); - expect('').assertEqual(key); - }; - mPref.on('change', observer); - mPref.off('change', observer); - mPref.putSync(KEY_TEST_STRING_ELEMENT, "abc"); - }) - - /** - * @tc.name test putSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0170 - * @tc.desc test put interface input parameter key exceed 80byte. - */ - it('testputSyncIllegal001', 0, function () { - let illegalKey = "1"; - illegalKey = illegalKey.repeat(81); - try { - mPref.putSync(illegalKey, "123456"); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - } - }) - - /** - * @tc.name test putSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0180 - * @tc.desc test put interface input parameter key is legal. - */ - it('testputSyncIllegal002', 0, function () { - let legalKey = "1"; - legalKey = legalKey.repeat(80); - try { - mPref.putSync(legalKey, "123456"); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - } - }) - - /** - * @tc.name test putSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0180 - * @tc.desc test put interface input parameter value exceed 8192byte. - */ - it('testputSyncIllegal003', 0, function () { - let illegalValue = "1"; - illegalValue = illegalValue.repeat(8193); - try { - mPref.putSync("test", illegalValue); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - } - }) - - /** - * @tc.name test putSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0180 - * @tc.desc test put interface input parameter value is legal. - */ - it('testputSyncIllegal004', 0, function () { - let legalValue = "1"; - legalValue = legalValue.repeat(8192); - try { - mPref.putSync("test", legalValue); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - } - }) - - /** - * @tc.name test getSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0190 - * @tc.desc test getSync interface input parameter key exceed 80byte. - */ - it('testgetSyncIllegal001', 0, function () { - let illegalkey = "1"; - illegalkey = illegalkey.repeat(81); - try { - mPref.getSync(illegalkey, "defaultValue"); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - } - }) - - /** - * @tc.name test getSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0190 - * @tc.desc test getSync interface input parameter key is legal. - */ - it('testgetSyncIllegal002', 0, function () { - let legalkey = "1"; - legalkey = legalkey.repeat(80); - try { - mPref.getSync(legalkey, "defaultValue"); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - } - }) - - /** - * @tc.name test deleteSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0200 - * @tc.desc test deleteSync interface input parameter key exceed 80byte. - */ - it('testdeleteSyncIllegal001', 0, function () { - let illegalkey = "1"; - illegalkey = illegalkey.repeat(81); - try { - mPref.deleteSync(illegalkey); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - } - }) - - /** - * @tc.name test deleteSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0200 - * @tc.desc test deleteSync interface input parameter key is legal. - */ - it('testdeleteSyncIllegal002', 0, function () { - let legalkey = "1"; - legalkey = legalkey.repeat(80); - try { - mPref.deleteSync(legalkey); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - } - }) - - /** - * @tc.name test hasSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0210 - * @tc.desc test hasSync interface input parameter key exceed 80byte. - */ - it('testhasSyncIllegal001', 0, function () { - let illegalkey = "1"; - illegalkey = illegalkey.repeat(81); - try { - mPref.hasSync(illegalkey); - expect(false).assertTrue(); - } catch (err) { - console.log("try catch err =" + err); - } - }) - - /** - * @tc.name test hasSync interface - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_Sync_0210 - * @tc.desc test hasSync interface input parameter key is legal. - */ - it('testhasSyncIllegal002', 0, function () { - let legalkey = "1"; - legalkey = legalkey.repeat(80); - try { - mPref.hasSync(legalkey); - } catch (err) { - console.log("try catch err =" + err); - expect(false).assertTrue(); - } - }) -}) diff --git a/preferences/test/js/unittest/src/SystemStorageJsunit.test.js b/preferences/test/js/unittest/src/SystemStorageJsunit.test.js deleted file mode 100644 index c252b4bb..00000000 --- a/preferences/test/js/unittest/src/SystemStorageJsunit.test.js +++ /dev/null @@ -1,514 +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. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import storage from '@system.storage'; - -const TAG = '[SYSTEM_STORAGE_JSKITS_TEST]' -describe('systemStorageTest', function () { - beforeAll(function () { - console.info(TAG + 'beforeAll') - }) - - afterEach(async function (done) { - console.info(TAG + 'afterEach') - let promise = storage.clear({ - success: function () { - expect(true).assertTrue(); - done(); - }, - fail: function (data, errCode) { - expect(false).assertTrue(); - done(); - } - }); - await promise; - done(); - }) - - /** - * @tc.name testSet001 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Set_0001 - * @tc.desc set and can get correct value in success callback, finally get complete callback - */ - it('testSet001', 0, async function (done) { - console.log(TAG + '************* testSet001 start *************'); - let completeRet = false; - let successRet = false; - let promise1 = storage.set({ - key: 'storageKey', - value: 'testVal', - success: async function () { - successRet = true; - await expect(successRet).assertTrue(); - }, - complete: async function () { - completeRet = true; - await expect(completeRet).assertTrue(); - } - }); - await promise1; - let promise2 = storage.get({ - key: 'storageKey', - success: async function (data) { - await expect(data).assertEqual('testVal'); - } - }) - await promise2; - - await expect(successRet).assertTrue(); - await expect(completeRet).assertTrue(); - done(); - - console.log(TAG + '************* testSet001 end *************'); - }) - - /** - * @tc.name testSet002 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Set_0002 - * @tc.desc set null key can receive fail callback - */ - it('testSet002', 0, async function (done) { - console.log(TAG + '************* testSet002 start *************'); - let testData = undefined; - let testErrCode = undefined; - let compelteRet = false; - let promise = storage.set({ - key: '', - value: 'testValue', - success: async function () { - await expect(false).assertTrue(); - }, - fail: async function (data, errCode) { - testData = data; - testErrCode = errCode; - }, - complete: async function () { - compelteRet = true; - await expect(compelteRet).assertTrue(); - } - }) - await promise; - await expect("The key string is null or empty.").assertEqual(testData); - await expect(-1006).assertEqual(testErrCode); - await expect(compelteRet).assertTrue(); - - done(); - - console.log(TAG + '************* testSet002 end *************'); - }) - - /** - * @tc.name testSet003 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Set_0003 - * @tc.desc set key which size over 32 bytes and can receive fail callback - */ - it('testSet003', 0, async function (done) { - console.log(TAG + '************* testSet003 start *************'); - let testData = undefined; - let testErrCode = undefined; - let compelteRet = false; - let promise = storage.set({ - key: 'x'.repeat(33), - value: 'testValue', - success: async function () { - await expect(false).assertTrue(); - }, - fail: async function (data, errCode) { - testData = data; - testErrCode = errCode; - }, - complete: async function () { - compelteRet = true; - await expect(compelteRet).assertTrue(); - } - }) - await promise; - await expect("The key string length should shorter than 32.").assertEqual(testData); - await expect(-1016).assertEqual(testErrCode); - await expect(compelteRet).assertTrue(); - - done(); - - console.log(TAG + '************* testSet003 end *************'); - }) - - - /** - * @tc.name testSet004 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Set_0004 - * @tc.desc set value which size over 128 bytes and can receive fail callback - */ - it('testSet004', 0, async function (done) { - console.log(TAG + '************* testSet004 start *************'); - let testData = undefined; - let testErrCode = undefined; - let compelteRet = false; - let promise = storage.set({ - key: 'testKey', - value: 'x'.repeat(129), - success: async function () { - await expect(false).assertTrue(); - }, - fail: async function (data, errCode) { - testData = data; - testErrCode = errCode; - }, - complete: async function () { - compelteRet = true; - } - }) - await promise; - await expect("The value string length should shorter than 128.").assertEqual(testData); - await expect(-1017).assertEqual(testErrCode); - await expect(compelteRet).assertTrue(); - - done(); - - console.log(TAG + '************* testSet004 end *************'); - }) - - /** - * @tc.name testGet001 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Get_0001 - * @tc.desc set and can get correct value in success callback, finally receive a get complete callback - */ - it('testGet001', 0, async function (done) { - console.log(TAG + '************* testGet001 start *************'); - let completeRet = false; - let promise1 = storage.set({ - key: 'storageKey', - value: 'storageVal', - success: async function () { - await expect(true).assertTrue(); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - }, - }); - await promise1; - let promise2 = storage.get({ - key: 'storageKey', - success: async function (data) { - await expect('storageVal').assertEqual(data); - }, - complete: async function () { - completeRet = true; - await expect(completeRet).assertTrue(); - } - }); - await promise2; - await expect(completeRet).assertTrue(); - - done(); - - console.log(TAG + '************* testGet001 end *************'); - }) - - /* - * @tc.name testGet002 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Get_0002 - * @tc.desc get value without set any value and can get default in success callback - */ - it('testGet002', 0, async function (done) { - console.log(TAG + '************* testGet002 start *************'); - let completeRet = false; - let promise = storage.get({ - key: 'storageKey', - default: '123', - success: async function (data) { - await expect('123').assertEqual(data); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - }, - complete: async function () { - completeRet = true; - await expect(completeRet).assertTrue(); - } - }) - await promise; - await expect(completeRet).assertTrue(); - - done(); - - console.log(TAG + '************* testGet002 end *************'); - }) - - - /* - * @tc.name testGet003 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Get_0003 - * @tc.desc get default size over 128 and can receive fail callback - */ - it('testGet003', 0, async function (done) { - console.log(TAG + '************* testGet003 start *************'); - let testVal = undefined; - let testData = undefined; - let testErrCode = undefined; - let completeRet = false; - let failRet = false; - let promise = storage.get({ - key: 'storageKey', - default: 'x'.repeat(129), - success: async function (data) { - testVal = data; - }, - fail: async function (data, errCode) { - testErrCode = errCode; - testData = data; - failRet = true; - }, - complete: async function () { - completeRet = true; - await expect(completeRet).assertTrue(); - } - }) - await promise; - expect(failRet).assertTrue(); - expect(completeRet).assertTrue(); - expect(-1018).assertEqual(testErrCode); - expect('The default string length should shorter than 128.').assertEqual(testData); - expect(testVal == undefined).assertTrue(); - - done(); - - console.log(TAG + '************* testGet003 end *************'); - }) - - /* - * @tc.name testGet004 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Get_0004 - * @tc.desc get null key and can return default value - */ - it('testGet004', 0, async function (done) { - console.log(TAG + '************* testGet004 start *************'); - let testVal = undefined; - let completeRet = false; - let promise = storage.get({ - key: '', - default: 'storageVal', - success: async function (data) { - await expect(data).assertEqual('storageVal'); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - }, - complete: async function () { - completeRet = true; - await expect(completeRet).assertTrue(); - } - }) - await promise; - await expect(completeRet).assertTrue(); - - done(); - - console.log(TAG + '************* testGet004 end *************'); - }) - - /* - * @tc.name testDelete001 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Delete_0001 - * @tc.desc delete value and can not get value - */ - it('testDelete001', 0, async function (done) { - console.log(TAG + '************* testDelete001 start *************'); - let completeRet = false; - let successRet = false; - let promise1 = storage.set({ - key: 'storageKey', - value: 'storageVal', - success: async function () { - await expect(true).assertTrue(); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - }, - }) - await promise1; - let promise2 = storage.delete({ - key: "storageKey", - success: async function () { - successRet = true; - await expect(successRet).assertTrue(); - }, - complete: async function () { - completeRet = true; - await expect(completeRet).assertTrue(); - } - }); - await promise2; - let promise3 = storage.get({ - key: 'storageKey', - default: 'testVal', - success: async function (data) { - await expect(data).assertEqual('testVal'); - } - }) - await promise3; - await expect(completeRet).assertTrue(); - await expect(successRet).assertTrue(); - - done(); - - console.log(TAG + '************* testDelete001 end *************'); - }) - - /* - * @tc.name testDelete002 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Delete_0002 - * @tc.desc delete null key and can get fail callback - */ - it('testDelete002', 0, async function (done) { - console.log(TAG + '************* testDelete002 start *************'); - let testData = undefined; - let testErrCode = undefined; - let completeRet = false; - let failRet = false; - let promise1 = storage.set({ - key: 'storageKey', - value: 'storageVal', - success: async function () { - await expect(true).assertTrue(); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - }, - }) - await promise1; - let promise2 = storage.delete({ - key: '', - success: async function () { - await expect(false).assertTrue(); - }, - fail: async function (data, err) { - testErrCode = err; - testData = data; - failRet = true; - }, - complete: async function () { - completeRet = true; - await expect(completeRet).assertTrue(); - } - }) - await promise2; - await expect(completeRet).assertTrue(); - await expect("The key string is null or empty.").assertEqual(testData); - await expect(-1006).assertEqual(testErrCode); - await expect(failRet).assertTrue(); - - done(); - - console.log(TAG + '************* testDelete002 end *************'); - }) - - /* - * @tc.name testDelete003 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Delete_0003 - * @tc.desc delete incorrect key and can get success callback - */ - it('testDelete003', 0, async function (done) { - console.log(TAG + '************* testDelete003 start *************'); - let completeRet = false; - let promise1 = storage.set({ - key: 'storageKey', - value: 'test', - success: async function () { - await expect(true).assertTrue(); - }, - fail: async function () { - await expect(false).assertTrue(); - }, - }); - await promise1; - let promise2 = storage.delete({ - key: '123', - success: async function () { - await expect(true).assertTrue(); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - }, - complete: async function () { - completeRet = true; - expect(completeRet).assertTrue(); - } - }); - await promise2; - let promise3 = storage.get({ - key: 'storageKey', - success: async function (data) { - await expect(data).assertEqual('test'); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - } - }) - await promise3; - await expect(completeRet).assertTrue(); - - done(); - - console.log(TAG + '************* testDelete003 end *************'); - }) - - /* - * @tc.name testClear001 - * @tc.number SUB_DDM_AppDataFWK_SystemStorage_Clear_0001 - * @tc.desc clear and can receive success callback - */ - it('testClear001', 0, async function (done) { - console.log(TAG + '************* testClear001 start *************'); - let successRet = false; - let promise1 = storage.set({ - key: 'storageKey1', - value: 'storageVal1', - success:async function () { - await expect(true).assertTrue(); - }, - fail:async function () { - await expect(false).assertTrue(); - }, - }); - await promise1; - let promise2 = storage.set({ - key: 'storageKey2', - value: 'storageVal2', - success:async function () { - await expect(true).assertTrue(); - }, - fail:async function () { - await expect(false).assertTrue(); - }, - }); - await promise2; - let promise3 = storage.clear({ - success:async function() { - successRet = true; - await expect(successRet).assertTrue(); - }, - fail: async function (data, err) { - await expect(false).assertTrue(); - } - }); - await promise3; - await expect(successRet).assertTrue(); - - done(); - - console.log(TAG + '************* testClear001 end *************'); - }) - -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/V9_PreferencesCallBackJsunit.test.js b/preferences/test/js/unittest/src/V9_PreferencesCallBackJsunit.test.js deleted file mode 100644 index 06d23d65..00000000 --- a/preferences/test/js/unittest/src/V9_PreferencesCallBackJsunit.test.js +++ /dev/null @@ -1,612 +0,0 @@ -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' -import data_preferences from '@ohos.data.preferences' -import featureAbility from '@ohos.ability.featureAbility' - -const NAME = 'v9_test_preferences_callback' -const KEY_TEST_INT_ELEMENT = 'key_test_int' -const KEY_TEST_LONG_ELEMENT = 'key_test_long' -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float' -const KEY_TEST_BOOLEAN_ELEMENT = 'key_test_boolean' -const KEY_TEST_STRING_ELEMENT = 'key_test_string' -const KEY_TEST_NUMBER_ARRAY_ELEMENT = 'key_test_number_array' -const KEY_TEST_STRING_ARRAY_ELEMENT = 'key_test_string_array' -const KEY_TEST_BOOL_ARRAY_ELEMENT = 'key_test_bool_array' -var mPreference = undefined -var context - -describe('preferencesTest', async function () { - beforeAll(async function () { - console.info('beforeAll') - context = featureAbility.getContext() - mPreference = await data_preferences.getPreferences(context, NAME) - }) - - afterAll(async function () { - console.info('afterAll') - await data_preferences.deletePreferences(context, NAME) - }) - - /** - * @tc.name has、delete、get、flush String callback interface test - * @tc.number SUB_DDM_AppDataFWK_JSPreferences_CallBack_0120 - * @tc.desc flush String callback interface test - */ - - it('testPreferencesCallback001', 0, function (done) { - console.log("testPreferencesCallback001 begin.") - try{ - mPreference.clear(function (err, val) { - if(err){ - console.log("clear err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - mPreference.put(KEY_TEST_STRING_ELEMENT, 'abc', function (err, ret) { - if(err){ - console.log("put err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - mPreference.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, pre) { - if(err){ - console.log("get err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - expect('abc').assertEqual(pre) - mPreference.flush(function (err, val) { - if(err){ - console.log("flush err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - data_preferences.removePreferencesFromCache(context, NAME,(err)=>{ - if(err){ - console.log("removePreferencesFromCache err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - mPreference.get(KEY_TEST_STRING_ELEMENT, "defaultvalue", function (err, pre2) { - if(err){ - console.log("get err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - expect('abc').assertEqual(pre2) - done() - console.log("testPreferencesCallback001 end.") - }) - }) - }) - }) - }) - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - // get err parsers - it('testPreferencesCallback002', 0, function (done) { - console.log("testPreferencesCallback002 begin.") - try { - mPreference.get(123, function (err, val) { - if (err) { - console.log("get err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - expect(true).assertEqual(val) - }) - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - done() - console.log("testPreferencesCallback002 end.") - } - }) - - // get OK parsers - it('testPreferencesCallback003', 0, function (done) { - console.log("testPreferencesCallback003 begin.") - try { - mPreference.get(KEY_TEST_STRING_ELEMENT, KEY_TEST_INT_ELEMENT, function (err, val) { - if (err) { - console.log("get err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - expect('abc').assertEqual(val) - done() - console.log("testPreferencesCallback003 end.") - }) - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - }) - - // getAll - it('testPreferencesCallback004', 0, function (done) { - console.log("testPreferencesCallback004 begin.") - try { - mPreference.getAll(function (err, val) { - if (err) { - console.log("getAll err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - console.log("getAll val = " + JSON.stringify(val)) - done() - console.log("testPreferencesCallback004 end.") - }) - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - done() - }) - - // has Error parsers - it('testPreferencesCallback005', 0, function (done) { - console.log("testPreferencesCallback005 begin.") - try{ - mPreference.has(123,function (err, val) { - console.log("has err") - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - done() - console.log("testPreferencesCallback005 end.") - } - }) - - // has OK parsers - it('testPreferencesCallback006', 0, function (done) { - console.log("testPreferencesCallback006 begin.") - try{ - mPreference.has(KEY_TEST_STRING_ELEMENT, function (err, val) { - if (err) { - console.log("has err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - expect(true).assertEqual(val) - done() - console.log("testPreferencesCallback006 end.") - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - // put Error parsers - it('testPreferencesCallback007', 0, function (done) { - console.log("testPreferencesCallback007 begin.") - try{ - mPreference.put(123, function (err) { - console.log("put err") - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - done() - console.log("testPreferencesCallback007 end.") - } - }) - - // put OK parsers - it('testPreferencesCallback008', 0, function (done) { - console.log("testPreferencesCallback008 begin.") - try{ - mPreference.put(KEY_TEST_STRING_ELEMENT, KEY_TEST_INT_ELEMENT, function (err) { - if (err) { - console.log("put err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - done() - console.log("testPreferencesCallback008 end.") - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - //delete Error parsers - it('testPreferencesCallback009', 0, function (done) { - console.log("testPreferencesCallback009 begin.") - try{ - mPreference.delete(1233, function(err) { - if (err) { - console.log("delete err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - console.log("delete err") - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - done() - console.log("testPreferencesCallback009 end.") - } - }) - - //delete OK parsers - it('testPreferencesCallback010', 0, function (done) { - console.log("testPreferencesCallback010 begin.") - try{ - mPreference.delete(KEY_TEST_STRING_ELEMENT, function(err) { - if (err) { - console.log("delete err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - done() - console.log("testPreferencesCallback010 end.") - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - // clear - it('testPreferencesCallback011', 0, function (done) { - console.log("testPreferencesCallback011 begin.") - try{ - mPreference.clear(function (err) { - if (err) { - console.log("clear err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - done() - console.log("testPreferencesCallback011 end.") - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - // flush - it('testPreferencesCallback012', 0, function (done) { - console.log("testPreferencesCallback012 begin.") - try{ - mPreference.flush(function (err) { - if (err) { - console.log("flush err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - done() - console.log("testPreferencesCallback012 end.") - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - /** - * @tc.name test put interface - * @tc.desc test put interface input parameter is illegal. - */ - it('testPreferencesPutIllegal0001', 0, async function (done) { - let illegalKey = 123; - let legalValue = "test"; - try { - mPreference.put(illegalKey, legalValue, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.desc test put interface input parameter is illegal. - */ - it('testPreferencesPutIllegal0002', 0, async function (done) { - let illegalKey = true; - let legalValue = "test"; - try { - mPreference.put(illegalKey, legalValue, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.desc test put interface input parameter key exceed 80bytes. - */ - it('testPreferencesPutIllegal0003', 0, async function (done) { - let illegalKey = '1'; - illegalKey = illegalKey.repeat(81); - try { - mPreference.put(illegalKey, "123456", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.desc test put interface input parameter key is legal. - */ - it('testPreferencesPutIllegal0004', 0, async function (done) { - let legalKey = '1'; - legalKey = legalKey.repeat(80); - try { - mPreference.put(legalKey, "123456", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect(false).assertEqual(true); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.desc test put interface input parameter value exceed 8192bytes. - */ - it('testPreferencesPutIllegal0005', 0, async function (done) { - let illegalValue = '1'; - illegalValue = illegalValue.repeat(8193); - try { - mPreference.put("test", illegalValue, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test put interface - * @tc.desc test put interface input parameter value is legal. - */ - it('testPreferencesPutIllegal0006', 0, async function (done) { - let legalValue = '1'; - legalValue = legalValue.repeat(8192); - try { - mPreference.put("test", legalValue, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect(false).assertEqual(true); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.desc test get interface input parameter is illegal. - */ - it('testPreferencesGetIllegal0001', 0, async function (done) { - let illegalKey = true; - try { - mPreference.get(illegalKey, "defaultValue", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.desc test get interface input parameter is illegal. - */ - it('testPreferencesGetIllegal0002', 0, async function (done) { - let illegalKey = 123; - try { - mPreference.get(illegalKey, "defaultValue", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.desc test get interface input parameter key exceed 80bytes. - */ - it('testPreferencesGetIllegal0003', 0, async function (done) { - let illegalKey = "1"; - illegalKey = illegalKey.repeat(81); - try { - mPreference.get(illegalKey, "defaultValue", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test get interface - * @tc.desc test get interface input parameter key is legal. - */ - it('testPreferencesGetIllegal0004', 0, async function (done) { - let legalKey = "1"; - legalKey = legalKey.repeat(80); - try { - mPreference.get(legalKey, "defaultValue", (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect(false).assertEqual(true); - done(); - } - }) - - /** - * @tc.name test delete interface - * @tc.desc test delete interface input parameter is illegal. - */ - it('testPreferencesDeleteIllegal0001', 0, async function (done) { - let illegalKey = 123; - try { - mPreference.delete(illegalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test delete interface - * @tc.desc test delete interface input parameter is illegal. - */ - it('testPreferencesDeleteIllegal0002', 0, async function (done) { - let illegalKey = false; - try { - mPreference.delete(illegalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test delete interface - * @tc.desc test delete interface input parameter key exceed 80bytes. - */ - it('testPreferencesDeleteIllegal0003', 0, async function (done) { - let illegalKey = '1'; - illegalKey = illegalKey.repeat(81); - try { - mPreference.delete(illegalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test delete interface - * @tc.desc test delete interface input parameter key is legal. - */ - it('testPreferencesDeleteIllegal0004', 0, async function (done) { - let legalKey = '1'; - legalKey = legalKey.repeat(80); - try { - mPreference.delete(legalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect(false).assertEqual(true); - done(); - } - }) - - /** - * @tc.name test has interface - * @tc.desc test has interface input parameter is illegal. - */ - it('testPreferencesHasIllegal0001', 0, async function (done) { - let illegalKey = false; - try { - mPreference.has(illegalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test has interface - * @tc.desc test has interface input parameter is illegal. - */ - it('testPreferencesHasIllegal0002', 0, async function (done) { - let illegalKey = 123; - try { - mPreference.has(illegalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test has interface - * @tc.desc test has interface input parameter key exceed 80bytes. - */ - it('testPreferencesHasIllegal0003', 0, async function (done) { - let illegalKey = '1'; - illegalKey = illegalKey.repeat(81); - try { - mPreference.has(illegalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect("401").assertEqual(err.code.toString()); - done(); - } - }) - - /** - * @tc.name test has interface - * @tc.desc test has interface input parameter key is legal. - */ - it('testPreferencesHasIllegal0004', 0, async function (done) { - let legalKey = '1'; - legalKey = legalKey.repeat(80); - try { - mPreference.has(legalKey, (ret) => { - done(); - }); - } catch (err) { - console.log("try catch err =" + err + ", code =" + err.code +", message =" + err.message); - expect(false).assertEqual(true); - done(); - } - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/V9_PreferencesPromiseJsunit.test.js b/preferences/test/js/unittest/src/V9_PreferencesPromiseJsunit.test.js deleted file mode 100644 index 2255be23..00000000 --- a/preferences/test/js/unittest/src/V9_PreferencesPromiseJsunit.test.js +++ /dev/null @@ -1,362 +0,0 @@ -/* -* Copyright (c) 2021 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' -import data_preferences from '@ohos.data.preferences' -import featureAbility from '@ohos.ability.featureAbility' - -const NAME = 'v9_test_preferences_promise' -const KEY_TEST_INT_ELEMENT = 'key_test_int' -const KEY_TEST_LONG_ELEMENT = 'key_test_long' -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float' -const KEY_TEST_BOOLEAN_ELEMENT = 'key_test_boolean' -const KEY_TEST_STRING_ELEMENT = 'key_test_string' -const KEY_TEST_NUMBER_ARRAY_ELEMENT = 'key_test_number_array' -const KEY_TEST_STRING_ARRAY_ELEMENT = 'key_test_string_array' -const KEY_TEST_BOOL_ARRAY_ELEMENT = 'key_test_bool_array' -var mPreference -var context - -describe('_preferencesTest', async function () { - beforeAll(async function () { - console.info('beforeAll') - context = featureAbility.getContext() - mPreference = await data_preferences.getPreferences(context, NAME) - }) - - afterAll(async function () { - console.info('afterAll') - await data_preferences.deletePreferences(context, NAME) - }) - - beforeEach(async function () { - console.info('beforeEach') - await mPreference.clear(); - await mPreference.flush(); - }) - - it('testPreferencesPromise001', 0, function (done) { - console.log("testPreferencesPromise001 begin.") - try{ - if(mPreference== undefined) { - console.log("mPreference undefined") - expect(false).assertTrue() - } - mPreference.clear().then(()=>{ - mPreference.put(KEY_TEST_STRING_ELEMENT, '123').then((ret)=>{ - mPreference.get(KEY_TEST_STRING_ELEMENT, "defaultvalue").then((pre)=>{ - expect('123').assertEqual(pre) - mPreference.flush().then(()=>{ - data_preferences.removePreferencesFromCache(context, NAME).then(()=>{ - mPreference.get(KEY_TEST_STRING_ELEMENT, "defaultvalue").then((pre2)=>{ - expect('123').assertEqual(pre2) - done() - console.log("testPreferencesPromise001 end.") - }).catch((err) => { - console.log("get err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - }).catch((err) => { - console.log("removePreferencesFromCache err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - }).catch((err) => { - console.log("flush err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - }).catch((err) => { - console.log("get err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - }).catch((err) => { - console.log("put err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - }).catch((err) => { - console.log("clear err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - //get error parsers - it('testPreferencesPromise002', 0, function (done) { - console.log("testPreferencesPromise002 begin.") - try{ - mPreference.get(1233).then((ret)=>{ - console.log("get err") - expect(false).assertTrue() - }).catch((err) => { - console.log("get err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - done() - console.log("testPreferencesPromise002 end.") - } - }) - - //get OK parsers - it('testPreferencesPromise003', 0, async function (done) { - console.log("testPreferencesPromise003 begin.") - try{ - await mPreference.put(KEY_TEST_STRING_ELEMENT, '123'); - mPreference.get(KEY_TEST_STRING_ELEMENT, KEY_TEST_INT_ELEMENT).then((ret) => { - done() - expect('123').assertEqual(ret) - console.log("testPreferencesPromise003 end.") - }).catch((err) => { - console.log("get err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - //getAll - it('testPreferencesPromise004', 0, function (done) { - console.log("testPreferencesPromise004 begin.") - try { - mPreference.getAll().then((ret) => { - done() - console.log("testPreferencesPromise004 end.") - }).catch((err) => { - console.log("getAll err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - }) - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - }) - - //has error parsers - it('testPreferencesPromise005', 0, function (done) { - console.log("testPreferencesPromise005 begin.") - try{ - mPreference.has(123).then((val)=>{ - console.log("has err") - expect(false).assertTrue() - }).catch((err) => { - console.log("has err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - done() - console.log("testPreferencesPromise005 end.") - } - }) - - //has OK parsers - it('testPreferencesPromise006', 0, function (done) { - console.log("testPreferencesPromise006 begin.") - try{ - mPreference.has(KEY_TEST_STRING_ELEMENT).then((val)=>{ - done() - console.log("testPreferencesPromise006 end.") - }).catch((err) => { - console.log("has err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - //put error parsers - it('testPreferencesPromise007', 0, function (done) { - console.log("testPreferencesPromise007 begin.") - try{ - mPreference.put(1233).then(()=>{ - console.log("put err") - expect(false).assertTrue() - }).catch((err) => { - console.log("put err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - done() - console.log("testPreferencesPromise007 end.") - } - }) - - //put OK parsers - it('testPreferencesPromise008', 0, function (done) { - console.log("testPreferencesPromise008 begin.") - try{ - mPreference.put(KEY_TEST_STRING_ELEMENT, KEY_TEST_INT_ELEMENT).then(()=>{ - done() - console.log("testPreferencesPromise008 end.") - }).catch((err) => { - console.log("put err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - //delete error parsers - it('testPreferencesPromise009', 0, function (done) { - console.log("testPreferencesPromise009 begin.") - try{ - mPreference.delete(1233).then(()=>{ - console.log("delete err") - expect(false).assertTrue() - }).catch((err) => { - console.log("delete err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - done() - console.log("testPreferencesPromise009 end.") - } - }) - - //delete OK parsers - it('testPreferencesPromise010', 0, function (done) { - console.log("testPreferencesPromise010 begin.") - try{ - mPreference.delete(KEY_TEST_STRING_ELEMENT).then(()=>{ - done() - console.log("testPreferencesPromise005 end.") - }).catch((err) => { - console.log("delete err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - //clear - it('testPreferencesPromise011', 0, function (done) { - console.log("testPreferencesPromise011 begin.") - try{ - mPreference.clear().then(()=>{ - done() - console.log("testPreferencesPromise011 end.") - }).catch((err) => { - console.log("clear err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - }) - } catch(err) { - console.log("trycatch err =" + err + ", code =" + err.code +", message =" + err.message) - expect(false).assertTrue() - } - }) - - //flush OK parsers - it('testPreferencesPromise012', 0, function (done) { - console.log("testPreferencesPromise012 begin.") - try { - mPreference.flush().then(() => { - done() - console.log("testPreferencesPromise012 end.") - }).catch((err) => { - console.log("flush err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - }) - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - }) - - //on OK parsers - it('testPreferencesPromise014', 0, async function (done) { - console.log("testPreferencesPromise014 begin.") - await mPreference.clear(); - try { - var observer = function (key) { - console.info('testPreferencesPromise014 key' + key); - done(); - expect(KEY_TEST_STRING_ELEMENT).assertEqual(key); - }; - mPreference.on('change', observer); - await mPreference.put(KEY_TEST_STRING_ELEMENT, "abc"); - await mPreference.flush(); - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } finally { - mPreference.off('change', observer); - } - }) - - //on err parsers - it('testPreferencesPromise015', 0, async function (done) { - console.log("testPreferencesPromise015 begin.") - await mPreference.clear(); - try { - var observer = function (key) { - console.info('testPreferencesPromise015 key' + key); - expect(KEY_TEST_STRING_ELEMENT).assertEqual(key); - }; - mPreference.on('sschange', observer); - expect(false).assertTrue() - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - done(); - } - }) - - //off OK parsers - it('testPreferencesPromise016', 0, async function (done) { - console.log("testPreferencesPromise016 begin.") - try { - var observer = function (key) { - console.info('testPreferencesPromise016 key' + key); - expect(false).assertTrue() - }; - mPreference.on('change', observer); - mPreference.off('change', observer); - await mPreference.put(KEY_TEST_STRING_ELEMENT, "abb"); - await mPreference.flush(); - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - expect(false).assertTrue() - } - done(); - }) - - //off err parsers - it('testPreferencesPromise017', 0, async function (done) { - console.log("testPreferencesPromise017 begin.") - try { - var observer = function (key) { - console.info('testPreferencesPromise017 key' + key); - expect(KEY_TEST_STRING_ELEMENT).assertEqual(key); - }; - mPreference.on('change', observer); - mPreference.off('sschange', observer); - expect(false).assertTrue() - } catch (err) { - console.log("trycatch err =" + err + ", code =" + err.code + ", message =" + err.message) - done(); - } - }) -}) \ No newline at end of file diff --git a/preferences/test/js/unittest/src/config.json b/preferences/test/js/unittest/src/config.json deleted file mode 100644 index e1b1bc28..00000000 --- a/preferences/test/js/unittest/src/config.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5 - } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.myapplication", - "name": ".MyApplication", - "deviceType": [ - "tablet", - "default", - "phone" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "visible": true, - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "MyApplication", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } -} diff --git a/preferences/test/native/unittest/preferences_test.cpp b/preferences/test/native/unittest/preferences_test.cpp index 8f9d3e26..7fcabe30 100644 --- a/preferences/test/native/unittest/preferences_test.cpp +++ b/preferences/test/native/unittest/preferences_test.cpp @@ -605,10 +605,14 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_019, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_020, TestSize.Level1) { - pref->PutDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT, (std::numeric_limits::max)()); - pref->Flush(); - - double ret = pref->GetDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT); + int errCode; + std::shared_ptr pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + pref1->PutDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT, (std::numeric_limits::max)()); + pref1->Flush(); + PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); + pref1.reset(); + pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + double ret = pref1->GetDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT); EXPECT_EQ(ret, (std::numeric_limits::max)()); } @@ -621,14 +625,20 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_020, TestSize.Level1) */ HWTEST_F(PreferencesTest, NativePreferencesTest_021, TestSize.Level1) { - pref->PutString(PreferencesTest::LONG_KEY, "test"); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->Flush(); + int errCode; + auto pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + pref1->PutString(PreferencesTest::LONG_KEY, "test"); + pref1->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1 test2"); + pref1->Flush(); - std::string ret = pref->GetString(PreferencesTest::LONG_KEY); - EXPECT_EQ(ret, "test"); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT); + PreferencesHelper::RemovePreferencesFromCache("/data/test/test1"); + pref1.reset(); + pref1 = PreferencesHelper::GetPreferences("/data/test/test1", errCode); + + std::string ret = pref1->GetString(PreferencesTest::LONG_KEY); EXPECT_EQ(ret, "test"); + ret = pref1->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT); + EXPECT_EQ(ret, "test1 test2"); } /** diff --git a/preferences/test/native/unittest/preferences_xml_utils_test.cpp b/preferences/test/native/unittest/preferences_xml_utils_test.cpp index 6756c205..011b4ae0 100644 --- a/preferences/test/native/unittest/preferences_xml_utils_test.cpp +++ b/preferences/test/native/unittest/preferences_xml_utils_test.cpp @@ -224,10 +224,10 @@ HWTEST_F(PreferencesXmlUtilsTest, ArrayNodeElementTest_003, TestSize.Level1) elemChild.key_ = "boolKey"; elemChild.tag_ = std::string("bool"); - elemChild.value_ = std::to_string(false); + elemChild.value_ = "false"; elem.children_.push_back(elemChild); - elemChild.value_ = std::to_string(true); + elemChild.value_ = "true"; elem.children_.push_back(elemChild); settings.push_back(elem); std::vector inputBoolArray = { false, true }; diff --git a/relational_store/CMakeLists.txt b/relational_store/CMakeLists.txt index 71f9d3d1..d903d371 100644 --- a/relational_store/CMakeLists.txt +++ b/relational_store/CMakeLists.txt @@ -1,41 +1,38 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(relational_store) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_FLAGS "${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") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl -Wno-deprecated") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wformat=0 -fpermissive") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=deprecated-declarations -Wno-deprecated-declarations") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") set(MOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../mock) set(KV_STORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store) add_definitions(-DNAPI_EXPERIMENTAL) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/src relational_store_src) -#aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataability/src relational_store_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/relationalstore/src relational_store_src) -#aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/rdb/src relational_store_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/src js_common_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataability/src js_dataability_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/relationalstore/src js_relational_store_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/rdb/src js_rdb_store_src) + aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/appdatafwk/src relational_store_src) list(REMOVE_ITEM relational_store_src "${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/appdatafwk/src/general_endian.cpp") -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/dataability/src relational_store_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/dataability/src relational_store_src) + aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb/src relational_store_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_bms_adaptor/src relational_store_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_data_ability_adapter/src relational_store_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_data_share_adapter/src relational_store_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_device_manager_adapter/src relational_store_src) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/appdatafwk/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/dataability/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb_bms_adapter/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb_data_ability_adapter/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb_data_share_adapter/include) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/dataability/src rdb_adapter_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_bms_adaptor/src rdb_adapter_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_data_ability_adapter/src rdb_adapter_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_data_share_adapter/src rdb_adapter_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_device_manager_adapter/src rdb_adapter_src) + include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/include) -#include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataability/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataability/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/relationalstore/include) -#include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/rdb/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/rdb/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/dataability/src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/rdb_device_manager_adapter/include) @@ -47,9 +44,38 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/safwk/native/include) include_directories(${MOCK_DIR}/sqlite/include) include_directories(${MOCK_DIR}/filemanagement/file_api/interfaces/kits) -include(${MOCK_DIR}/include/CMakeLists.txt OPTIONAL) include(${KV_STORE_DIR}/interfaces/CMakeLists.txt OPTIONAL) set(links secure mock adapter distributeddb kvdb) -add_library(relational_store SHARED ${relational_store_src}) -target_link_libraries(relational_store ${links}) \ No newline at end of file +add_library(relational_store SHARED ${relational_store_src} ${rdb_adapter_src}) +target_link_libraries(relational_store ${links}) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb/include) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/appdatafwk/include) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/appdatafwk/include) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb_bms_adapter/include) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb_data_ability_adapter/include) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb_data_share_adapter/include) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/dataability/include) +target_include_directories(relational_store PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb/include) + + +add_library(js_relational_store SHARED ${js_common_src} ${js_relational_store_src}) +target_link_libraries(js_relational_store ${links} relational_store) + +add_library(js_rdb_store SHARED ${js_common_src} ${js_rdb_store_src}) +target_link_libraries(js_rdb_store ${links} relational_store) + +add_library(js_dataability SHARED ${js_common_src} ${js_dataability_src}) +target_link_libraries(js_dataability mock relational_store rdb_data_ability_adapter js_rdb_store) + + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/cloud_data/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/cloud_data/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/rdb/include) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/cloud_data/src cloud_data_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/cloud_data/src cloud_data_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/src cloud_data_src) +add_library(cloud_data SHARED ${cloud_data_src}) +target_link_libraries(cloud_data mock) +target_include_directories(cloud_data PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/cloud_data/include) \ No newline at end of file diff --git a/relational_store/bundle.json b/relational_store/bundle.json index 0eb7194b..967784a4 100644 --- a/relational_store/bundle.json +++ b/relational_store/bundle.json @@ -58,6 +58,7 @@ "hitrace", "huks", "ipc", + "kv_store", "napi", "resource_management", "samgr" @@ -186,4 +187,4 @@ ] } } -} +} \ No newline at end of file diff --git a/relational_store/frameworks/js/napi/common/include/js_utils.h b/relational_store/frameworks/js/napi/common/include/js_utils.h index 0f2f3d86..e39af577 100644 --- a/relational_store/frameworks/js/napi/common/include/js_utils.h +++ b/relational_store/frameworks/js/napi/common/include/js_utils.h @@ -33,12 +33,10 @@ namespace AppDataMgrJsKit { namespace JSUtils { constexpr int OK = 0; constexpr int ERR = -1; -constexpr int32_t DEFAULT_BUF_SIZE = 1024; -// 1 is the margin -constexpr int32_t BUF_CACHE_MARGIN = 4 + 1; -constexpr int32_t ASYNC_RST_SIZE = 2; -constexpr int32_t MAX_VALUE_LENGTH = 8 * 1024; -constexpr int32_t SYNC_RESULT_ELEMNT_NUM = 2; +constexpr uint32_t ASYNC_RST_SIZE = 2; +constexpr uint32_t DEFAULT_VALUE_LENGTH = 1024; +constexpr uint32_t MAX_VALUE_LENGTH = 1024 * 1024 * 8; // the max length of all kand of out string value +constexpr uint32_t SYNC_RESULT_ELEMENT_NUM = 2; struct JsFeatureSpace { const char* spaceName; const char* nameBase64; @@ -87,10 +85,7 @@ const std::optional GetJsFeatureSpace(const std::string &name); napi_value DefineClass(napi_env env, const std::string &spaceName, const std::string &className, const Descriptor &descriptor, napi_callback ctor); napi_value GetClass(napi_env env, const std::string &spaceName, const std::string &className); -std::string Convert2String(napi_env env, napi_value jsStr, bool useDefaultBufSize = true); -std::vector Convert2StrVector(napi_env env, napi_value value); -std::vector Convert2U8Vector(napi_env env, napi_value jsValue); -std::string ConvertAny2String(napi_env env, napi_value jsValue); +std::string Convert2String(napi_env env, napi_value jsStr); int32_t Convert2JSValue(napi_env env, std::string value, napi_value &output); int32_t Convert2JSValue(napi_env env, bool value, napi_value &output); diff --git a/relational_store/frameworks/js/napi/common/src/js_utils.cpp b/relational_store/frameworks/js/napi/common/src/js_utils.cpp index 0657ac44..6551c141 100644 --- a/relational_store/frameworks/js/napi/common/src/js_utils.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_utils.cpp @@ -60,86 +60,13 @@ napi_value JSUtils::GetNamedProperty(napi_env env, napi_value object, const char return jsItem; } -std::string JSUtils::Convert2String(napi_env env, napi_value jsStr, bool useDefaultBufSize) +std::string JSUtils::Convert2String(napi_env env, napi_value jsStr) { - size_t str_buffer_size = 0; - napi_get_value_string_utf8(env, jsStr, nullptr, 0, &str_buffer_size); - str_buffer_size = (useDefaultBufSize && (str_buffer_size > DEFAULT_BUF_SIZE)) - ? (DEFAULT_BUF_SIZE + BUF_CACHE_MARGIN) - : (str_buffer_size + BUF_CACHE_MARGIN); - auto buf = std::make_unique(str_buffer_size); - if (buf == nullptr) { - LOG_ERROR("Convert2String new failed, buf is nullptr"); - return ""; - } - size_t len = 0; - napi_get_value_string_utf8(env, jsStr, buf.get(), str_buffer_size, &len); - buf[len] = 0; - std::string value(buf.get()); + std::string value = ""; // TD: need to check everywhere in use whether empty is work well. + JSUtils::Convert2Value(env, jsStr, value); return value; } -std::vector JSUtils::Convert2StrVector(napi_env env, napi_value value) -{ - uint32_t arrLen = 0; - napi_get_array_length(env, value, &arrLen); - if (arrLen == 0) { - return {}; - } - std::vector result; - for (size_t i = 0; i < arrLen; ++i) { - napi_value element; - napi_get_element(env, value, i, &element); - result.push_back(ConvertAny2String(env, element)); - } - return result; -} - -std::vector JSUtils::Convert2U8Vector(napi_env env, napi_value input_array) -{ - bool isTypedArray = false; - napi_is_typedarray(env, input_array, &isTypedArray); - if (!isTypedArray) { - 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 {}; - } - return std::vector((uint8_t *)data, ((uint8_t *)data) + length); -} - -std::string JSUtils::ConvertAny2String(napi_env env, napi_value jsValue) -{ - napi_valuetype valueType = napi_undefined; - NAPI_CALL_BASE(env, napi_typeof(env, jsValue, &valueType), "napi_typeof failed"); - if (valueType == napi_string) { - return JSUtils::Convert2String(env, jsValue, false); - } else if (valueType == napi_number) { - double valueNumber; - napi_get_value_double(env, jsValue, &valueNumber); - return std::to_string(valueNumber); - } else if (valueType == napi_boolean) { - bool valueBool = false; - napi_get_value_bool(env, jsValue, &valueBool); - return std::to_string(valueBool); - } else if (valueType == napi_null) { - return ""; - } else if (valueType == napi_object) { - std::vector bytes = JSUtils::Convert2U8Vector(env, jsValue); - std::string ret(bytes.begin(), bytes.end()); - return ret; - } - - return "invalid type"; -} - int32_t JSUtils::Convert2ValueExt(napi_env env, napi_value jsValue, uint32_t &output) { napi_valuetype type; @@ -151,7 +78,7 @@ int32_t JSUtils::Convert2ValueExt(napi_env env, napi_value jsValue, uint32_t &ou status = napi_get_value_uint32(env, jsValue, &output); if (status != napi_ok) { - LOG_DEBUG("Convert2Value napi_get_value_uint32 failed, status = %{public}d", status); + LOG_DEBUG("napi_get_value_uint32 failed, status = %{public}d", status); return status; } return status; @@ -168,7 +95,7 @@ int32_t JSUtils::Convert2ValueExt(napi_env env, napi_value jsValue, int32_t &out status = napi_get_value_int32(env, jsValue, &output); if (status != napi_ok) { - LOG_DEBUG("Convert2Value napi_get_value_int32 failed, status = %{public}d", status); + LOG_DEBUG("napi_get_value_int32 failed, status = %{public}d", status); return status; } return status; @@ -186,7 +113,7 @@ int32_t JSUtils::Convert2Value(napi_env env, napi_value jsValue, bool &output) bool bValue = false; status = napi_get_value_bool(env, jsValue, &bValue); if (status != napi_ok) { - LOG_ERROR("Convert2Value napi_get_value_bool failed, status = %{public}d", status); + LOG_ERROR("napi_get_value_bool failed, status = %{public}d", status); return status; } output = bValue; @@ -204,7 +131,7 @@ int32_t JSUtils::Convert2ValueExt(napi_env env, napi_value jsValue, int64_t &out status = napi_get_value_int64(env, jsValue, &output); if (status != napi_ok) { - LOG_DEBUG("Convert2Value napi_get_value_int32 failed, status = %{public}d", status); + LOG_DEBUG("napi_get_value_int32 failed, status = %{public}d", status); return status; } return status; @@ -222,7 +149,7 @@ int32_t JSUtils::Convert2Value(napi_env env, napi_value jsValue, double &output) double number = 0.0; status = napi_get_value_double(env, jsValue, &number); if (status != napi_ok) { - LOG_DEBUG("Convert2Value napi_get_value_double failed, status = %{public}d", status); + LOG_DEBUG("napi_get_value_double failed, status = %{public}d", status); return status; } output = number; @@ -243,24 +170,26 @@ int32_t JSUtils::Convert2Value(napi_env env, napi_value jsValue, std::string &ou return napi_invalid_arg; } - size_t length = MAX_VALUE_LENGTH; - napi_get_value_string_utf8(env, jsValue, nullptr, 0, &length); - length = length + 1; // add the null-terminated byte - length = length < MAX_VALUE_LENGTH ? MAX_VALUE_LENGTH - 1 : length; - /* array init to zero */ - std::unique_ptr str = std::make_unique(length + 1); - if (str == nullptr) { - LOG_ERROR("Convert2Value new failed, str is nullptr"); - return napi_generic_failure; - } + size_t buffSize = 0; + napi_get_value_string_utf8(env, jsValue, nullptr, 0, &buffSize); - size_t valueSize = 0; - status = napi_get_value_string_utf8(env, jsValue, str.get(), length, &valueSize); + // cut down with 0 if more than MAX_VALUE_LENGTH + if (buffSize >= JSUtils::MAX_VALUE_LENGTH - 1) { + buffSize = JSUtils::MAX_VALUE_LENGTH - 1; + } + char *buffer = (char *)malloc((buffSize + 1) * sizeof(char)); + if (buffer == nullptr) { + LOG_ERROR("buffer data is nullptr."); + return napi_invalid_arg; + } + status = napi_get_value_string_utf8(env, jsValue, buffer, buffSize + 1, &buffSize); if (status != napi_ok) { - LOG_ERROR("Convert2Value napi_get_value_string_utf8 failed, status = %{public}d", status); + LOG_ERROR("napi_get_value_string_utf8 failed, status = %{public}d", status); + free(buffer); return status; } - output = std::string(str.get()); + output = std::string(buffer); + free(buffer); return status; } @@ -297,7 +226,13 @@ int32_t JSUtils::Convert2Value(napi_env env, napi_value jsValue, std::monostate value = std::monostate(); return napi_ok; } - LOG_DEBUG("Convert2Value jsValue is not null"); + napi_get_undefined(env, &tempValue); + napi_strict_equals(env, jsValue, tempValue, &equal); + if (equal) { + value = std::monostate(); + return napi_ok; + } + LOG_DEBUG("jsValue is not undefined or null"); return napi_invalid_arg; } @@ -462,7 +397,7 @@ napi_value JSUtils::Convert2JSValue(napi_env env, const std::map value); static std::shared_ptr GetNativePredicates( - const napi_env &env, const napi_value &arg); + const napi_env env, const napi_value arg); static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); DataAbilityPredicatesProxy(); @@ -94,6 +94,6 @@ __attribute__((visibility("default"))) napi_value NAPI_OHOS_Data_DataAbilityJsKi __attribute__((visibility("default"))) OHOS::NativeRdb::DataAbilityPredicates * NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject( - const napi_env &env, const napi_value &arg); + const napi_env env, const napi_value arg); EXTERN_C_END #endif // DATAABILITY_JSKIT_NAPI_DATA_ABILITY_PREDICATES_H \ No newline at end of file diff --git a/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp b/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp index d0138cf0..92e5b728 100644 --- a/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp +++ b/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp @@ -144,7 +144,7 @@ napi_value DataAbilityPredicatesProxy::NewInstance( } std::shared_ptr DataAbilityPredicatesProxy::GetNativePredicates( - const napi_env &env, const napi_value &arg) + const napi_env env, const napi_value arg) { if (arg == nullptr) { LOG_ERROR("DataAbilityPredicatesProxy arg is null."); @@ -190,8 +190,10 @@ napi_value DataAbilityPredicatesProxy::EqualTo(napi_env env, napi_callback_info napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::EqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->EqualTo(field, value); @@ -205,8 +207,10 @@ napi_value DataAbilityPredicatesProxy::NotEqualTo(napi_env env, napi_callback_in napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::NotEqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->NotEqualTo(field, value); @@ -260,8 +264,10 @@ napi_value DataAbilityPredicatesProxy::Contains(napi_env env, napi_callback_info napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::Contains Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + std::string value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->Contains(field, value); @@ -275,8 +281,10 @@ napi_value DataAbilityPredicatesProxy::BeginsWith(napi_env env, napi_callback_in napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::BeginsWith Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + std::string value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->BeginsWith(field, value); @@ -290,8 +298,10 @@ napi_value DataAbilityPredicatesProxy::EndsWith(napi_env env, napi_callback_info napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::EndsWith Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + std::string value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->EndsWith(field, value); @@ -305,7 +315,8 @@ napi_value DataAbilityPredicatesProxy::IsNull(napi_env env, napi_callback_info i napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::IsNull Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->IsNull(field); @@ -319,7 +330,8 @@ napi_value DataAbilityPredicatesProxy::IsNotNull(napi_env env, napi_callback_inf napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::IsNotNull Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->IsNotNull(field); @@ -333,8 +345,10 @@ napi_value DataAbilityPredicatesProxy::Like(napi_env env, napi_callback_info inf napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::Like Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + std::string value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->Like(field, value); @@ -348,8 +362,10 @@ napi_value DataAbilityPredicatesProxy::Glob(napi_env env, napi_callback_info inf napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::Glob Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + std::string value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->Glob(field, value); @@ -360,12 +376,19 @@ napi_value DataAbilityPredicatesProxy::Between(napi_env env, napi_callback_info { napi_value thiz; size_t argc = 3; + // 3 represents the number of parameters napi_value args[3] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::Between Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string low = JSUtils::ConvertAny2String(env, args[1]); - std::string high = JSUtils::ConvertAny2String(env, args[2]); + std::string field; + // args[0] represents the first parameter + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject low; + // args[1] represents the second parameter + JSUtils::Convert2Value(env, args[1], low); + ValueObject high; + // args[2] represents the third parameter + JSUtils::Convert2Value(env, args[2], high); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->Between(field, low, high); @@ -376,12 +399,19 @@ napi_value DataAbilityPredicatesProxy::NotBetween(napi_env env, napi_callback_in { napi_value thiz; size_t argc = 3; + // 3 represents the number of parameters napi_value args[3] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::NotBetween Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string low = JSUtils::ConvertAny2String(env, args[1]); - std::string high = JSUtils::ConvertAny2String(env, args[2]); + std::string field; + // args[0] represents the first parameter + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject low; + // args[1] represents the second parameter + JSUtils::Convert2Value(env, args[1], low); + ValueObject high; + // args[2] represents the third parameter + JSUtils::Convert2Value(env, args[2], high); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->NotBetween(field, low, high); @@ -395,8 +425,10 @@ napi_value DataAbilityPredicatesProxy::GreaterThan(napi_env env, napi_callback_i napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::GreaterThan Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->GreaterThan(field, value); @@ -410,8 +442,10 @@ napi_value DataAbilityPredicatesProxy::LessThan(napi_env env, napi_callback_info napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::LessThan Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->LessThan(field, value); @@ -425,8 +459,10 @@ napi_value DataAbilityPredicatesProxy::GreaterThanOrEqualTo(napi_env env, napi_c napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::GreaterThanOrEqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->GreaterThanOrEqualTo(field, value); @@ -440,8 +476,10 @@ napi_value DataAbilityPredicatesProxy::LessThanOrEqualTo(napi_env env, napi_call napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::LessThanOrEqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + ValueObject value; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[1], value) == napi_ok, "the value is invalid"); auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->LessThanOrEqualTo(field, value); @@ -455,7 +493,10 @@ napi_value DataAbilityPredicatesProxy::OrderByAsc(napi_env env, napi_callback_in napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::OrderByAsc Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); + + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->OrderByAsc(field); @@ -469,7 +510,10 @@ napi_value DataAbilityPredicatesProxy::OrderByDesc(napi_env env, napi_callback_i napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::OrderByDesc Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); + + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->OrderByDesc(field); @@ -493,8 +537,10 @@ napi_value DataAbilityPredicatesProxy::Limit(napi_env env, napi_callback_info in napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::Limit Invalid argvs!"); + int32_t limit = 0; - napi_get_value_int32(env, args[0], &limit); + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2ValueExt(env, args[0], limit) == napi_ok, "the limit is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->Limit(limit); @@ -508,8 +554,10 @@ napi_value DataAbilityPredicatesProxy::Offset(napi_env env, napi_callback_info i napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::Offset Invalid argvs!"); + int32_t offset = 0; - napi_get_value_int32(env, args[0], &offset); + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2ValueExt(env, args[0], offset) == napi_ok, "the offset is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->Offset(offset); @@ -523,7 +571,10 @@ napi_value DataAbilityPredicatesProxy::GroupBy(napi_env env, napi_callback_info napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::GroupBy Invalid argvs!"); - std::vector fields = JSUtils::Convert2StrVector(env, args[0]); + + std::vector fields = {}; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], fields) == napi_ok, "the fields is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->GroupBy(fields); @@ -537,7 +588,10 @@ napi_value DataAbilityPredicatesProxy::IndexedBy(napi_env env, napi_callback_inf napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::IndexedBy Invalid argvs!"); - std::string indexName = JSUtils::Convert2String(env, args[0]); + + std::string indexName; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], indexName) == napi_ok, "the indexName is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->IndexedBy(indexName); @@ -551,8 +605,13 @@ napi_value DataAbilityPredicatesProxy::In(napi_env env, napi_callback_info info) napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::In Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::vector values = JSUtils::Convert2StrVector(env, args[1]); + + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + + std::vector values; + NAPI_ASSERT(env, JSUtils::Convert2Value(env, args[1], values) == napi_ok, "Invalid values!"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->In(field, values); @@ -566,8 +625,13 @@ napi_value DataAbilityPredicatesProxy::NotIn(napi_env env, napi_callback_info in napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::NotIn Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::vector values = JSUtils::Convert2StrVector(env, args[1]); + + std::string field; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], field) == napi_ok, "the field is invalid"); + + std::vector values; + NAPI_ASSERT(env, JSUtils::Convert2Value(env, args[1], values) == napi_ok, "Invalid values"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->NotIn(field, values); @@ -615,7 +679,9 @@ napi_value DataAbilityPredicatesProxy::SetWhereClause(napi_env env, napi_callbac napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::SetWhereClause Invalid argvs!"); - std::string whereClause = JSUtils::Convert2String(env, args[0]); + std::string whereClause; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], whereClause) == napi_ok, "whereClause is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->SetWhereClause(whereClause); @@ -639,7 +705,9 @@ napi_value DataAbilityPredicatesProxy::SetWhereArgs(napi_env env, napi_callback_ napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::SetWhereArgs Invalid argvs!"); - std::vector whereArgs = JSUtils::Convert2StrVector(env, args[0]); + std::vector whereArgs; + NAPI_ASSERT(env, JSUtils::Convert2Value(env, args[0], whereArgs) == napi_ok, "Invalid whereArgs!"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->SetWhereArgs(whereArgs); @@ -663,7 +731,9 @@ napi_value DataAbilityPredicatesProxy::SetOrder(napi_env env, napi_callback_info napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 0, "DataAbilityPredicatesProxy::SetOrder Invalid argvs!"); - std::string order = JSUtils::Convert2String(env, args[0]); + std::string order; + RDB_CHECK_RETURN_NULLPTR(JSUtils::Convert2Value(env, args[0], order) != napi_ok, "the order is invalid"); + auto nativePredicates = GetNativePredicates(env, info); RDB_CHECK_RETURN_NULLPTR(nativePredicates != nullptr, "GetNativePredicates return nullptr"); nativePredicates->SetOrder(order); @@ -733,7 +803,7 @@ __attribute__((visibility("default"))) napi_value NAPI_OHOS_Data_DataAbilityJsKi } __attribute__((visibility("default"))) OHOS::NativeRdb::DataAbilityPredicates * -NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject(const napi_env &env, const napi_value &arg) +NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject(const napi_env env, const napi_value arg) { auto predicates = OHOS::DataAbilityJsKit::DataAbilityPredicatesProxy::GetNativePredicates(env, arg); return predicates.get(); diff --git a/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp b/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp index 11e51d12..b6461a18 100644 --- a/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp +++ b/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp @@ -46,14 +46,14 @@ napi_value CreateRdbPredicates(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_unwrap(env, args[1], reinterpret_cast(&dataAbilityPredicatesProxy))); auto absPredicates = dataAbilityPredicatesProxy->GetPredicates(); - auto predicates = std::make_shared(tableName); + auto predicates = new NativeRdb::RdbPredicates(tableName); NativeRdb::PredicatesUtils::SetWhereClauseAndArgs( - predicates.get(), absPredicates->GetWhereClause(), absPredicates->GetWhereArgs()); - NativeRdb::PredicatesUtils::SetAttributes(predicates.get(), absPredicates->IsDistinct(), + predicates, absPredicates->GetWhereClause(), absPredicates->GetBindArgs()); + NativeRdb::PredicatesUtils::SetAttributes(predicates, absPredicates->IsDistinct(), absPredicates->GetIndex(), absPredicates->GetGroup(), absPredicates->GetOrder(), absPredicates->GetLimit(), absPredicates->GetOffset()); - return RdbJsKit::RdbPredicatesProxy::NewInstance(env, predicates); + return RdbJsKit::RdbPredicatesProxy::NewInstance(env, std::shared_ptr(predicates)); } napi_value InitPredicatesUtils(napi_env env, napi_value exports) diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_js_utils.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_js_utils.h index f7d95d29..2801cc5b 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_js_utils.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_js_utils.h @@ -23,12 +23,15 @@ namespace OHOS::AppDataMgrJsKit { namespace JSUtils { using Asset = OHOS::NativeRdb::AssetValue; using RowEntity = OHOS::NativeRdb::RowEntity; +using ValueObject = OHOS::NativeRdb::ValueObject; template<> int32_t Convert2Value(napi_env env, napi_value input, Asset &output); template<> napi_value Convert2JSValue(napi_env env, const Asset &value); template<> napi_value Convert2JSValue(napi_env env, const RowEntity &value); +template<> +int32_t Convert2Value(napi_env env, napi_value jsValue, ValueObject &valueObject); }; // namespace JSUtils } // namespace OHOS::AppDataMgrJsKit #endif // RDB_JSKIT_NAPI_RDB_JS_UTILS_H diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h index f9371b5e..81ba767f 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h @@ -52,11 +52,13 @@ private: static RdbPredicatesProxy *ParseInt32FieldByName( napi_env env, napi_callback_info info, napi_value &thiz, int32_t &field, const std::string fieldName); static RdbPredicatesProxy *ParseFieldAndValueArray(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::vector &value, const std::string valueType); + std::string &field, std::vector &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, NativeRdb::ValueObject &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldAndStringValue(napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, std::string &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldLowAndHigh(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::string &low, std::string &High); + std::string &field, NativeRdb::ValueObject &low, NativeRdb::ValueObject &High); static napi_value EqualTo(napi_env env, napi_callback_info info); static napi_value NotEqualTo(napi_env env, napi_callback_info info); diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h b/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h index 26fa2475..22f532aa 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h @@ -37,14 +37,13 @@ public: int version = AppDataMgrJsKit::APIVERSION_8); static napi_value NewInstance(napi_env env, std::shared_ptr resultSet, int version = AppDataMgrJsKit::APIVERSION_8); - static std::shared_ptr GetNativeObject(const napi_env &env, const napi_value &arg); + static std::shared_ptr GetNativeObject(const napi_env env, const napi_value arg); static napi_value GetConstructor(napi_env env, int version); std::shared_ptr Create() override; int apiversion = AppDataMgrJsKit::APIVERSION_8; private: - static std::shared_ptr &GetInnerResultSet( - napi_env env, napi_callback_info info, int &version); + static ResultSetProxy *GetInnerResultSet(napi_env env, napi_callback_info info, int &version); static ResultSetProxy *ParseInt32FieldByName( napi_env env, napi_callback_info info, int32_t &field, const std::string& fieldName); static ResultSetProxy *ParseFieldByName(napi_env env, napi_callback_info info, std::string &field); diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h index 9ab42672..c452312a 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h @@ -52,11 +52,13 @@ private: static RdbPredicatesProxy *ParseInt32FieldByName( napi_env env, napi_callback_info info, napi_value &thiz, int32_t &field, const std::string fieldName); static RdbPredicatesProxy *ParseFieldAndValueArray(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::vector &value, const std::string valueType); + std::string &field, std::vector &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, NativeRdb::ValueObject &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldAndStringValue(napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, std::string &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldLowAndHigh(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::string &low, std::string &High); + std::string &field, NativeRdb::ValueObject &low, NativeRdb::ValueObject &High); static napi_value EqualTo(napi_env env, napi_callback_info info); static napi_value NotEqualTo(napi_env env, napi_callback_info info); diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h index ac600bfe..3be1867e 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h @@ -38,8 +38,7 @@ public: int apiversion = AppDataMgrJsKit::APIVERSION_8; private: - static std::shared_ptr &GetInnerResultSet(napi_env env, napi_callback_info info, - int &version); + static ResultSetProxy *GetInnerResultSet(napi_env env, napi_callback_info info, int &version); static ResultSetProxy *ParseInt32FieldByName( napi_env env, napi_callback_info info, int32_t &field, const std::string& fieldName); static ResultSetProxy *ParseFieldByName(napi_env env, napi_callback_info info, std::string &field); diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_js_utils.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_js_utils.cpp index 566e4b1c..b8c3e809 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_js_utils.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_js_utils.cpp @@ -71,5 +71,15 @@ napi_value Convert2JSValue(napi_env env, const RowEntity &rowEntity) } return ret; } + +template<> +int32_t Convert2Value(napi_env env, napi_value jsValue, ValueObject &valueObject) +{ + auto status = Convert2Value(env, jsValue, valueObject.value); + if (status != napi_ok) { + return napi_invalid_arg; + } + return napi_ok; +} }; // namespace JSUtils } // namespace OHOS::AppDataMgrJsKit \ No newline at end of file diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp index 036482f1..4083bba0 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp @@ -220,8 +220,15 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldArrayByName(napi_env env, napi int version = predicatesProxy->apiversion; RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), version); - fieldarray = JSUtils::Convert2StrVector(env, args[0]); - RDB_NAPI_ASSERT_FROMV9(env, fieldarray.size() >= 0, + int32_t ret = JSUtils::Convert2Value(env, args[0], fieldarray); + if (ret != napi_ok && fieldName == "devices") { + std::string field; + ret = JSUtils::Convert2Value(env, args[0], field); + RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, + std::make_shared(fieldName, "a " + fieldType + " array."), version); + fieldarray.push_back(field); + } + RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, std::make_shared(fieldName, "a " + fieldType + " array."), version); return predicatesProxy; } @@ -261,7 +268,7 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseInt32FieldByName( } RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValueArray(napi_env env, napi_callback_info info, - napi_value &thiz, std::string &field, std::vector &value, const std::string valueType) + napi_value &thiz, std::string &field, std::vector &values, const std::string valueType) { size_t argc = 2; napi_value args[2] = { 0 }; @@ -275,53 +282,85 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValueArray(napi_env env, na RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), std::make_shared("field", "a non empty string."), version); - value = JSUtils::Convert2StrVector(env, args[1]); - RDB_NAPI_ASSERT_FROMV9(env, value.size() >= 0, + int32_t ret = JSUtils::Convert2Value(env, args[1], values); + RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, std::make_shared("value", "a " + valueType + " array."), version); return predicatesProxy; } RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::string &value, const std::string valueType) + std::string &field, ValueObject &value, const std::string valueType) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); size_t argc = 2; + // 2 represents the number of parameters napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); RdbPredicatesProxy *predicatesProxy = nullptr; napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); int version = predicatesProxy->apiversion; + // 2 represents the number of parameters RDB_NAPI_ASSERT_FROMV9(env, argc == 2, std::make_shared("2"), version); + // args[0] represents the first parameter field = JSUtils::Convert2String(env, args[0]); RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), std::make_shared("field", "a non empty string."), version); - value = JSUtils::ConvertAny2String(env, args[1]); + // args[1] represents the second parameter + int ret = JSUtils::Convert2Value(env, args[1], value.value); + RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, + std::make_shared("value", "a non empty string."), version); + return predicatesProxy; +} + +RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndStringValue(napi_env env, napi_callback_info info, + napi_value &thiz, std::string &field, std::string &value, const std::string valueType) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + size_t argc = 2; + napi_value args[2] = { 0 }; + napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); + RdbPredicatesProxy *predicatesProxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); + int version = predicatesProxy->apiversion; + // 2 represents the number of parameters + RDB_NAPI_ASSERT_FROMV9(env, argc == 2, std::make_shared("2"), version); + + field = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), + std::make_shared("field", "a non empty string."), version); + + value = JSUtils::Convert2String(env, args[1]); return predicatesProxy; } RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldLowAndHigh( - napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, std::string &low, std::string &high) + napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, ValueObject &low, ValueObject &high) { size_t argc = 3; + // 3 represents the number of parameters napi_value args[3] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); RdbPredicatesProxy *predicatesProxy = nullptr; napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); int version = predicatesProxy->apiversion; + // 3 represents the number of parameters RDB_NAPI_ASSERT_FROMV9(env, argc == 3, std::make_shared("3"), version); + // args[0] represents the first parameter field = JSUtils::Convert2String(env, args[0]); - RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), + RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), std::make_shared("field", "a non empty string."), version); - low = JSUtils::ConvertAny2String(env, args[1]); - RDB_NAPI_ASSERT_FROMV9(env, !low.empty(), + // args[1] represents the second parameter + int32_t ret = JSUtils::Convert2Value(env, args[1], low); + RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, std::make_shared("low", "a non empty ValueType."), version); - high = JSUtils::ConvertAny2String(env, args[2]); - RDB_NAPI_ASSERT_FROMV9(env, !high.empty(), + // args[2] represents the third parameter + ret = JSUtils::Convert2Value(env, args[2], high); + RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, std::make_shared("high", "a non empty ValueType."), version); return predicatesProxy; @@ -332,7 +371,7 @@ napi_value RdbPredicatesProxy::EqualTo(napi_env env, napi_callback_info info) DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -344,7 +383,7 @@ napi_value RdbPredicatesProxy::NotEqualTo(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -397,7 +436,7 @@ napi_value RdbPredicatesProxy::Contains(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); predicatesProxy->predicates_->Contains(field, value); @@ -409,7 +448,7 @@ napi_value RdbPredicatesProxy::BeginsWith(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); predicatesProxy->predicates_->BeginsWith(field, value); @@ -421,7 +460,7 @@ napi_value RdbPredicatesProxy::EndsWith(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); predicatesProxy->predicates_->EndsWith(field, value); @@ -455,7 +494,7 @@ napi_value RdbPredicatesProxy::Like(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); predicatesProxy->predicates_->Like(field, value); @@ -467,7 +506,7 @@ napi_value RdbPredicatesProxy::Glob(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); predicatesProxy->predicates_->Glob(field, value); @@ -478,8 +517,8 @@ napi_value RdbPredicatesProxy::Between(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; std::string field = ""; - std::string low = ""; - std::string high = ""; + ValueObject low; + ValueObject high; auto predicatesProxy = ParseFieldLowAndHigh(env, info, thiz, field, low, high); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -491,8 +530,8 @@ napi_value RdbPredicatesProxy::NotBetween(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; std::string field = ""; - std::string low = ""; - std::string high = ""; + ValueObject low; + ValueObject high; auto predicatesProxy = ParseFieldLowAndHigh(env, info, thiz, field, low, high); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -504,7 +543,7 @@ napi_value RdbPredicatesProxy::GreaterThan(napi_env env, napi_callback_info info { napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -516,7 +555,7 @@ napi_value RdbPredicatesProxy::LessThan(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -528,7 +567,7 @@ napi_value RdbPredicatesProxy::GreaterThanOrEqualTo(napi_env env, napi_callback_ { napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; RdbPredicatesProxy *predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -540,7 +579,7 @@ napi_value RdbPredicatesProxy::LessThanOrEqualTo(napi_env env, napi_callback_inf { napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; RdbPredicatesProxy *predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -583,7 +622,7 @@ napi_value RdbPredicatesProxy::Distinct(napi_env env, napi_callback_info info) napi_value RdbPredicatesProxy::Limit(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; - int32_t limit = 0; + int32_t limit = AbsPredicates::INIT_LIMIT_VALUE; auto predicatesProxy = ParseInt32FieldByName(env, info, thiz, limit, "value"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -594,7 +633,7 @@ napi_value RdbPredicatesProxy::Limit(napi_env env, napi_callback_info info) napi_value RdbPredicatesProxy::Offset(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; - int32_t offset = 0; + int32_t offset = AbsPredicates::INIT_OFFSET_VALUE; auto predicatesProxy = ParseInt32FieldByName(env, info, thiz, offset, "rowOffset"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -629,7 +668,7 @@ napi_value RdbPredicatesProxy::In(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; std::string field = ""; - std::vector values; + std::vector values; auto predicatesProxy = ParseFieldAndValueArray(env, info, thiz, field, values, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); @@ -641,7 +680,7 @@ napi_value RdbPredicatesProxy::NotIn(napi_env env, napi_callback_info info) { napi_value thiz = nullptr; std::string field = ""; - std::vector values; + std::vector values; auto predicatesProxy = ParseFieldAndValueArray(env, info, thiz, field, values, "ValueType"); RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr && predicatesProxy->predicates_ != nullptr, "RdbPredicatesProxy predicatesProxy or predicates_ is nullptr"); diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp index cc0c032e..16001377 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp @@ -53,7 +53,6 @@ struct PredicatesProxy { #endif struct RdbStoreContext : public BaseContext { bool isNapiString = false; - int BindArgs(napi_env env, napi_value arg); std::string device; std::string tableName; std::vector tablesName; @@ -96,50 +95,6 @@ struct RdbStoreContext : public BaseContext { static __thread napi_ref constructor_ = nullptr; static __thread napi_ref constructorV9_ = nullptr; -int RdbStoreContext::BindArgs(napi_env env, napi_value arg) -{ - bindArgs.clear(); - uint32_t arrLen = 0; - napi_get_array_length(env, arg, &arrLen); - if (arrLen == 0) { - return OK; - } - for (size_t i = 0; i < arrLen; ++i) { - napi_value element; - napi_get_element(env, arg, i, &element); - napi_valuetype type; - napi_typeof(env, element, &type); - switch (type) { - case napi_boolean: { - bool value = false; - napi_status status = napi_get_value_bool(env, element, &value); - if (status == napi_ok) { - bindArgs.push_back(ValueObject(value)); - } - } break; - case napi_number: { - double value; - napi_status status = napi_get_value_double(env, element, &value); - if (status == napi_ok) { - bindArgs.push_back(ValueObject(value)); - } - } break; - case napi_null: - bindArgs.push_back(ValueObject()); - break; - case napi_string: - bindArgs.push_back(ValueObject(JSUtils::Convert2String(env, element, false))); - break; - case napi_object: - bindArgs.push_back(ValueObject(JSUtils::Convert2U8Vector(env, element))); - break; - default: - break; - } - } - return OK; -} - RdbStoreProxy::RdbStoreProxy() { } @@ -274,15 +229,18 @@ RdbStoreProxy *RdbStoreProxy::GetNativeInstance(napi_env env, napi_value self) return proxy; } -void ParserThis(const napi_env &env, const napi_value &self, std::shared_ptr context) +int ParserThis(const napi_env &env, const napi_value &self, std::shared_ptr context) { RdbStoreProxy *obj = RdbStoreProxy::GetNativeInstance(env, self); + std::shared_ptr paramError = std::make_shared("RdbStore", "not nullptr."); + RDB_CHECK_RETURN_CALL_RESULT(obj, context->SetError(paramError)); context->apiversion = obj->apiversion; context->boundObj = obj; LOG_DEBUG("ParserThis RdbStoreProxy is v%{public}d", obj->apiversion); + return OK; } -int ParseTableName(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseTableName(const napi_env env, const napi_value arg, std::shared_ptr context) { context->tableName = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("table", "a non empty string."); @@ -292,7 +250,7 @@ int ParseTableName(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseDevice(const napi_env env, const napi_value arg, std::shared_ptr context) { context->device = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("device", "a non empty string."); @@ -302,7 +260,7 @@ int ParseDevice(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseTablesName(const napi_env env, const napi_value arg, std::shared_ptr context) { uint32_t arrLen = 0; napi_get_array_length(env, arg, &arrLen); @@ -323,7 +281,7 @@ int ParseTablesName(const napi_env &env, const napi_value &arg, std::shared_ptr< return OK; } -int ParseSyncModeArg(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseSyncModeArg(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_get_value_int32(env, arg, &context->enumArg); std::shared_ptr paramError = std::make_shared("mode", "a SyncMode."); @@ -333,7 +291,7 @@ int ParseSyncModeArg(const napi_env &env, const napi_value &arg, std::shared_ptr return OK; } -bool CheckGlobalProperty(const napi_env &env, const napi_value &arg, const std::string &propertyName) +bool CheckGlobalProperty(const napi_env env, const napi_value arg, const std::string &propertyName) { LOG_DEBUG("CheckGlobalProperty start: %{public}s", propertyName.c_str()); napi_value global = nullptr; @@ -351,7 +309,7 @@ bool CheckGlobalProperty(const napi_env &env, const napi_value &arg, const std:: return (status == napi_ok ? result : false); } -int ParsePredicates(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParsePredicates(const napi_env env, const napi_value arg, std::shared_ptr context) { LOG_DEBUG("ParsePredicates start"); std::shared_ptr paramError = std::make_shared("predicates", "an RdbPredicates."); @@ -387,14 +345,7 @@ int ParsePredicates(const napi_env &env, const napi_value &arg, std::shared_ptr< return OK; } -int ParseNewKey(const napi_env &env, const napi_value &arg, std::shared_ptr context) -{ - context->newKey = JSUtils::Convert2U8Vector(env, arg); - LOG_DEBUG("ParseNewKey end"); - return OK; -} - -int ParseSrcName(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseSrcName(const napi_env env, const napi_value arg, std::shared_ptr context) { context->srcName = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("srcName", "a non empty string."); @@ -404,14 +355,20 @@ int ParseSrcName(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseColumns(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->columns = JSUtils::Convert2StrVector(env, arg); - LOG_DEBUG("ParseColumns end"); + napi_valuetype type; + napi_typeof(env, arg, &type); + if (type == napi_undefined || type == napi_null) { + return OK; + } + int32_t ret = JSUtils::Convert2Value(env, arg, context->columns); + std::shared_ptr paramError = std::make_shared("columns", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(ret == napi_ok, context->SetError(paramError)); return OK; } -int ParseWhereClause(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseWhereClause(const napi_env env, const napi_value arg, std::shared_ptr context) { context->whereClause = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("whereClause", "a non empty string."); @@ -421,7 +378,7 @@ int ParseWhereClause(const napi_env &env, const napi_value &arg, std::shared_ptr return OK; } -int ParseAlias(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseAlias(const napi_env env, const napi_value arg, std::shared_ptr context) { context->aliasName = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("aliasName", "a non empty string."); @@ -431,7 +388,7 @@ int ParseAlias(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParsePath(const napi_env env, const napi_value arg, std::shared_ptr context) { context->pathName = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("pathName", "a non empty string."); @@ -441,23 +398,35 @@ int ParsePath(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseWhereArgs(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->whereArgs = JSUtils::Convert2StrVector(env, arg); - LOG_DEBUG("ParseWhereArgs end"); + napi_valuetype type; + napi_typeof(env, arg, &type); + if (type == napi_undefined || type == napi_null) { + return OK; + } + int32_t ret = JSUtils::Convert2Value(env, arg, context->whereArgs); + std::shared_ptr paramError = std::make_shared("columns", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(ret == napi_ok, context->SetError(paramError)); return OK; } -int ParseSelectionArgs(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseSelectionArgs(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->selectionArgs = JSUtils::Convert2StrVector(env, arg); - LOG_DEBUG("ParseSelectionArgs end"); + napi_valuetype type; + napi_typeof(env, arg, &type); + if (type == napi_undefined || type == napi_null) { + return OK; + } + int32_t ret = JSUtils::Convert2Value(env, arg, context->selectionArgs); + std::shared_ptr paramError = std::make_shared("columns", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(ret == napi_ok, context->SetError(paramError)); return OK; } -int ParseSql(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseSql(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->sql = JSUtils::Convert2String(env, arg, false); + context->sql = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("sql", "a non empty string."); RDB_CHECK_RETURN_CALL_RESULT(!context->sql.empty(), context->SetError(paramError)); @@ -465,7 +434,7 @@ int ParseSql(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseValuesBucket(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_value keys = 0; napi_get_property_names(env, arg, &keys); @@ -485,23 +454,11 @@ int ParseValuesBucket(const napi_env &env, const napi_value &arg, std::shared_pt std::string keyStr = JSUtils::Convert2String(env, key); napi_value value; napi_get_property(env, arg, key, &value); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, value, &valueType); - if (valueType == napi_string) { - std::string valueString = JSUtils::Convert2String(env, value, false); - context->valuesBucket.PutString(keyStr, valueString); - } else if (valueType == napi_number) { - double valueNumber; - napi_get_value_double(env, value, &valueNumber); - context->valuesBucket.PutDouble(keyStr, valueNumber); - } else if (valueType == napi_boolean) { - bool valueBool = false; - napi_get_value_bool(env, value, &valueBool); - context->valuesBucket.PutBool(keyStr, valueBool); - } else if (valueType == napi_null) { - context->valuesBucket.PutNull(keyStr); - } else if (valueType == napi_object) { - context->valuesBucket.PutBlob(keyStr, JSUtils::Convert2U8Vector(env, value)); + + ValueObject valueObject; + int32_t ret = JSUtils::Convert2Value(env, value, valueObject.value); + if (ret == napi_ok) { + context->valuesBucket.Put(keyStr, std::move(valueObject)); } else { LOG_WARN("bad value type of key %{public}s", keyStr.c_str()); } @@ -510,7 +467,7 @@ int ParseValuesBucket(const napi_env &env, const napi_value &arg, std::shared_pt return OK; } -int ParseValuesBuckets(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseValuesBuckets(const napi_env env, const napi_value arg, std::shared_ptr context) { bool isArray = false; napi_is_array(env, arg, &isArray); @@ -562,7 +519,7 @@ napi_value RdbStoreProxy::Insert(napi_env env, napi_callback_info info) RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBucket(env, argv[1], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -596,7 +553,7 @@ napi_value RdbStoreProxy::BatchInsert(napi_env env, napi_callback_info info) RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBuckets(env, argv[1], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -638,7 +595,7 @@ napi_value RdbStoreProxy::Delete(napi_env env, napi_callback_info info) RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[0], context)); } - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -681,7 +638,7 @@ napi_value RdbStoreProxy::Update(napi_env env, napi_callback_info info) RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBucket(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[1], context)); } - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -727,7 +684,7 @@ napi_value RdbStoreProxy::Query(napi_env env, napi_callback_info info) RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseColumns(env, argv[1], context)); } } - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -763,7 +720,7 @@ napi_value RdbStoreProxy::QuerySql(napi_env env, napi_callback_info info) RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSelectionArgs(env, argv[1], context)); #endif } - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -793,9 +750,24 @@ napi_value RdbStoreProxy::QuerySql(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -int ParseBindArgs(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseBindArgs(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->BindArgs(env, arg); + context->bindArgs.clear(); + uint32_t arrLen = 0; + napi_get_array_length(env, arg, &arrLen); + if (arrLen == 0) { + return OK; + } + for (size_t i = 0; i < arrLen; ++i) { + napi_value element; + napi_get_element(env, arg, i, &element); + + ValueObject valueObject; + int32_t ret = JSUtils::Convert2Value(env, element, valueObject.value); + std::shared_ptr paramError = std::make_shared("tables", "a string array."); + RDB_CHECK_RETURN_CALL_RESULT(ret == napi_ok, context->SetError(paramError)); + context->bindArgs.push_back(valueObject); + } return OK; } @@ -810,7 +782,7 @@ napi_value RdbStoreProxy::ExecuteSql(napi_env env, napi_callback_info info) if (argc > 1) { RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseBindArgs(env, argv[1], context)); } - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -840,7 +812,7 @@ napi_value RdbStoreProxy::Count(napi_env env, napi_callback_info info) std::shared_ptr paramNumError = std::make_shared("1 or 2"); RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[0], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -876,7 +848,7 @@ napi_value RdbStoreProxy::Replace(napi_env env, napi_callback_info info) RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBucket(env, argv[1], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -909,8 +881,7 @@ napi_value RdbStoreProxy::Attach(napi_env env, napi_callback_info info) RDB_CHECK_RETURN_CALL_RESULT(argc == 3 || argc == 4, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseAlias(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePath(env, argv[1], context)); - RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseNewKey(env, argv[2], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -1027,7 +998,7 @@ napi_value RdbStoreProxy::QueryByStep(napi_env env, napi_callback_info info) RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSql(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseColumns(env, argv[1], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -1112,7 +1083,7 @@ napi_value RdbStoreProxy::SetDistributedTables(napi_env env, napi_callback_info std::shared_ptr paramNumError = std::make_shared("1 or 2"); RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTablesName(env, argv[0], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -1145,7 +1116,7 @@ napi_value RdbStoreProxy::ObtainDistributedTableName(napi_env env, napi_callback RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseDevice(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[1], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { @@ -1182,7 +1153,7 @@ napi_value RdbStoreProxy::Sync(napi_env env, napi_callback_info info) RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSyncModeArg(env, argv[0], context)); RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[1], context)); - ParserThis(env, self, context); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParserThis(env, self, context)); return OK; }; auto exec = [context]() { diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp index 8e44a5cb..3d5d7593 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp @@ -389,7 +389,7 @@ int ParseStoreConfigV9(const napi_env &env, const napi_value &object, std::share return OK; } -int ParsePath(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParsePath(const napi_env env, const napi_value arg, std::shared_ptr context) { std::string path = JSUtils::Convert2String(env, arg); std::shared_ptr paramError = std::make_shared("name", "a without path non empty string."); @@ -411,7 +411,7 @@ int ParsePath(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseVersion(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_get_value_int32(env, arg, &context->version); std::shared_ptr paramError = std::make_shared("version", "an integer greater than 0."); diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp index 4fa7cb92..1284f609 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp @@ -86,7 +86,7 @@ napi_value ResultSetProxy::NewInstance(napi_env env, std::shared_ptr ResultSetProxy::GetNativeObject( - napi_env const &env, napi_value const &arg) + napi_env const env, napi_value const arg) { if (arg == nullptr) { LOG_ERROR("ResultSetProxy GetNativeObject arg is null."); @@ -94,8 +94,8 @@ std::shared_ptr ResultSetProxy::GetNativeObject( } ResultSetProxy *proxy = nullptr; napi_unwrap(env, arg, reinterpret_cast(&proxy)); - if (proxy == nullptr) { - LOG_ERROR("ResultSetProxy GetNativeObject proxy is null."); + if (proxy == nullptr || proxy->sharedResultSet_ == nullptr) { + LOG_ERROR("ResultSetProxy GetNativeObject proxy or sharedResultSet_ is null."); return nullptr; } return proxy->sharedResultSet_; @@ -107,7 +107,7 @@ std::shared_ptr ResultSetProxy::Create() LOG_ERROR("resultSet_ is null"); return nullptr; } - return std::make_shared(resultSet_); + return std::make_shared(std::move(resultSet_)); } #endif @@ -221,15 +221,17 @@ ResultSetProxy &ResultSetProxy::operator=(std::shared_ptr resultSet) return *this; } -std::shared_ptr &ResultSetProxy::GetInnerResultSet( - napi_env env, napi_callback_info info, int &version) +ResultSetProxy *ResultSetProxy::GetInnerResultSet(napi_env env, napi_callback_info info, int &version) { ResultSetProxy *resultSetProxy = nullptr; napi_value self = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr); napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)); + RDB_NAPI_ASSERT_FROMV9(env, resultSetProxy && resultSetProxy->resultSet_, std::make_shared(), + resultSetProxy->apiversion); + version = resultSetProxy->apiversion; - return resultSetProxy->resultSet_; + return resultSetProxy; } ResultSetProxy *ResultSetProxy::ParseInt32FieldByName( @@ -242,8 +244,14 @@ ResultSetProxy *ResultSetProxy::ParseInt32FieldByName( napi_get_cb_info(env, info, &argc, args, &self, nullptr); ResultSetProxy *resultSetProxy = nullptr; napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)); - RDB_CHECK_RETURN_NULLPTR(napi_get_value_int32(env, args[0], &field) == napi_ok, - "napi_get_value_int32 reurn invalid"); + RDB_NAPI_ASSERT_FROMV9(env, resultSetProxy && resultSetProxy->resultSet_, + std::make_shared("resultSet", "not null"), resultSetProxy->apiversion); + RDB_NAPI_ASSERT_FROMV9( + env, argc == 1, std::make_shared("1"), resultSetProxy->apiversion); + + napi_status status = napi_get_value_int32(env, args[0], &field); + RDB_NAPI_ASSERT_FROMV9( + env, status == napi_ok, std::make_shared(name, "a number."), resultSetProxy->apiversion); return resultSetProxy; } @@ -254,8 +262,11 @@ ResultSetProxy *ResultSetProxy::ParseFieldByName(napi_env env, napi_callback_inf napi_value args[1] = { 0 }; napi_get_cb_info(env, info, &argc, args, &self, nullptr); ResultSetProxy *resultSetProxy = nullptr; - RDB_CHECK_RETURN_NULLPTR(napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)) == napi_ok, - "napi_unwrap return invalid"); + napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + RDB_NAPI_ASSERT_FROMV9( + env, argc == 1, std::make_shared("1"), resultSetProxy->apiversion); + field = JSUtils::Convert2String(env, args[0]); return resultSetProxy; } @@ -264,7 +275,10 @@ napi_value ResultSetProxy::GetAllColumnNames(napi_env env, napi_callback_info in { std::vector colNames; int version = 0; - int errCode = GetInnerResultSet(env, info, version)->GetAllColumnNames(colNames); + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int errCode = resultSetProxy->resultSet_->GetAllColumnNames(colNames); if (errCode != E_OK) { LOG_ERROR("GetAllColumnNames failed code:%{public}d, version:%{public}d", errCode, version); } @@ -275,8 +289,8 @@ napi_value ResultSetProxy::GoToRow(napi_env env, napi_callback_info info) { int32_t position; auto resultSetProxy = ParseInt32FieldByName(env, info, position, "position"); - RDB_NAPI_ASSERT_FROMV9(env, resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - std::make_shared(), resultSetProxy->apiversion); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GoToRow(position); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } @@ -285,7 +299,10 @@ napi_value ResultSetProxy::GetColumnCount(napi_env env, napi_callback_info info) { int32_t count = 0; int version = 0; - int errCode = GetInnerResultSet(env, info, version)->GetColumnCount(count); + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int errCode = resultSetProxy->resultSet_->GetColumnCount(count); if (errCode != E_OK) { LOG_ERROR("GetColumnCount failed code:%{public}d, version:%{public}d", errCode, version); } @@ -297,8 +314,8 @@ napi_value ResultSetProxy::GetLong(napi_env env, napi_callback_info info) int32_t columnIndex; int64_t result; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetLong(columnIndex, result); int version = resultSetProxy->apiversion; RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); @@ -310,11 +327,12 @@ napi_value ResultSetProxy::GetColumnType(napi_env env, napi_callback_info info) int32_t columnIndex; ColumnType columnType; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetColumnType(columnIndex, columnType); - int version = resultSetProxy->apiversion; - RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); + if (errCode != E_OK) { + LOG_ERROR("GetColumnType failed code:%{public}d, version:%{public}d", errCode, resultSetProxy->apiversion); + } return JSUtils::Convert2JSValue(env, int32_t(columnType)); } @@ -322,8 +340,8 @@ napi_value ResultSetProxy::GoTo(napi_env env, napi_callback_info info) { int32_t offset; auto resultSetProxy = ParseInt32FieldByName(env, info, offset, "offset"); - RDB_NAPI_ASSERT_FROMV9(env, resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - std::make_shared(), resultSetProxy->apiversion); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GoTo(offset); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } @@ -333,8 +351,8 @@ napi_value ResultSetProxy::GetColumnIndex(napi_env env, napi_callback_info info) std::string input; int32_t result = -1; auto resultSetProxy = ParseFieldByName(env, info, input); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetColumnIndex(input, result); if (errCode != E_OK) { LOG_ERROR("GetColumnIndex failed code:%{public}d, version:%{public}d", errCode, resultSetProxy->apiversion); @@ -347,8 +365,8 @@ napi_value ResultSetProxy::GetInt(napi_env env, napi_callback_info info) int32_t columnIndex; int32_t result; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetInt(columnIndex, result); int version = resultSetProxy->apiversion; RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); @@ -360,8 +378,8 @@ napi_value ResultSetProxy::GetColumnName(napi_env env, napi_callback_info info) int32_t columnIndex; std::string result; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetColumnName(columnIndex, result); if (errCode != E_OK) { LOG_ERROR("GetColumnName failed code:%{public}d, version:%{public}d", errCode, resultSetProxy->apiversion); @@ -371,10 +389,11 @@ napi_value ResultSetProxy::GetColumnName(napi_env env, napi_callback_info info) napi_value ResultSetProxy::Close(napi_env env, napi_callback_info info) { - int version; - auto resultSet = GetInnerResultSet(env, info, version); - RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); - int errCode = resultSet->Close(); + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int errCode = resultSetProxy->resultSet_->Close(); RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); napi_value result = nullptr; napi_get_null(env, &result); @@ -383,9 +402,12 @@ napi_value ResultSetProxy::Close(napi_env env, napi_callback_info info) napi_value ResultSetProxy::GetRowCount(napi_env env, napi_callback_info info) { - int version; + int version = 0; + ResultSetProxy *resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int32_t result; - int errCode = GetInnerResultSet(env, info, version)->GetRowCount(result); + int errCode = resultSetProxy->resultSet_->GetRowCount(result); if (errCode != E_OK) { LOG_ERROR("GetRowCount failed code:%{public}d, version:%{public}d", errCode, version); } @@ -394,9 +416,12 @@ napi_value ResultSetProxy::GetRowCount(napi_env env, napi_callback_info info) napi_value ResultSetProxy::GetRowIndex(napi_env env, napi_callback_info info) { - int version; + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int32_t result; - int errCode = GetInnerResultSet(env, info, version)->GetRowIndex(result); + int errCode = resultSetProxy->resultSet_->GetRowIndex(result); if (errCode != E_OK) { LOG_ERROR("GetRowIndex failed code:%{public}d, version:%{public}d", errCode, version); } @@ -405,9 +430,12 @@ napi_value ResultSetProxy::GetRowIndex(napi_env env, napi_callback_info info) napi_value ResultSetProxy::IsEnded(napi_env env, napi_callback_info info) { - int version; + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + bool result = false; - int errCode = GetInnerResultSet(env, info, version)->IsEnded(result); + int errCode = resultSetProxy->resultSet_->IsEnded(result); if (errCode != E_OK) { LOG_ERROR("IsEnded failed code:%{public}d, version:%{public}d", errCode, version); } @@ -416,9 +444,12 @@ napi_value ResultSetProxy::IsEnded(napi_env env, napi_callback_info info) napi_value ResultSetProxy::IsBegin(napi_env env, napi_callback_info info) { - int version; + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + bool result = false; - int errCode = GetInnerResultSet(env, info, version)->IsStarted(result); + int errCode = resultSetProxy->resultSet_->IsStarted(result); if (errCode != E_OK) { LOG_ERROR("IsBegin failed code:%{public}d, version:%{public}d", errCode, version); } @@ -427,45 +458,52 @@ napi_value ResultSetProxy::IsBegin(napi_env env, napi_callback_info info) napi_value ResultSetProxy::GoToFirstRow(napi_env env, napi_callback_info info) { - int version; - auto resultSet = GetInnerResultSet(env, info, version); - RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); - int errCode = resultSet->GoToFirstRow(); + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int errCode = resultSetProxy->resultSet_->GoToFirstRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GoToLastRow(napi_env env, napi_callback_info info) { - int version; - auto resultSet = GetInnerResultSet(env, info, version); - RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); - int errCode = resultSet->GoToLastRow(); + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int errCode = resultSetProxy->resultSet_->GoToLastRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GoToNextRow(napi_env env, napi_callback_info info) { - int version; - auto resultSet = GetInnerResultSet(env, info, version); - RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); - int errCode = resultSet->GoToNextRow(); + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int errCode = resultSetProxy->resultSet_->GoToNextRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GoToPreviousRow(napi_env env, napi_callback_info info) { - int version; - auto resultSet = GetInnerResultSet(env, info, version); - RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); - int errCode = resultSet->GoToPreviousRow(); + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int errCode = resultSetProxy->resultSet_->GoToPreviousRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::IsAtFirstRow(napi_env env, napi_callback_info info) { - int version; + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + bool result = false; - int errCode = GetInnerResultSet(env, info, version)->IsAtFirstRow(result); + int errCode = resultSetProxy->resultSet_->IsAtFirstRow(result); if (errCode != E_OK) { LOG_ERROR("IsAtFirstRow failed code:%{public}d, version:%{public}d", errCode, version); } @@ -474,9 +512,12 @@ napi_value ResultSetProxy::IsAtFirstRow(napi_env env, napi_callback_info info) napi_value ResultSetProxy::IsAtLastRow(napi_env env, napi_callback_info info) { - int version; + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + bool result = false; - int errCode = GetInnerResultSet(env, info, version)->IsAtLastRow(result); + int errCode = resultSetProxy->resultSet_->IsAtLastRow(result); if (errCode != E_OK) { LOG_ERROR("IsAtLastRow failed code:%{public}d, version:%{public}d", errCode, version); } @@ -489,8 +530,8 @@ napi_value ResultSetProxy::GetBlob(napi_env env, napi_callback_info info) int32_t columnIndex; std::vector result; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetBlob(columnIndex, result); int version = resultSetProxy->apiversion; RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); @@ -503,8 +544,8 @@ napi_value ResultSetProxy::GetString(napi_env env, napi_callback_info info) int32_t columnIndex; std::string result; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetString(columnIndex, result); int version = resultSetProxy->apiversion; RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); @@ -516,8 +557,8 @@ napi_value ResultSetProxy::GetDouble(napi_env env, napi_callback_info info) int32_t columnIndex; double result = 0.0; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->GetDouble(columnIndex, result); int version = resultSetProxy->apiversion; RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); @@ -529,8 +570,8 @@ napi_value ResultSetProxy::IsColumnNull(napi_env env, napi_callback_info info) int32_t columnIndex; bool result = false; auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); - RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr && resultSetProxy->resultSet_ != nullptr, - "resultSetProxy or resultSet_ is nullptr"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + int errCode = resultSetProxy->resultSet_->IsColumnNull(columnIndex, result); int version = resultSetProxy->apiversion; RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); @@ -541,8 +582,11 @@ napi_value ResultSetProxy::IsColumnNull(napi_env env, napi_callback_info info) napi_value ResultSetProxy::IsClosed(napi_env env, napi_callback_info info) { - int version; - int result = GetInnerResultSet(env, info, version)->IsClosed(); + int version = 0; + auto resultSetProxy = GetInnerResultSet(env, info, version); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->resultSet_, "resultSetProxy or resultSet_ is nullptr"); + + int result = resultSetProxy->resultSet_->IsClosed(); napi_value output; napi_get_boolean(env, result, &output); return output; diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp index 458f4215..00349fc6 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp @@ -52,7 +52,6 @@ __attribute__((visibility("default"))) ValuesBucket *NAPI_OHOS_Data_RdbJsKit_Val LOG_DEBUG("ValuesBucket errr"); return valuesBucket; } - LOG_DEBUG("ValuesBucket num:%{public}u ", arrLen); for (size_t i = 0; i < arrLen; ++i) { napi_value key; napi_get_element(env, keys, i, &key); @@ -64,23 +63,20 @@ __attribute__((visibility("default"))) ValuesBucket *NAPI_OHOS_Data_RdbJsKit_Val if (valueType == napi_string) { std::string valueString = JSUtils::Convert2String(env, value); valuesBucket->PutString(keyStr, valueString); - LOG_DEBUG("ValueObject type napi_string"); } else if (valueType == napi_number) { double valueNumber; napi_get_value_double(env, value, &valueNumber); valuesBucket->PutDouble(keyStr, valueNumber); - LOG_DEBUG("ValueObject type napi_number"); } else if (valueType == napi_boolean) { bool valueBool = false; napi_get_value_bool(env, value, &valueBool); valuesBucket->PutBool(keyStr, valueBool); - LOG_DEBUG("ValueObject type napi_boolean"); } else if (valueType == napi_null) { valuesBucket->PutNull(keyStr); - LOG_DEBUG("ValueObject type napi_null"); } else if (valueType == napi_object) { - valuesBucket->PutBlob(keyStr, JSUtils::Convert2U8Vector(env, value)); - LOG_DEBUG("ValueObject type napi_object"); + std::vector val = {}; + JSUtils::Convert2Value(env, value, val); + valuesBucket->PutBlob(keyStr, val); } else { LOG_WARN("valuesBucket error"); } diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_js_utils.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_js_utils.h index 5f25014d..268d3086 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_js_utils.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_js_utils.h @@ -27,6 +27,7 @@ namespace OHOS::AppDataMgrJsKit { namespace JSUtils { using Asset = OHOS::NativeRdb::AssetValue; using RowEntity = OHOS::NativeRdb::RowEntity; +using ValueObject = OHOS::NativeRdb::ValueObject; using Date = OHOS::DistributedRdb::Date; using JSChangeInfo = OHOS::RelationalStoreJsKit::NapiRdbStoreObserver::JSChangeInfo; using PRIKey = OHOS::DistributedRdb::RdbStoreObserver::PrimaryKey; @@ -34,12 +35,18 @@ using PRIKey = OHOS::DistributedRdb::RdbStoreObserver::PrimaryKey; template<> int32_t Convert2Value(napi_env env, napi_value input, Asset &output); +template<> +int32_t Convert2Value(napi_env env, napi_value jsValue, ValueObject &valueObject); + template<> napi_value Convert2JSValue(napi_env env, const Asset &value); template<> napi_value Convert2JSValue(napi_env env, const RowEntity &value); +template<> +napi_value Convert2JSValue(napi_env env, const ValueObject &value); + template<> napi_value Convert2JSValue(napi_env env, const DistributedRdb::Statistic &statistic); template<> diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h index 2a7aaa42..5317cbf1 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h @@ -48,11 +48,13 @@ private: static RdbPredicatesProxy *ParseInt32FieldByName( napi_env env, napi_callback_info info, napi_value &thiz, int32_t &field, const std::string fieldName); static RdbPredicatesProxy *ParseFieldAndValueArray(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::vector &value, const std::string valueType); + std::string &field, std::vector &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, NativeRdb::ValueObject &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldAndStringValue(napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, std::string &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldLowAndHigh(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::string &low, std::string &High); + std::string &field, NativeRdb::ValueObject &low, NativeRdb::ValueObject &High); static napi_value EqualTo(napi_env env, napi_callback_info info); static napi_value NotEqualTo(napi_env env, napi_callback_info info); diff --git a/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_predicates.h index 0b7878ff..92167bc6 100644 --- a/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_predicates.h @@ -48,11 +48,13 @@ private: static RdbPredicatesProxy *ParseInt32FieldByName( napi_env env, napi_callback_info info, napi_value &thiz, int32_t &field, const std::string fieldName); static RdbPredicatesProxy *ParseFieldAndValueArray(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::vector &value, const std::string valueType); + std::string &field, std::vector &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, NativeRdb::ValueObject &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldAndStringValue(napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, std::string &value, const std::string valueType); static RdbPredicatesProxy *ParseFieldLowAndHigh(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::string &low, std::string &High); + std::string &field, NativeRdb::ValueObject &low, NativeRdb::ValueObject &High); static napi_value EqualTo(napi_env env, napi_callback_info info); static napi_value NotEqualTo(napi_env env, napi_callback_info info); diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_js_utils.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_js_utils.cpp index 4e26ffb2..8caba162 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_js_utils.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_js_utils.cpp @@ -76,6 +76,16 @@ int32_t Convert2Value(napi_env env, napi_value input, DistributedRdb::Distribute return ret; } +template<> +int32_t Convert2Value(napi_env env, napi_value jsValue, ValueObject &valueObject) +{ + auto status = Convert2Value(env, jsValue, valueObject.value); + if (status != napi_ok) { + return napi_invalid_arg; + } + return napi_ok; +} + template<> napi_value Convert2JSValue(napi_env env, const Asset &value) { @@ -98,12 +108,18 @@ napi_value Convert2JSValue(napi_env env, const RowEntity &rowEntity) NAPI_CALL(env, napi_create_object(env, &ret)); auto &values = rowEntity.Get(); for (auto const &[key, object] : values) { - napi_value value = JSUtils::Convert2JSValue(env, object.value); + napi_value value = JSUtils::Convert2JSValue(env, object); NAPI_CALL(env, napi_set_named_property(env, ret, key.c_str(), value)); } return ret; } +template<> +napi_value Convert2JSValue(napi_env env, const ValueObject &valueObject) +{ + return JSUtils::Convert2JSValue(env, valueObject.value); +} + template<> napi_value Convert2JSValue(napi_env env, const DistributedRdb::Statistic &statistic) { diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp index ffe6f710..4adbc4b2 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp @@ -196,9 +196,14 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldArrayByName(napi_env env, napi napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); RDB_NAPI_ASSERT(env, argc == 1, std::make_shared("1")); - fieldarray = JSUtils::Convert2StrVector(env, args[0]); - RDB_NAPI_ASSERT( - env, fieldarray.size() >= 0, std::make_shared(fieldName, "a " + fieldType + " array.")); + int32_t ret = JSUtils::Convert2Value(env, args[0], fieldarray); + if (ret != napi_ok && fieldName == "devices") { + std::string field; + ret = JSUtils::Convert2Value(env, args[0], field); + RDB_NAPI_ASSERT(env, ret == napi_ok, std::make_shared(fieldName, "a " + fieldType + " array.")); + fieldarray.push_back(field); + } + RDB_NAPI_ASSERT(env, ret == napi_ok, std::make_shared(fieldName, "a " + fieldType + " array.")); RdbPredicatesProxy *proxy = nullptr; napi_unwrap(env, thiz, reinterpret_cast(&proxy)); @@ -241,7 +246,7 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseInt32FieldByName( } RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValueArray(napi_env env, napi_callback_info info, - napi_value &thiz, std::string &field, std::vector &value, const std::string valueType) + napi_value &thiz, std::string &field, std::vector &value, const std::string valueType) { size_t argc = 2; napi_value args[2] = { 0 }; @@ -251,8 +256,8 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValueArray(napi_env env, na field = JSUtils::Convert2String(env, args[0]); RDB_NAPI_ASSERT(env, !field.empty(), std::make_shared("field", "not empty")); - value = JSUtils::Convert2StrVector(env, args[1]); - RDB_NAPI_ASSERT(env, value.size() >= 0, std::make_shared("value", "a " + valueType + " array.")); + int32_t ret = JSUtils::Convert2Value(env, args[1], value); + RDB_NAPI_ASSERT(env, ret == napi_ok, std::make_shared("value", "a " + valueType + " array.")); RdbPredicatesProxy *proxy = nullptr; napi_unwrap(env, thiz, reinterpret_cast(&proxy)); @@ -261,7 +266,7 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValueArray(napi_env env, na } RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, - std::string &field, std::string &value, const std::string valueType) + std::string &field, ValueObject &value, const std::string valueType) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); size_t argc = 2; @@ -271,8 +276,30 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValue(napi_env env, napi_ca field = JSUtils::Convert2String(env, args[0]); RDB_NAPI_ASSERT(env, !field.empty(), std::make_shared("field", "not empty")); + + int32_t ret = JSUtils::Convert2Value(env, args[1], value); + RDB_NAPI_ASSERT(env, ret == napi_ok, std::make_shared("value", "a " + valueType + " array.")); + + RdbPredicatesProxy *proxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&proxy)); + RDB_NAPI_ASSERT(env, proxy && proxy->predicates_, std::make_shared("predicates", "null")); + return proxy; +} - value = JSUtils::ConvertAny2String(env, args[1]); +RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndStringValue(napi_env env, napi_callback_info info, + napi_value &thiz, std::string &field, std::string &value, const std::string valueType) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + size_t argc = 2; + napi_value args[2] = { 0 }; + napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); + RDB_NAPI_ASSERT(env, argc == 2, std::make_shared("2")); + + field = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT(env, !field.empty(), std::make_shared("field", "not empty")); + + int32_t ret = JSUtils::Convert2Value(env, args[1], value); + RDB_NAPI_ASSERT(env, ret == napi_ok, std::make_shared("value", "a string.")); RdbPredicatesProxy *proxy = nullptr; napi_unwrap(env, thiz, reinterpret_cast(&proxy)); @@ -281,7 +308,7 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValue(napi_env env, napi_ca } RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldLowAndHigh( - napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, std::string &low, std::string &high) + napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, ValueObject &low, ValueObject &high) { size_t argc = 3; napi_value args[3] = { 0 }; @@ -290,12 +317,12 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldLowAndHigh( field = JSUtils::Convert2String(env, args[0]); RDB_NAPI_ASSERT(env, !field.empty(), std::make_shared("field", "not empty")); - - low = JSUtils::ConvertAny2String(env, args[1]); - RDB_NAPI_ASSERT(env, !low.empty(), std::make_shared("low", "a non empty ValueType.")); - - high = JSUtils::ConvertAny2String(env, args[2]); - RDB_NAPI_ASSERT(env, !high.empty(), std::make_shared("high", "a non empty ValueType.")); + + int32_t ret = JSUtils::Convert2Value(env, args[1], low); + RDB_NAPI_ASSERT(env, ret == napi_ok, std::make_shared("low", "a valueType.")); + + ret = JSUtils::Convert2Value(env, args[2], high); + RDB_NAPI_ASSERT(env, ret == napi_ok, std::make_shared("high", "a valueType.")); RdbPredicatesProxy *proxy = nullptr; napi_unwrap(env, thiz, reinterpret_cast(&proxy)); @@ -309,7 +336,7 @@ napi_value RdbPredicatesProxy::EqualTo(napi_env env, napi_callback_info info) LOG_DEBUG("RdbPredicatesProxy::EqualTo begin."); napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->EqualTo(field, value); @@ -321,7 +348,7 @@ napi_value RdbPredicatesProxy::NotEqualTo(napi_env env, napi_callback_info info) LOG_DEBUG("RdbPredicatesProxy::NotEqualTo begin."); napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->NotEqualTo(field, value); @@ -378,7 +405,7 @@ napi_value RdbPredicatesProxy::Contains(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->Contains(field, value); return thiz; @@ -390,7 +417,7 @@ napi_value RdbPredicatesProxy::BeginsWith(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->BeginsWith(field, value); return thiz; @@ -402,7 +429,7 @@ napi_value RdbPredicatesProxy::EndsWith(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->EndsWith(field, value); return thiz; @@ -436,7 +463,7 @@ napi_value RdbPredicatesProxy::Like(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->Like(field, value); return thiz; @@ -448,7 +475,7 @@ napi_value RdbPredicatesProxy::Glob(napi_env env, napi_callback_info info) napi_value thiz = nullptr; std::string field = ""; std::string value = ""; - auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + auto predicatesProxy = ParseFieldAndStringValue(env, info, thiz, field, value, "string"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->Glob(field, value); return thiz; @@ -459,8 +486,8 @@ napi_value RdbPredicatesProxy::Between(napi_env env, napi_callback_info info) LOG_DEBUG("RdbPredicatesProxy::Between begin."); napi_value thiz = nullptr; std::string field = ""; - std::string low = ""; - std::string high = ""; + ValueObject low; + ValueObject high; auto predicatesProxy = ParseFieldLowAndHigh(env, info, thiz, field, low, high); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->Between(field, low, high); @@ -472,8 +499,8 @@ napi_value RdbPredicatesProxy::NotBetween(napi_env env, napi_callback_info info) LOG_DEBUG("RdbPredicatesProxy::NotBetween begin."); napi_value thiz = nullptr; std::string field = ""; - std::string low = ""; - std::string high = ""; + ValueObject low; + ValueObject high; auto predicatesProxy = ParseFieldLowAndHigh(env, info, thiz, field, low, high); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->NotBetween(field, low, high); @@ -485,7 +512,7 @@ napi_value RdbPredicatesProxy::GreaterThan(napi_env env, napi_callback_info info LOG_DEBUG("RdbPredicatesProxy::GreaterThan begin."); napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->GreaterThan(field, value); @@ -497,7 +524,7 @@ napi_value RdbPredicatesProxy::LessThan(napi_env env, napi_callback_info info) LOG_DEBUG("RdbPredicatesProxy::LessThan begin."); napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->LessThan(field, value); @@ -509,7 +536,7 @@ napi_value RdbPredicatesProxy::GreaterThanOrEqualTo(napi_env env, napi_callback_ LOG_DEBUG("RdbPredicatesProxy::GreaterThanOrEqualTo begin."); napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->GreaterThanOrEqualTo(field, value); @@ -521,7 +548,7 @@ napi_value RdbPredicatesProxy::LessThanOrEqualTo(napi_env env, napi_callback_inf LOG_DEBUG("RdbPredicatesProxy::LessThanOrEqualTo begin."); napi_value thiz = nullptr; std::string field = ""; - std::string value = ""; + ValueObject value; auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->LessThanOrEqualTo(field, value); @@ -570,10 +597,11 @@ napi_value RdbPredicatesProxy::Limit(napi_env env, napi_callback_info info) napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); RdbPredicatesProxy *predicatesProxy = GetNativePredicates(env, info); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); + //Ensure that the number of parameters is 1 or 2 RDB_NAPI_ASSERT(env, argc == 1 || argc == 2, std::make_shared("1 or 2")); - int32_t offset = 0; - int32_t limit = 0; + int32_t offset = AbsPredicates::INIT_OFFSET_VALUE; + int32_t limit = AbsPredicates::INIT_LIMIT_VALUE; if (argc == 1) { napi_status status = napi_get_value_int32(env, args[0], &limit); RDB_NAPI_ASSERT(env, status == napi_ok, std::make_shared("limit", "a number.")); @@ -594,7 +622,7 @@ napi_value RdbPredicatesProxy::Offset(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbPredicatesProxy::Offset begin."); napi_value thiz = nullptr; - int32_t offset = 0; + int32_t offset = AbsPredicates::INIT_OFFSET_VALUE; auto predicatesProxy = ParseInt32FieldByName(env, info, thiz, offset, "rowOffset"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->Offset(offset); @@ -628,7 +656,7 @@ napi_value RdbPredicatesProxy::In(napi_env env, napi_callback_info info) LOG_DEBUG("RdbPredicatesProxy::In begin."); napi_value thiz = nullptr; std::string field = ""; - std::vector values; + std::vector values; auto predicatesProxy = ParseFieldAndValueArray(env, info, thiz, field, values, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->In(field, values); @@ -640,7 +668,7 @@ napi_value RdbPredicatesProxy::NotIn(napi_env env, napi_callback_info info) LOG_DEBUG("RdbPredicatesProxy::NotIn begin."); napi_value thiz = nullptr; std::string field = ""; - std::vector values; + std::vector values; auto predicatesProxy = ParseFieldAndValueArray(env, info, thiz, field, values, "ValueType"); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); predicatesProxy->predicates_->NotIn(field, values); @@ -709,7 +737,7 @@ napi_value RdbPredicatesProxy::GetBindArgs(napi_env env, napi_callback_info info RdbPredicatesProxy *predicatesProxy = GetNativePredicates(env, info); CHECK_RETURN_NULL(predicatesProxy && predicatesProxy->predicates_); - std::vector bindArgs = predicatesProxy->predicates_->GetBindArgs(); + std::vector bindArgs = predicatesProxy->predicates_->GetBindArgs(); return JSUtils::Convert2JSValue(env, bindArgs); } diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp index d0006a3f..0d137cc5 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp @@ -43,6 +43,7 @@ using namespace OHOS::AppDataMgrJsKit; using OHOS::DistributedRdb::SubscribeMode; using OHOS::DistributedRdb::SubscribeOption; using OHOS::DistributedRdb::SyncOption; + using OHOS::DistributedRdb::SyncResult; using OHOS::DistributedRdb::Details; #endif @@ -60,8 +61,6 @@ struct RdbStoreContext : public Context { std::string tableName; std::vector tablesNames; std::string whereClause; - std::vector whereArgs; - std::vector selectionArgs; std::string sql; RdbPredicatesProxy *predicatesProxy; std::vector columns; @@ -246,41 +245,42 @@ int ParserThis(const napi_env &env, const napi_value &self, std::shared_ptr context) +int ParseTableName(const napi_env env, const napi_value arg, std::shared_ptr context) { context->tableName = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!context->tableName.empty(), std::make_shared("table", "not empty")); return OK; } -int ParseColumnName(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseColumnName(const napi_env env, const napi_value arg, std::shared_ptr context) { context->columnName = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!context->columnName.empty(), std::make_shared("columnName", "not string")); return OK; } -int ParsePrimaryKey(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParsePrimaryKey(const napi_env env, const napi_value arg, std::shared_ptr context) { JSUtils::Convert2Value(env, arg, context->keys); CHECK_RETURN_SET(!context->keys.empty(), std::make_shared("PRIKey", "not number or string")); return OK; } -int ParseDevice(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseDevice(const napi_env env, const napi_value arg, std::shared_ptr context) { context->device = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!context->device.empty(), std::make_shared("device", "not empty")); return OK; } -int ParseTablesName(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseTablesName(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->tablesNames = JSUtils::Convert2StrVector(env, arg); + int32_t ret = JSUtils::Convert2Value(env, arg, context->tablesNames); + CHECK_RETURN_SET(ret == napi_ok, std::make_shared("tablesNames", "not empty")); return OK; } -int ParseSyncModeArg(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseSyncModeArg(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_valuetype type = napi_undefined; napi_typeof(env, arg, &type); @@ -318,7 +318,7 @@ int ParseDistributedConfigArg(const napi_env &env, size_t argc, napi_value * arg return OK; } -int ParseCloudSyncModeArg(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseCloudSyncModeArg(const napi_env env, const napi_value arg, std::shared_ptr context) { auto status = JSUtils::Convert2ValueExt(env, arg, context->syncMode); bool checked = (status == napi_ok && context->syncMode >= DistributedRdb::TIME_FIRST @@ -327,7 +327,7 @@ int ParseCloudSyncModeArg(const napi_env &env, const napi_value &arg, std::share return OK; } -int ParseCallback(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseCallback(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_valuetype valueType = napi_undefined; napi_status status = napi_typeof(env, arg, &valueType); @@ -337,7 +337,7 @@ int ParseCallback(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseCloudSyncCallback(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_valuetype valueType = napi_undefined; napi_typeof(env, arg, &valueType); @@ -346,7 +346,7 @@ int ParseCloudSyncCallback(const napi_env &env, const napi_value &arg, std::shar return OK; } -int ParsePredicates(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParsePredicates(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_unwrap(env, arg, reinterpret_cast(&context->predicatesProxy)); CHECK_RETURN_SET(context->predicatesProxy != nullptr, @@ -356,7 +356,7 @@ int ParsePredicates(const napi_env &env, const napi_value &arg, std::shared_ptr< return OK; } -int ParseDataSharePredicates(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseDataSharePredicates(const napi_env env, const napi_value arg, std::shared_ptr context) { #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) RdbStoreProxy *obj = reinterpret_cast(context->boundObj); @@ -373,53 +373,73 @@ int ParseDataSharePredicates(const napi_env &env, const napi_value &arg, std::sh return OK; } -int ParseNewKey(const napi_env &env, const napi_value &arg, std::shared_ptr context) -{ - context->newKey = JSUtils::Convert2U8Vector(env, arg); - return OK; -} - -int ParseSrcName(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseSrcName(const napi_env env, const napi_value arg, std::shared_ptr context) { context->srcName = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!context->srcName.empty(), std::make_shared("srcName", "not empty")); return OK; } -int ParseColumns(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseColumns(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->columns = JSUtils::Convert2StrVector(env, arg); + napi_valuetype type; + napi_typeof(env, arg, &type); + if (type == napi_undefined || type == napi_null) { + return OK; + } + int32_t ret = JSUtils::Convert2Value(env, arg, context->columns); + CHECK_RETURN_SET(ret == napi_ok, std::make_shared("columns", "a string array")); return OK; } -int ParseAlias(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseAlias(const napi_env env, const napi_value arg, std::shared_ptr context) { context->aliasName = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!context->aliasName.empty(), std::make_shared("aliasName", "not empty")); return OK; } -int ParsePath(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParsePath(const napi_env env, const napi_value arg, std::shared_ptr context) { context->pathName = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!context->pathName.empty(), std::make_shared("pathName", "not empty")); return OK; } -int ParseSelectionArgs(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseBindArgs(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->selectionArgs = JSUtils::Convert2StrVector(env, arg); + context->bindArgs.clear(); + napi_valuetype type; + napi_typeof(env, arg, &type); + if (type == napi_undefined || type == napi_null) { + return OK; + } + bool isArray = false; + napi_status status = napi_is_array(env, arg, &isArray); + CHECK_RETURN_SET(status == napi_ok && isArray, std::make_shared("values", "a BindArgs array.")); + + uint32_t arrLen = 0; + status = napi_get_array_length(env, arg, &arrLen); + CHECK_RETURN_SET(status == napi_ok, std::make_shared("values", "not empty.")); + for (size_t i = 0; i < arrLen; ++i) { + napi_value element; + napi_get_element(env, arg, i, &element); + ValueObject valueObject; + int32_t ret = JSUtils::Convert2Value(env, element, valueObject.value); + CHECK_RETURN_SET(ret == OK, std::make_shared(std::to_string(i), "ValueObject")); + context->bindArgs.push_back(std::move(valueObject)); + } return OK; } -int ParseSql(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseSql(const napi_env env, const napi_value arg, std::shared_ptr context) { - context->sql = JSUtils::Convert2String(env, arg, false); + context->sql = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!context->sql.empty(), std::make_shared("sql", "not empty")); return OK; } -int ParseValuesBucket(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseValuesBucket(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_value keys = 0; napi_get_property_names(env, arg, &keys); @@ -437,15 +457,15 @@ int ParseValuesBucket(const napi_env &env, const napi_value &arg, std::shared_pt ValueObject valueObject; int32_t ret = JSUtils::Convert2Value(env, value, valueObject.value); if (ret == napi_ok) { - context->valuesBucket.Put(keyStr, std::move(valueObject)); + context->valuesBucket.Put(keyStr, valueObject); } else { - LOG_WARN("bad value type of key %{public}s", keyStr.c_str()); + LOG_WARN("bad value type of key %{public}s", keyStr.c_str()); // TD: need to throw error here } } return OK; } -int ParseValuesBuckets(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseValuesBuckets(const napi_env env, const napi_value arg, std::shared_ptr context) { bool isArray = false; napi_is_array(env, arg, &isArray); @@ -467,7 +487,7 @@ int ParseValuesBuckets(const napi_env &env, const napi_value &arg, std::shared_p return OK; } -int ParseConflictResolution(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParseConflictResolution(const napi_env env, const napi_value arg, std::shared_ptr context) { int32_t conflictResolution = 0; napi_get_value_int32(env, arg, &conflictResolution); @@ -587,7 +607,7 @@ napi_value RdbStoreProxy::Update(napi_env env, napi_callback_info info) CHECK_RETURN_ERR(obj != nullptr && obj->rdbStore_ != nullptr); CHECK_RETURN_ERR(context->rdbPredicates != nullptr); return obj->rdbStore_->UpdateWithConflictResolution(context->intOutput, context->tableName, - context->valuesBucket, context->rdbPredicates->GetWhereClause(), context->rdbPredicates->GetWhereArgs(), + context->valuesBucket, context->rdbPredicates->GetWhereClause(), context->rdbPredicates->GetBindArgs(), context->conflictResolution); }; auto output = [context](napi_env env, napi_value &result) { @@ -680,29 +700,15 @@ napi_value RdbStoreProxy::QuerySql(napi_env env, napi_callback_info info) CHECK_RETURN(OK == ParserThis(env, self, context)); CHECK_RETURN(OK == ParseSql(env, argv[0], context)); if (argc == 2) { -#if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - CHECK_RETURN(OK == ParseColumns(env, argv[1], context)); -#else - CHECK_RETURN(OK == ParseSelectionArgs(env, argv[1], context)); -#endif + CHECK_RETURN(OK == ParseBindArgs(env, argv[1], context)); } }; auto exec = [context]() -> int { RdbStoreProxy *obj = reinterpret_cast(context->boundObj); -#if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - CHECK_RETURN_ERR(obj != nullptr && obj->rdbStore_ != nullptr); - context->resultSet_value = obj->rdbStore_->QueryByStep(context->sql, context->columns); - LOG_ERROR("RdbStoreProxy::QuerySql is nullptr ? %{public}d ", context->resultSet_value == nullptr); -#endif - std::string selectionArgs = ","; - for (size_t i = 0; i < context->selectionArgs.size(); i++) { - selectionArgs += context->selectionArgs[i]; - } -#if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) - context->resultSet_value = obj->rdbStore_->QueryByStep(context->sql, context->selectionArgs); - LOG_ERROR("RdbStoreProxy::QuerySql is nullptr ? %{public}d ", context->resultSet_value == nullptr); +#if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) || defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) + context->resultSet_value = obj->rdbStore_->QueryByStep(context->sql, context->bindArgs); #else - context->resultSet_value = obj->rdbStore_->QuerySql(context->sql, context->selectionArgs); + context->resultSet_value = obj->rdbStore_->QuerySql(context->sql, context->bindArgs); #endif return (context->resultSet_value != nullptr) ? E_OK : E_ERROR; }; @@ -716,32 +722,6 @@ napi_value RdbStoreProxy::QuerySql(napi_env env, napi_callback_info info) return AsyncCall::Call(env, context); } -int ParseBindArgs(const napi_env &env, const napi_value &arg, std::shared_ptr context) -{ - context->bindArgs.clear(); - napi_valuetype type; - napi_typeof(env, arg, &type); - if (type == napi_undefined || type == napi_null) { - return OK; - } - bool isArray = false; - napi_status status = napi_is_array(env, arg, &isArray); - CHECK_RETURN_SET(status == napi_ok && isArray, std::make_shared("values", "a BindArgs array.")); - - uint32_t arrLen = 0; - status = napi_get_array_length(env, arg, &arrLen); - CHECK_RETURN_SET(status == napi_ok, std::make_shared("values", "not empty.")); - for (size_t i = 0; i < arrLen; ++i) { - napi_value element; - napi_get_element(env, arg, i, &element); - ValueObject valueObject; - int32_t ret = JSUtils::Convert2Value(env, element, valueObject.value); - CHECK_RETURN_SET(ret == OK, std::make_shared(std::to_string(i), "ValueObject")); - context->bindArgs.push_back(std::move(valueObject)); - } - return OK; -} - napi_value RdbStoreProxy::ExecuteSql(napi_env env, napi_callback_info info) { auto context = std::make_shared(); @@ -847,7 +827,6 @@ napi_value RdbStoreProxy::Attach(napi_env env, napi_callback_info info) CHECK_RETURN(OK == ParserThis(env, self, context)); CHECK_RETURN(OK == ParseAlias(env, argv[0], context)); CHECK_RETURN(OK == ParsePath(env, argv[1], context)); - CHECK_RETURN(OK == ParseNewKey(env, argv[2], context)); }; auto exec = [context]() -> int { RdbStoreProxy *obj = reinterpret_cast(context->boundObj); @@ -1285,20 +1264,30 @@ napi_value RdbStoreProxy::OffRemote(napi_env env, size_t argc, napi_value *argv) bool valid = (mode >= 0 && mode < SubscribeMode::SUBSCRIBE_MODE_MAX); RDB_NAPI_ASSERT(env, valid, std::make_shared("type", "SubscribeType")); - napi_typeof(env, argv[1], &type); - RDB_NAPI_ASSERT(env, type == napi_function, std::make_shared("observer", "function")); + bool isNotNull = argc >=2 && !JSUtils::IsNull(env, argv[1]); + if (isNotNull) { + napi_typeof(env, argv[1], &type); + RDB_NAPI_ASSERT(env, type == napi_function, std::make_shared("observer", "function")); + } SubscribeOption option; option.mode = static_cast(mode); std::lock_guard lockGuard(mutex_); - for (auto it = observers_[mode].begin(); it != observers_[mode].end(); it++) { - if (*it != nullptr && **it == argv[1]) { - int errCode = rdbStore_->UnSubscribe(option, it->get()); - RDB_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); - observers_[mode].erase(it); - LOG_INFO("observer unsubscribe success"); - return nullptr; + for (auto it = observers_[mode].begin(); it != observers_[mode].end();) { + if (*it == nullptr) { + it = observers_[mode].erase(it); + continue; } + if (isNotNull && !(**it == argv[1])) { + ++it; + continue; + } + + int errCode = rdbStore_->UnSubscribe(option, it->get()); + RDB_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); + it = observers_[mode].erase(it); + LOG_INFO("observer unsubscribe success"); + return nullptr; } LOG_INFO("observer not found"); return nullptr; @@ -1368,7 +1357,7 @@ napi_value RdbStoreProxy::OnEvent(napi_env env, napi_callback_info info) napi_typeof(env, argv[0], &type); RDB_NAPI_ASSERT(env, type == napi_string, std::make_shared("event", "string")); - std::string event = JSUtils::Convert2String(env, argv[0], false); + std::string event = JSUtils::Convert2String(env, argv[0]); RDB_NAPI_ASSERT(env, !event.empty(), std::make_shared("event", "a not empty string.")); // 'argv[2]' represents a callback function napi_typeof(env, argv[2], &type); @@ -1408,7 +1397,7 @@ napi_value RdbStoreProxy::OffEvent(napi_env env, napi_callback_info info) bool valueBool = false; napi_get_value_bool(env, argv[1], &valueBool); - std::string event = JSUtils::Convert2String(env, argv[0], false); + std::string event = JSUtils::Convert2String(env, argv[0]); RDB_NAPI_ASSERT(env, !event.empty(), std::make_shared("event", "a not empty string.")); // 'argc == 3' represents determine whether the value of variable 'argc' is equal to '3' @@ -1445,4 +1434,4 @@ napi_value RdbStoreProxy::Notify(napi_env env, napi_callback_info info) } #endif } // namespace RelationalStoreJsKit -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp index 9e8b40a7..65ad7cab 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store_helper.cpp @@ -166,7 +166,7 @@ int ParseStoreConfig(const napi_env &env, const napi_value &object, std::shared_ return OK; } -int ParsePath(const napi_env &env, const napi_value &arg, std::shared_ptr context) +int ParsePath(const napi_env env, const napi_value arg, std::shared_ptr context) { std::string path = JSUtils::Convert2String(env, arg); CHECK_RETURN_SET(!path.empty(), std::make_shared("name", "a without path non empty string.")); diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_result_set.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_result_set.cpp index 909d2cb3..0f16b07f 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_result_set.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_result_set.cpp @@ -69,7 +69,7 @@ std::shared_ptr ResultSetProxy::Create() LOG_ERROR("resultSet is null"); return nullptr; } - return std::make_shared(resultSet_); + return std::make_shared(std::move(resultSet_)); } #endif @@ -190,7 +190,7 @@ ResultSetProxy *ResultSetProxy::ParseInt32FieldByName( ResultSetProxy *proxy = nullptr; napi_unwrap(env, self, reinterpret_cast(&proxy)); - RDB_NAPI_ASSERT(env, proxy && proxy->resultSet_, std::make_shared("resultSet", "null")); + RDB_NAPI_ASSERT(env, proxy && proxy->resultSet_, std::make_shared("resultSet", "not null")); return proxy; } @@ -208,7 +208,7 @@ ResultSetProxy *ResultSetProxy::ParseFieldByName( ResultSetProxy *proxy = nullptr; napi_unwrap(env, self, reinterpret_cast(&proxy)); - RDB_NAPI_ASSERT(env, proxy && proxy->resultSet_, std::make_shared("resultSet", "null")); + RDB_NAPI_ASSERT(env, proxy && proxy->resultSet_, std::make_shared("resultSet", "not null")); return proxy; } diff --git a/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp b/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp index 64a4b269..b28a96f6 100644 --- a/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp +++ b/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp @@ -31,6 +31,8 @@ namespace OHOS { namespace AppDataFwk { using namespace OHOS::Rdb; +#define LIKELY(x) __builtin_expect(!!(x), 1) +#define UNLIKELY(x) __builtin_expect(!!(x), 0) SharedBlock::SharedBlock(const std::string &name, sptr ashmem, size_t size, bool readOnly) : mName(name), ashmem_(ashmem), mSize(size), mReadOnly(readOnly), mHeader(nullptr) { @@ -44,20 +46,10 @@ SharedBlock::~SharedBlock() } } -std::u16string SharedBlock::ToUtf16(std::string str) -{ - return OHOS::Str8ToStr16(str); -} - -std::string SharedBlock::ToUtf8(std::u16string str16) -{ - return OHOS::Str16ToStr8(str16); -} - bool SharedBlock::Init() { - mData = const_cast(ashmem_->ReadFromAshmem(sizeof(SharedBlockHeader), 0)); - mHeader = static_cast(mData); + mData = static_cast(const_cast(ashmem_->ReadFromAshmem(sizeof(SharedBlockHeader), 0))); + mHeader = reinterpret_cast(mData); if (mHeader == nullptr) { return false; } @@ -110,29 +102,29 @@ int SharedBlock::Create(const std::string &name, size_t size, SharedBlock *&outS int SharedBlock::WriteMessageParcel(MessageParcel &parcel) { - return parcel.WriteString16(ToUtf16(mName)) && parcel.WriteAshmem(ashmem_); + return parcel.WriteString16(OHOS::Str8ToStr16(mName)) && parcel.WriteAshmem(ashmem_); } int SharedBlock::ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block) { - std::string name = ToUtf8(parcel.ReadString16()); + std::string name = OHOS::Str16ToStr8(parcel.ReadString16()); sptr ashmem = parcel.ReadAshmem(); - if (ashmem == nullptr) { + if (UNLIKELY(ashmem == nullptr)) { LOG_ERROR("ReadMessageParcel: No ashmem in the parcel."); return SHARED_BLOCK_BAD_VALUE; } bool ret = ashmem->MapReadAndWriteAshmem(); - if (!ret) { + if (UNLIKELY(!ret)) { LOG_ERROR("ReadMessageParcel: MapReadAndWriteAshmem function error."); ashmem->CloseAshmem(); return SHARED_BLOCK_SET_PORT_ERROR; } block = new (std::nothrow) SharedBlock(name, ashmem, ashmem->GetAshmemSize(), true); - if (block == nullptr) { + if (UNLIKELY(block == nullptr)) { LOG_ERROR("ReadMessageParcel new SharedBlock error."); return SHARED_BLOCK_BAD_VALUE; } - if (block->Init() == false) { + if (UNLIKELY(block->Init() == false)) { delete block; LOG_ERROR("ReadMessageParcel: mHeader is null."); return SHARED_BLOCK_ASHMEM_ERROR; @@ -148,34 +140,27 @@ int SharedBlock::ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block) int SharedBlock::Clear() { - if (mReadOnly) { + if (UNLIKELY(mReadOnly)) { return SHARED_BLOCK_INVALID_OPERATION; } - if (mHeader == nullptr) { - LOG_ERROR("SharedBlock::Clear mHeader is nullptr"); - return SHARED_BLOCK_BAD_VALUE; - } - - mHeader->unusedOffset = sizeof(SharedBlockHeader) + sizeof(RowGroupHeader); - mHeader->firstRowGroupOffset = sizeof(SharedBlockHeader); - mHeader->rowNums = 0; - mHeader->columnNums = 0; - mHeader->startPos_ = 0; - mHeader->lastPos_ = 0; - mHeader->blockPos_ = 0; - - RowGroupHeader *firstGroup = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); - if (!firstGroup) { - LOG_ERROR("Failed to get group in clear()."); - return SHARED_BLOCK_BAD_VALUE; + if (LIKELY(mHeader != nullptr)) { + mHeader->unusedOffset = sizeof(SharedBlockHeader) + sizeof(RowGroupHeader); + mHeader->rowNums = 0; + mHeader->columnNums = 0; + mHeader->startPos_ = 0; + mHeader->lastPos_ = 0; + mHeader->blockPos_ = 0; + memset_s(mHeader->groupOffset, sizeof(mHeader->groupOffset), 0, sizeof(mHeader->groupOffset)); + mHeader->groupOffset[0] = sizeof(SharedBlockHeader); + return SHARED_BLOCK_OK; } - firstGroup->nextGroupOffset = 0; - return SHARED_BLOCK_OK; + LOG_ERROR("SharedBlock::Clear mHeader is nullptr"); + return SHARED_BLOCK_BAD_VALUE; } int SharedBlock::SetColumnNum(uint32_t numColumns) { - if (mReadOnly) { + if (UNLIKELY(mReadOnly)) { return SHARED_BLOCK_INVALID_OPERATION; } @@ -194,13 +179,9 @@ int SharedBlock::SetColumnNum(uint32_t numColumns) int SharedBlock::AllocRow() { - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - /* Fill in the row offset */ uint32_t *rowOffset = AllocRowOffset(); - if (rowOffset == nullptr) { + if (UNLIKELY(rowOffset == nullptr)) { return SHARED_BLOCK_NO_MEMORY; } @@ -208,34 +189,20 @@ int SharedBlock::AllocRow() size_t fieldDirSize = mHeader->columnNums * sizeof(CellUnit); /* Aligned */ - uint32_t fieldDirOffset = Alloc(fieldDirSize, true); - if (!fieldDirOffset) { + uint32_t fieldDirOffset = Alloc(fieldDirSize); + if (UNLIKELY(!fieldDirOffset)) { mHeader->rowNums--; - LOG_INFO("Alloc the row failed, so back out the new row accounting from allocRowoffset %{public}" PRIu32 "", + LOG_INFO("Alloc the row size %{public}u failed, roll back row number %{public}u", fieldDirOffset, mHeader->rowNums); return SHARED_BLOCK_NO_MEMORY; } - CellUnit *fieldDir = static_cast(OffsetToPtr(fieldDirOffset)); - if (fieldDir == nullptr) { - return SHARED_BLOCK_BAD_VALUE; - } - int result = memset_s(fieldDir, fieldDirSize, 0, fieldDirSize); - if (result != 0) { - LOG_ERROR("Set memory failed"); - return SHARED_BLOCK_NO_MEMORY; - } - *rowOffset = fieldDirOffset; return SHARED_BLOCK_OK; } int SharedBlock::FreeLastRow() { - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - if (mHeader->rowNums > 0) { mHeader->rowNums--; } @@ -243,108 +210,55 @@ int SharedBlock::FreeLastRow() return SHARED_BLOCK_OK; } -uint32_t SharedBlock::Alloc(size_t size, bool aligned) +uint32_t SharedBlock::Alloc(size_t size) { /* Number of unused offsets in the header */ uint32_t offsetDigit = 3; - uint32_t padding = aligned ? (~mHeader->unusedOffset + 1) & offsetDigit : 0; - uint32_t offset = mHeader->unusedOffset + padding; - uint32_t nextFreeOffset; - - if (offset + size > mSize) { + uint32_t offset = mHeader->unusedOffset + ((~mHeader->unusedOffset + 1) & offsetDigit); + uint32_t nextFreeOffset = offset + size; + if (UNLIKELY(nextFreeOffset > mSize)) { LOG_ERROR("SharedBlock is full: requested allocation %{public}zu bytes," " free space %{public}zu bytes, block size %{public}zu bytes", size, mSize - mHeader->unusedOffset, mSize); return 0; } - nextFreeOffset = offset + size; mHeader->unusedOffset = nextFreeOffset; return offset; } -uint32_t *SharedBlock::GetRowOffset(uint32_t row) -{ - uint32_t rowPos = row; - - RowGroupHeader *group = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in getRowOffset()."); - return nullptr; - } - - while (rowPos >= ROW_OFFSETS_NUM) { - group = static_cast(OffsetToPtr(group->nextGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset) when while loop."); - return nullptr; - } - rowPos -= ROW_OFFSETS_NUM; - } - - return &group->rowOffsets[rowPos]; -} - uint32_t *SharedBlock::AllocRowOffset() { - uint32_t rowPos = mHeader->rowNums; - - RowGroupHeader *group = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in allocRowOffset()."); + uint32_t groupPos = mHeader->rowNums / ROW_NUM_IN_A_GROUP; + if (UNLIKELY(groupPos >= GROUP_NUM)) { + LOG_ERROR("rows is full. row number %{public}u, groupPos %{public}u", mHeader->rowNums, groupPos); return nullptr; } - - while (rowPos > ROW_OFFSETS_NUM) { - group = static_cast(OffsetToPtr(group->nextGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset) when while loop."); + if (mHeader->groupOffset[groupPos] == 0) { + mHeader->groupOffset[groupPos] = Alloc(sizeof(RowGroupHeader)); + if (UNLIKELY(mHeader->groupOffset[groupPos] == 0)) { return nullptr; } - rowPos -= ROW_OFFSETS_NUM; - } - if (rowPos == ROW_OFFSETS_NUM) { - if (!group->nextGroupOffset) { - /* Aligned */ - group->nextGroupOffset = Alloc(sizeof(RowGroupHeader), true); - if (!group->nextGroupOffset) { - return nullptr; - } - } - group = static_cast(OffsetToPtr(group->nextGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset)."); - return nullptr; - } - group->nextGroupOffset = 0; - rowPos = 0; } + uint32_t rowPos = mHeader->rowNums % ROW_NUM_IN_A_GROUP; + RowGroupHeader *group = static_cast(OffsetToPtr(mHeader->groupOffset[groupPos])); mHeader->rowNums += 1; - return &group->rowOffsets[rowPos]; + return group->rowOffsets + rowPos; } SharedBlock::CellUnit *SharedBlock::GetCellUnit(uint32_t row, uint32_t column) { - if (row >= mHeader->rowNums || column >= mHeader->columnNums) { + if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", row, column, mHeader->rowNums, mHeader->columnNums); return nullptr; } - uint32_t *rowOffset = GetRowOffset(row); - if (!rowOffset) { - LOG_ERROR("Failed to find rowOffset for row %{public}" PRIu32 ".", row); - return nullptr; - } - - CellUnit *cellUnit = static_cast(OffsetToPtr(*rowOffset)); - if (!cellUnit) { - LOG_ERROR("Failed to find cellUnit for rowOffset %{public}" PRIu32 ".", *rowOffset); - return nullptr; - } - - return &cellUnit[column]; + uint32_t groupPos = row / ROW_NUM_IN_A_GROUP; + uint32_t rowPos = row % ROW_NUM_IN_A_GROUP; + RowGroupHeader *group = reinterpret_cast(mData + mHeader->groupOffset[groupPos]); + return reinterpret_cast(mData + group->rowOffsets[rowPos]) + column; } int SharedBlock::PutBlob(uint32_t row, uint32_t column, const void *value, size_t size) @@ -369,28 +283,26 @@ int SharedBlock::PutAssets(uint32_t row, uint32_t column, const void *value, siz int SharedBlock::PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type) { - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { + if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { + LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + row, column, mHeader->rowNums, mHeader->columnNums); return SHARED_BLOCK_BAD_VALUE; } - - uint32_t offset = Alloc(size); - if (!offset) { - return SHARED_BLOCK_NO_MEMORY; - } - - void *ptr = OffsetToPtr(offset); - if (!ptr) { + uint32_t groupPos = row / ROW_NUM_IN_A_GROUP; + uint32_t rowPos = row % ROW_NUM_IN_A_GROUP; + RowGroupHeader *group = reinterpret_cast(mData + mHeader->groupOffset[groupPos]); + CellUnit *cellUnit = reinterpret_cast(mData + group->rowOffsets[rowPos]) + column; + uint32_t offset = mHeader->unusedOffset; + uint32_t end = offset + size; + if (UNLIKELY(end > mSize)) { return SHARED_BLOCK_NO_MEMORY; } + mHeader->unusedOffset = end; if (size != 0) { - errno_t result = memcpy_s(ptr, size, value, size); - if (result != EOK) { + errno_t result = memcpy_s(mData + offset, size, value, size); + if (UNLIKELY(result != EOK)) { return SHARED_BLOCK_NO_MEMORY; } } @@ -403,15 +315,17 @@ int SharedBlock::PutBlobOrString(uint32_t row, uint32_t column, const void *valu int SharedBlock::PutLong(uint32_t row, uint32_t column, int64_t value) { - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { + if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { + LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + row, column, mHeader->rowNums, mHeader->columnNums); return SHARED_BLOCK_BAD_VALUE; } + uint32_t groupPos = row / ROW_NUM_IN_A_GROUP; + uint32_t rowPos = row % ROW_NUM_IN_A_GROUP; + RowGroupHeader *group = reinterpret_cast(mData + mHeader->groupOffset[groupPos]); + CellUnit *cellUnit = reinterpret_cast(mData + group->rowOffsets[rowPos]) + column; cellUnit->type = CELL_UNIT_TYPE_INTEGER; cellUnit->cell.longValue = value; return SHARED_BLOCK_OK; @@ -419,15 +333,17 @@ int SharedBlock::PutLong(uint32_t row, uint32_t column, int64_t value) int SharedBlock::PutDouble(uint32_t row, uint32_t column, double value) { - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { + if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { + LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + row, column, mHeader->rowNums, mHeader->columnNums); return SHARED_BLOCK_BAD_VALUE; } + uint32_t groupPos = row / ROW_NUM_IN_A_GROUP; + uint32_t rowPos = row % ROW_NUM_IN_A_GROUP; + RowGroupHeader *group = reinterpret_cast(mData + mHeader->groupOffset[groupPos]); + CellUnit *cellUnit = reinterpret_cast(mData + group->rowOffsets[rowPos]) + column; cellUnit->type = CELL_UNIT_TYPE_FLOAT; cellUnit->cell.doubleValue = value; return SHARED_BLOCK_OK; @@ -435,15 +351,18 @@ int SharedBlock::PutDouble(uint32_t row, uint32_t column, double value) int SharedBlock::PutNull(uint32_t row, uint32_t column) { - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { + if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { + LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + row, column, mHeader->rowNums, mHeader->columnNums); return SHARED_BLOCK_BAD_VALUE; } + uint32_t groupPos = row / ROW_NUM_IN_A_GROUP; + uint32_t rowPos = row % ROW_NUM_IN_A_GROUP; + RowGroupHeader *group = reinterpret_cast(mData + mHeader->groupOffset[groupPos]); + CellUnit *cellUnit = reinterpret_cast(mData + group->rowOffsets[rowPos]) + column; + cellUnit->type = CELL_UNIT_TYPE_NULL; cellUnit->cell.stringOrBlobValue.offset = 0; cellUnit->cell.stringOrBlobValue.size = 0; @@ -452,38 +371,20 @@ int SharedBlock::PutNull(uint32_t row, uint32_t column) size_t SharedBlock::SetRawData(const void *rawData, size_t size) { - if (size <= 0) { + if (UNLIKELY(size <= 0)) { LOG_ERROR("SharedBlock rawData is less than or equal to 0M"); return SHARED_BLOCK_INVALID_OPERATION; } - if (size > mSize) { + if (UNLIKELY(size > mSize)) { LOG_ERROR("SharedBlock size is %{public}zu, current byteArray size is %{public}zu", mSize, size); return SHARED_BLOCK_NO_MEMORY; } int result = memcpy_s(mHeader, mSize, rawData, size); - if (result != 0) { + if (UNLIKELY(result != 0)) { return SHARED_BLOCK_NO_MEMORY; } return SHARED_BLOCK_OK; } - -void *SharedBlock::OffsetToPtr(uint32_t offset, uint32_t bufferSize) -{ - if (offset >= mSize) { - LOG_ERROR("Offset %{public}" PRIu32 " out of bounds, max value %{public}zu", offset, mSize); - return nullptr; - } - if (offset + bufferSize > mSize) { - LOG_ERROR("End offset %{public}" PRIu32 " out of bounds, max value %{public}zu", offset + bufferSize, mSize); - return nullptr; - } - return static_cast(mData) + offset; -} - -uint32_t SharedBlock::OffsetFromPtr(void *ptr) -{ - return static_cast(ptr) - static_cast(mData); -} } // namespace AppDataFwk } // namespace OHOS diff --git a/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp b/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp index d11b766f..75489df2 100644 --- a/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp +++ b/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp @@ -14,6 +14,9 @@ */ #include "data_ability_predicates.h" + +#include + #include "predicates_utils.h" namespace OHOS { @@ -31,7 +34,7 @@ DataAbilityPredicates::DataAbilityPredicates(const std::string &rawSelection) : AbsPredicates::SetWhereClause(rawSelection); } -DataAbilityPredicates::DataAbilityPredicates(OHOS::Parcel *source) +DataAbilityPredicates::DataAbilityPredicates(OHOS::Parcel *source) : isRawSelection(false), judgeSource(true) { if (source == nullptr) { this->judgeSource = false; @@ -46,9 +49,14 @@ DataAbilityPredicates::DataAbilityPredicates(OHOS::Parcel *source) std::string index = (source->ReadInt32() != g_invalidObjectFlag) ? source->ReadString() : ""; std::string group = (source->ReadInt32() != g_invalidObjectFlag) ? source->ReadString() : ""; std::string order = (source->ReadInt32() != g_invalidObjectFlag) ? source->ReadString() : ""; - int limit = (source->ReadInt32() != g_invalidObjectFlag) ? source->ReadInt32() : -1; - int offset = (source->ReadInt32() != g_invalidObjectFlag) ? source->ReadInt32() : -1; - PredicatesUtils::SetWhereClauseAndArgs(this, whereClause, whereArgs); + int limit = (source->ReadInt32() != g_invalidObjectFlag) ? source->ReadInt32() + : AbsPredicates::INIT_LIMIT_VALUE; + int offset = (source->ReadInt32() != g_invalidObjectFlag) ? source->ReadInt32() + : AbsPredicates::INIT_OFFSET_VALUE; + std::vector bindArgs; + std::for_each( + whereArgs.begin(), whereArgs.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + PredicatesUtils::SetWhereClauseAndArgs(this, whereClause, bindArgs); PredicatesUtils::SetAttributes(this, isDistinct, index, group, order, limit, offset); } } @@ -80,13 +88,13 @@ bool DataAbilityPredicates::Marshalling(OHOS::Parcel &parcel) const int limit = GetLimit(); int offset = GetOffset(); - if (limit != -1) { + if (limit != INIT_LIMIT_VALUE) { parcel.WriteInt32(g_validObjectFlag); parcel.WriteInt32(limit); } else { parcel.WriteInt32(g_invalidObjectFlag); } - if (offset != -1) { + if (offset != INIT_OFFSET_VALUE) { parcel.WriteInt32(g_validObjectFlag); parcel.WriteInt32(offset); } else { diff --git a/relational_store/frameworks/native/dataability/src/predicates_utils.cpp b/relational_store/frameworks/native/dataability/src/predicates_utils.cpp index 7db3d2cf..22f04299 100644 --- a/relational_store/frameworks/native/dataability/src/predicates_utils.cpp +++ b/relational_store/frameworks/native/dataability/src/predicates_utils.cpp @@ -19,22 +19,35 @@ namespace OHOS { namespace NativeRdb { -PredicatesUtils::PredicatesUtils() {} +PredicatesUtils::PredicatesUtils() +{ +} + /** - * Set the param of whereClause and whereArgs of the specified Predicates. + * Set the param of whereClause and bindArgs of the specified Predicates. */ -void PredicatesUtils::SetWhereClauseAndArgs(AbsPredicates *predicates, std::string whereClause, - std::vector whereArgs) +void PredicatesUtils::SetWhereClauseAndArgs( + AbsPredicates *predicates, const std::string &whereClause, const std::vector &whereArgs) { predicates->SetWhereClause(whereClause); predicates->SetWhereArgs(whereArgs); } +/** + * Set the param of whereClause and bindArgs of the specified Predicates. + */ +void PredicatesUtils::SetWhereClauseAndArgs(AbsPredicates *predicates, const std::string &whereClause, + const std::vector &bindArgs) +{ + predicates->SetWhereClause(whereClause); + predicates->SetBindArgs(bindArgs); +} + /** * Sets params of the specified Predicates including distinct, index, group, order, limit and offset. */ -void PredicatesUtils::SetAttributes(AbsPredicates *predicates, bool isDistinct, std::string index, std::string group, - std::string order, int limit, int offset) +void PredicatesUtils::SetAttributes(AbsPredicates *predicates, bool isDistinct, const std::string &index, + const std::string &group, const std::string &order, const int limit, const int offset) { if (isDistinct) { predicates->Distinct(); @@ -44,13 +57,6 @@ void PredicatesUtils::SetAttributes(AbsPredicates *predicates, bool isDistinct, } if (!group.empty()) { std::vector groupArray; - std::string::size_type startpos = 0; - while (startpos != std::string::npos) { - startpos = group.find('`'); - if (startpos != std::string::npos) { - group.replace(startpos, 1, ""); - } - } std::istringstream iss(group); std::string temp; while (getline(iss, temp, ',')) { @@ -61,10 +67,10 @@ void PredicatesUtils::SetAttributes(AbsPredicates *predicates, bool isDistinct, if (!order.empty()) { predicates->SetOrder(order); } - if (limit != -1) { + if (limit != AbsPredicates::INIT_LIMIT_VALUE) { predicates->Limit(limit); } - if (offset != -1) { + if (offset != AbsPredicates::INIT_OFFSET_VALUE) { predicates->Offset(offset); } } diff --git a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h index ef7d18cd..fff5d1bd 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h +++ b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h @@ -26,8 +26,12 @@ namespace OHOS::DistributedRdb { class RdbServiceProxy : public IRemoteProxy { public: - using ObserverMapValue = std::pair, RdbSyncerParam>; - using ObserverMap = ConcurrentMap; + struct ObserverParam { + RdbStoreObserver *observer = nullptr; + std::string bundleName; + SubscribeOption subscribeOption{ SubscribeMode::REMOTE }; + }; + using Observers = ConcurrentMap>; explicit RdbServiceProxy(const sptr& object); @@ -51,11 +55,13 @@ public: int32_t RemoteQuery(const RdbSyncerParam& param, const std::string& device, const std::string& sql, const std::vector& selectionArgs, sptr& resultSet) override; - ObserverMap ExportObservers(); + Observers ExportObservers(); - void ImportObservers(ObserverMap& observers); + void ImportObservers(Observers & observers); int32_t GetSchema(const RdbSyncerParam ¶m) override; + + int32_t Delete(const RdbSyncerParam ¶m) override; private: using ChangeInfo = RdbStoreObserver::ChangeInfo; using PrimaryFields = RdbStoreObserver::PrimaryFields; @@ -85,7 +91,7 @@ private: std::atomic seqNum_ {}; ConcurrentMap syncCallbacks_; - ObserverMap observers_; + Observers observers_; sptr notifier_; sptr remote_; diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h index 1112a61e..60ccb319 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h @@ -81,17 +81,26 @@ public: ConflictResolution conflictResolution) override; int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, const std::vector &whereArgs) override; + int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, + const std::vector &bindArgs) override; int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, const std::vector &whereArgs, ConflictResolution conflictResolution) override; + int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &bindArgs, + ConflictResolution conflictResolution) override; int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, const std::vector &whereArgs) override; + int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &bindArgs) override; std::shared_ptr Query(int &errCode, bool distinct, const std::string &table, const std::vector &columns, - const std::string &selection, const std::vector &selectionArgs, const std::string &groupBy, - const std::string &having, const std::string &orderBy, const std::string &limit) override; + const std::string &whereClause, const std::vector &bindArgs, const std::string &groupBy, + const std::string &indexName, const std::string &orderBy, const int &limit, const int &offset) override; + std::shared_ptr QuerySql(const std::string &sql, + const std::vector &sqlArgs) override; std::shared_ptr QuerySql(const std::string &sql, - const std::vector &selectionArgs) override; + const std::vector &bindArgs) override; int ExecuteSql( const std::string &sql, const std::vector &bindArgs = std::vector()) override; int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const std::vector &bindArgs) override; @@ -126,12 +135,12 @@ public: std::string GetOrgPath(); std::string GetFileType(); std::shared_ptr QueryByStep(const std::string &sql, - const std::vector &selectionArgs) override; - std::shared_ptr QueryByStep(const std::string &sql, std::vector &&args) override; + const std::vector &sqlArgs) override; + std::shared_ptr QueryByStep(const std::string &sql, const std::vector &args) override; std::shared_ptr QueryByStep( - const AbsRdbPredicates &predicates, const std::vector columns) override; + const AbsRdbPredicates &predicates, const std::vector &columns) override; std::shared_ptr Query( - const AbsRdbPredicates &predicates, const std::vector columns) override; + const AbsRdbPredicates &predicates, const std::vector &columns) override; int Count(int64_t &outValue, const AbsRdbPredicates &predicates) override; int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) override; int Delete(int &deletedRows, const AbsRdbPredicates &predicates) override; @@ -154,9 +163,6 @@ public: int Notify(const std::string &event) override; - // user must use UDID - bool DropDeviceData(const std::vector& devices, const DropOption& option) override; - std::map GetModifyTime( const std::string &table, const std::string &columnName, std::vector &keys) override; diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_manager.h b/relational_store/frameworks/native/rdb/include/rdb_store_manager.h index 6204943a..e6cbab51 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_manager.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_manager.h @@ -35,6 +35,7 @@ public: int &errCode, int version, RdbOpenCallback &openCallback); void Clear(); bool Remove(const std::string &path); + bool Delete(const std::string &path); int SetSecurityLabel(const RdbStoreConfig &config); private: diff --git a/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h b/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h index f6804785..465729b2 100644 --- a/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h +++ b/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h @@ -32,15 +32,35 @@ public: int AddRow(int addedRows); int Reset(int startPos); int Finish(int addedRows, int totalRows); - int PutString(int row, int column, const char *text, int sizeIncludingNull); int PutLong(int row, int column, sqlite3_int64 value); int PutDouble(int row, int column, double value); int PutBlob(int row, int column, const void *blob, int len); int PutNull(int row, int column); int PutOther(int row, int column); - int GetTotalRows() const; - int GetAddedRows() const; - int GetStartPos() const; + int PutString(int row, int column, const char *text, int sizeIncludingNull) + { + int status = sharedBlock_->PutString(row, column, text, sizeIncludingNull); + if (status == AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { + return SQLITE_OK; + } + sharedBlock_->FreeLastRow(); + return SQLITE_FULL; + } + + int GetTotalRows() const + { + return atotalRows; + } + + int GetAddedRows() const + { + return raddedRows; + } + + int GetStartPos() const + { + return astartPos; + } private: AppDataFwk::SharedBlock *sharedBlock_; sqlite3_stmt *statement_ = nullptr; @@ -48,7 +68,6 @@ private: int atotalRows; int astartPos; int raddedRows; - bool risFull; }; struct Sqlite3SharedBlockMethods { diff --git a/relational_store/frameworks/native/rdb/include/sqlite_connection.h b/relational_store/frameworks/native/rdb/include/sqlite_connection.h index 460e6519..aedbad45 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_connection.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_connection.h @@ -45,8 +45,6 @@ public: const std::vector &bindArgs = std::vector()); int ExecuteGetString(std::string &outValue, const std::string &sql, const std::vector &bindArgs = std::vector()); - std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, - const std::vector &selectionArgs) const; std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, const std::vector &args) const; int DesFinalize(); diff --git a/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h b/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h index ae80a2c2..aafb1d87 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h @@ -35,7 +35,7 @@ namespace NativeRdb { class SqliteSharedResultSet : public AbsSharedResultSet { public: SqliteSharedResultSet(std::shared_ptr store, SqliteConnectionPool *connectionPool, std::string path, - std::string sql, const std::vector &bindArgs); + std::string sql, const std::vector &bindArgs); ~SqliteSharedResultSet() override; int GetAllColumnNames(std::vector &columnNames) override; int Close() override; @@ -63,7 +63,7 @@ private: // Controls fetching of rows relative to requested position bool isOnlyFillResultSetBlock; std::string qrySql; - std::vector selectionArgVec; + std::vector bindArgs_; // The number of rows in the cursor int rowNum; std::vector columnNames_; diff --git a/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h b/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h index 4f972602..0b070fa4 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h @@ -34,16 +34,9 @@ public: const std::vector &whereArgs, const std::string &index, const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset, std::vector &bindArgs, ConflictResolution conflictResolution); - static std::string BuildUpdateStringOnlyWhere(const ValuesBucket &values, const std::string &tableName, - const std::vector &whereArgs, const std::string &index, const std::string &whereClause, - const std::string &group, const std::string &order, int limit, int offset, std::vector &bindArgs, - ConflictResolution conflictResolution); static int BuildQueryString(bool distinct, const std::string &table, const std::vector &columns, - const std::string &where, const std::string &groupBy, const std::string &having, const std::string &orderBy, - const std::string &limit, const std::string &offset, std::string &outSql); - static std::string BuildQueryStringWithExpr(const std::string &tableName, bool distinct, const std::string &index, - const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset, - std::vector &expr); + const std::string &whereClause, const std::string &groupBy, const std::string &indexName, + const std::string &orderBy, const int &limit, const int &offset, std::string &outSql); static std::string BuildCountString(const std::string &tableName, const std::string &index, const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset); static std::string BuildSqlStringFromPredicates(const std::string &index, const std::string &whereClause, @@ -52,12 +45,11 @@ public: const std::string &group, const std::string &order, int limit, int offset); static std::string BuildQueryString(const AbsRdbPredicates &predicates, const std::vector &columns); static std::string BuildCountString(const AbsRdbPredicates &predicates); - static std::string BuildSqlStringFromPredicates(const AbsRdbPredicates &predicates); + static std::string BuildSqlStringFromPredicates(const AbsPredicates &predicates); private: static void AppendClause(std::string &builder, const std::string &name, const std::string &clause); - static void AppendColumns(std::string &builder, const std::vector &columns, int &errorCode); - static void AppendExpr(std::string &builder, std::vector &exprs); + static void AppendColumns(std::string &builder, const std::vector &columns); }; } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/frameworks/native/rdb/include/step_result_set.h b/relational_store/frameworks/native/rdb/include/step_result_set.h index 729d806e..c0bd917e 100644 --- a/relational_store/frameworks/native/rdb/include/step_result_set.h +++ b/relational_store/frameworks/native/rdb/include/step_result_set.h @@ -30,9 +30,7 @@ namespace NativeRdb { class StepResultSet : public AbsResultSet { public: StepResultSet(std::shared_ptr rdb, SqliteConnectionPool *connectionPool, const std::string &sql, - const std::vector &selectionArgs); - StepResultSet(std::shared_ptr rdb, SqliteConnectionPool *pool, const std::string &sql, - std::vector &&args); + const std::vector &selectionArgs); ~StepResultSet() override; int GetAllColumnNames(std::vector &columnNames) override; @@ -67,7 +65,6 @@ private: std::shared_ptr rdb; SqliteConnectionPool *connectionPool_; std::string sql; - std::vector selectionArgs; std::vector args_; // Whether reach the end of this result set or not bool isAfterLast; diff --git a/relational_store/frameworks/native/rdb/include/string_utils.h b/relational_store/frameworks/native/rdb/include/string_utils.h index 6ae11ec3..ebd93b33 100644 --- a/relational_store/frameworks/native/rdb/include/string_utils.h +++ b/relational_store/frameworks/native/rdb/include/string_utils.h @@ -26,6 +26,8 @@ public: static std::string SurroundWithQuote(const std::string &value, const std::string "e); static std::string SurroundWithFunction( const std::string &function, const std::string &separator, const std::vector &array); + + static std::vector Split(const std::string &str, const std::string &delim); static bool IsEmpty(std::string source) { return (source.empty()); diff --git a/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h b/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h index 1d41bac9..0ed65a3b 100644 --- a/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h @@ -44,11 +44,18 @@ public: ConflictResolution conflictResolution) override; int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, const std::vector &whereArgs) override; + int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, + const std::vector &bindArgs) override; int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, const std::vector &whereArgs, ConflictResolution conflictResolution) override; + int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &bindArgs, + ConflictResolution conflictResolution) override; int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, const std::vector &whereArgs) override; + int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &bindArgs) override; int ExecuteSql( const std::string &sql, const std::vector &bindArgs = std::vector()) override; int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const std::vector &bindArgs) override; @@ -82,10 +89,10 @@ public: std::string GetOrgPath(); std::string GetFileType(); std::shared_ptr QueryByStep(const std::string &sql, - const std::vector &selectionArgs) override; - std::shared_ptr QueryByStep(const std::string &sql, std::vector &&args) override; + const std::vector &sqlArgs) override; + std::shared_ptr QueryByStep(const std::string &sql, const std::vector &args) override; std::shared_ptr Query( - const AbsRdbPredicates &predicates, const std::vector columns) override; + const AbsRdbPredicates &predicates, const std::vector &columns) override; int Count(int64_t &outValue, const AbsRdbPredicates &predicates) override; int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) override; int Delete(int &deletedRows, const AbsRdbPredicates &predicates) override; diff --git a/relational_store/frameworks/native/rdb/mock/include/rdb_store_manager.h b/relational_store/frameworks/native/rdb/mock/include/rdb_store_manager.h index 6204943a..e6cbab51 100644 --- a/relational_store/frameworks/native/rdb/mock/include/rdb_store_manager.h +++ b/relational_store/frameworks/native/rdb/mock/include/rdb_store_manager.h @@ -35,6 +35,7 @@ public: int &errCode, int version, RdbOpenCallback &openCallback); void Clear(); bool Remove(const std::string &path); + bool Delete(const std::string &path); int SetSecurityLabel(const RdbStoreConfig &config); private: diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h index 9f2f368b..343b8d14 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h @@ -43,8 +43,6 @@ public: const std::vector &bindArgs = std::vector()); int ExecuteGetString(std::string &outValue, const std::string &sql, const std::vector &bindArgs = std::vector()); - std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, - const std::vector &selectionArgs) const; std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, const std::vector &args) const; int DesFinalize(); diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_sql_builder.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_sql_builder.h index 4f972602..0b070fa4 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_sql_builder.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_sql_builder.h @@ -34,16 +34,9 @@ public: const std::vector &whereArgs, const std::string &index, const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset, std::vector &bindArgs, ConflictResolution conflictResolution); - static std::string BuildUpdateStringOnlyWhere(const ValuesBucket &values, const std::string &tableName, - const std::vector &whereArgs, const std::string &index, const std::string &whereClause, - const std::string &group, const std::string &order, int limit, int offset, std::vector &bindArgs, - ConflictResolution conflictResolution); static int BuildQueryString(bool distinct, const std::string &table, const std::vector &columns, - const std::string &where, const std::string &groupBy, const std::string &having, const std::string &orderBy, - const std::string &limit, const std::string &offset, std::string &outSql); - static std::string BuildQueryStringWithExpr(const std::string &tableName, bool distinct, const std::string &index, - const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset, - std::vector &expr); + const std::string &whereClause, const std::string &groupBy, const std::string &indexName, + const std::string &orderBy, const int &limit, const int &offset, std::string &outSql); static std::string BuildCountString(const std::string &tableName, const std::string &index, const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset); static std::string BuildSqlStringFromPredicates(const std::string &index, const std::string &whereClause, @@ -52,12 +45,11 @@ public: const std::string &group, const std::string &order, int limit, int offset); static std::string BuildQueryString(const AbsRdbPredicates &predicates, const std::vector &columns); static std::string BuildCountString(const AbsRdbPredicates &predicates); - static std::string BuildSqlStringFromPredicates(const AbsRdbPredicates &predicates); + static std::string BuildSqlStringFromPredicates(const AbsPredicates &predicates); private: static void AppendClause(std::string &builder, const std::string &name, const std::string &clause); - static void AppendColumns(std::string &builder, const std::vector &columns, int &errorCode); - static void AppendExpr(std::string &builder, std::vector &exprs); + static void AppendColumns(std::string &builder, const std::vector &columns); }; } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/frameworks/native/rdb/mock/include/step_result_set.h b/relational_store/frameworks/native/rdb/mock/include/step_result_set.h index c7c4c207..35b72e84 100644 --- a/relational_store/frameworks/native/rdb/mock/include/step_result_set.h +++ b/relational_store/frameworks/native/rdb/mock/include/step_result_set.h @@ -30,9 +30,7 @@ namespace NativeRdb { class StepResultSet : public AbsResultSet { public: StepResultSet(std::shared_ptr rdb, SqliteConnectionPool *connectionPool, const std::string &sql, - const std::vector &selectionArgs); - StepResultSet(std::shared_ptr rdb, SqliteConnectionPool *pool, const std::string &sql, - std::vector &&args); + const std::vector &selectionArgs); ~StepResultSet() override; int GetAllColumnNames(std::vector &columnNames) override; @@ -67,7 +65,6 @@ private: std::shared_ptr rdb; SqliteConnectionPool *connectionPool_; std::string sql; - std::vector selectionArgs; std::vector args_; // Whether reach the end of this result set or not bool isAfterLast; diff --git a/relational_store/frameworks/native/rdb/mock/include/string_utils.h b/relational_store/frameworks/native/rdb/mock/include/string_utils.h index 6ae11ec3..ebd93b33 100644 --- a/relational_store/frameworks/native/rdb/mock/include/string_utils.h +++ b/relational_store/frameworks/native/rdb/mock/include/string_utils.h @@ -26,6 +26,8 @@ public: static std::string SurroundWithQuote(const std::string &value, const std::string "e); static std::string SurroundWithFunction( const std::string &function, const std::string &separator, const std::vector &array); + + static std::vector Split(const std::string &str, const std::string &delim); static bool IsEmpty(std::string source) { return (source.empty()); diff --git a/relational_store/frameworks/native/rdb/src/abs_predicates.cpp b/relational_store/frameworks/native/rdb/src/abs_predicates.cpp index 9cf1f152..88b9b9d0 100644 --- a/relational_store/frameworks/native/rdb/src/abs_predicates.cpp +++ b/relational_store/frameworks/native/rdb/src/abs_predicates.cpp @@ -17,7 +17,7 @@ #include #include -#include +#include #include "logger.h" #include "rdb_trace.h" @@ -50,12 +50,9 @@ bool AbsPredicates::IsNeedAnd() const /** * Restricts the value of the field to be greater than the specified value. */ -AbsPredicates *AbsPredicates::EqualTo(const std::string &field, const std::string &value) +AbsPredicates *AbsPredicates::EqualTo(const std::string &field, const ValueObject &value) { - DISTRIBUTED_DATA_HITRACE("AbsPredicates::EqualTo"); - bool chekParaFlag = CheckParameter("equalTo", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: EqualTo() fails because Invalid parameter."); + if (!CheckParameter("equalTo", field, { value })) { return this; } if (isNeedAnd) { @@ -64,23 +61,21 @@ AbsPredicates *AbsPredicates::EqualTo(const std::string &field, const std::strin isNeedAnd = true; } whereClause += field + " = ? "; - whereArgs.push_back(value); + bindArgs.push_back(value); return this; } /** * Restricts the value of the field to be unequal to the specified value. */ -AbsPredicates *AbsPredicates::NotEqualTo(const std::string &field, const std::string &value) +AbsPredicates *AbsPredicates::NotEqualTo(const std::string &field, const ValueObject &value) { - bool chekParaFlag = CheckParameter("notEqualTo", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: NotEqualTo() fails because Invalid parameter."); + if (!CheckParameter("notEqualTo", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " <> ? "; - whereArgs.push_back(value); + bindArgs.push_back(value); return this; } @@ -129,14 +124,12 @@ AbsPredicates *AbsPredicates::And() */ AbsPredicates *AbsPredicates::Contains(const std::string &field, const std::string &value) { - bool chekParaFlag = CheckParameter("contains", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: Contains() fails because Invalid parameter."); + if (!CheckParameter("contains", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " LIKE ? "; - whereArgs.push_back("%" + value + "%"); + bindArgs.push_back(ValueObject("%" + value + "%")); return this; } @@ -145,14 +138,12 @@ AbsPredicates *AbsPredicates::Contains(const std::string &field, const std::stri */ AbsPredicates *AbsPredicates::BeginsWith(const std::string &field, const std::string &value) { - bool chekParaFlag = CheckParameter("beginsWith", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: BeginsWith() fails because Invalid parameter."); + if (!CheckParameter("beginsWith", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " LIKE ? "; - whereArgs.push_back(value + "%"); + bindArgs.push_back(ValueObject(value + "%")); return this; } @@ -161,14 +152,12 @@ AbsPredicates *AbsPredicates::BeginsWith(const std::string &field, const std::st */ AbsPredicates *AbsPredicates::EndsWith(const std::string &field, const std::string &value) { - bool chekParaFlag = CheckParameter("endsWith", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: EndsWith() fails because Invalid parameter."); + if (!CheckParameter("endsWith", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " LIKE ? "; - whereArgs.push_back("%" + value); + bindArgs.push_back(ValueObject("%" + value)); return this; } @@ -177,13 +166,11 @@ AbsPredicates *AbsPredicates::EndsWith(const std::string &field, const std::stri */ AbsPredicates *AbsPredicates::IsNull(const std::string &field) { - bool chekParaFlag = CheckParameter("isNull", field, {}); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: IsNull() fails because Invalid parameter."); + if (!CheckParameter("isNull", field, {})) { return this; } CheckIsNeedAnd(); - whereClause += field + " is null "; + whereClause += field + " IS NULL "; return this; } @@ -192,13 +179,11 @@ AbsPredicates *AbsPredicates::IsNull(const std::string &field) */ AbsPredicates *AbsPredicates::IsNotNull(const std::string &field) { - bool chekParaFlag = CheckParameter("isNotNull", field, {}); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: IsNotNull() fails because Invalid parameter."); + if (!CheckParameter("isNotNull", field, {})) { return this; } CheckIsNeedAnd(); - whereClause += field + " is not null "; + whereClause += field + " IS NOT NULL "; return this; } @@ -207,14 +192,12 @@ AbsPredicates *AbsPredicates::IsNotNull(const std::string &field) */ AbsPredicates *AbsPredicates::Like(const std::string &field, const std::string &value) { - bool chekParaFlag = CheckParameter("like", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: Like() fails because Invalid parameter."); + if (!CheckParameter("like", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " LIKE ? "; - whereArgs.push_back(value); + bindArgs.push_back(ValueObject(value)); return this; } @@ -223,112 +206,98 @@ AbsPredicates *AbsPredicates::Like(const std::string &field, const std::string & */ AbsPredicates *AbsPredicates::Glob(const std::string &field, const std::string &value) { - bool chekParaFlag = CheckParameter("glob", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: Glob() fails because Invalid parameter."); + if (!CheckParameter("glob", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " GLOB ? "; - whereArgs.push_back(value); + bindArgs.push_back(ValueObject(value)); return this; } /** * Restricts the value of the field to be unequal to the specified value. */ -AbsPredicates *AbsPredicates::Between(std::string field, std::string low, std::string high) +AbsPredicates *AbsPredicates::Between(const std::string &field, const ValueObject &low, const ValueObject &high) { - bool chekParaFlag = CheckParameter("between", field, { low, high }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: Between() fails because Invalid parameter."); + if (!CheckParameter("between", field, { low, high })) { return this; } CheckIsNeedAnd(); whereClause += field + " BETWEEN ? AND ? "; - whereArgs.push_back(low); - whereArgs.push_back(high); + bindArgs.push_back(low); + bindArgs.push_back(high); return this; } /** * Configures to match the specified field whose data type is String and value is out of a given range. */ -AbsPredicates *AbsPredicates::NotBetween(std::string field, std::string low, std::string high) +AbsPredicates *AbsPredicates::NotBetween(const std::string &field, const ValueObject &low, const ValueObject &high) { - bool chekParaFlag = CheckParameter("notBetween", field, { low, high }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: NotBetween() fails because Invalid parameter."); + if (!CheckParameter("notBetween", field, { low, high })) { return this; } CheckIsNeedAnd(); whereClause += field + " NOT BETWEEN ? AND ? "; - whereArgs.push_back(low); - whereArgs.push_back(high); + bindArgs.push_back(low); + bindArgs.push_back(high); return this; } /** * Restricts the value of the field to be greater than the specified value. */ -AbsPredicates *AbsPredicates::GreaterThan(const std::string &field, const std::string &value) +AbsPredicates *AbsPredicates::GreaterThan(const std::string &field, const ValueObject &value) { - bool chekParaFlag = CheckParameter("greaterThan", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: GreaterThan() fails because Invalid parameter."); + if (!CheckParameter("greaterThan", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " > ? "; - whereArgs.push_back(value); + bindArgs.push_back(value); return this; } /** * Restricts the value of the field to be smaller than the specified value. */ -AbsPredicates *AbsPredicates::LessThan(const std::string &field, const std::string &value) +AbsPredicates *AbsPredicates::LessThan(const std::string &field, const ValueObject &value) { - bool chekParaFlag = CheckParameter("lessThan", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: LessThan() fails because Invalid parameter."); + if (!CheckParameter("lessThan", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " < ? "; - whereArgs.push_back(value); + bindArgs.push_back(value); return this; } /** * Restricts the value of the field to be greater than or equal to the specified value. */ -AbsPredicates *AbsPredicates::GreaterThanOrEqualTo(const std::string &field, const std::string &value) +AbsPredicates *AbsPredicates::GreaterThanOrEqualTo(const std::string &field, const ValueObject &value) { - bool chekParaFlag = CheckParameter("greaterThanOrEqualTo", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: GreaterThanOrEqualTo() fails because Invalid parameter."); + if (!CheckParameter("greaterThanOrEqualTo", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " >= ? "; - whereArgs.push_back(value); + bindArgs.push_back(value); return this; } /** * Restricts the value of the field to be smaller than or equal to the specified value. */ -AbsPredicates *AbsPredicates::LessThanOrEqualTo(const std::string &field, const std::string &value) +AbsPredicates *AbsPredicates::LessThanOrEqualTo(const std::string &field, const ValueObject &value) { - bool chekParaFlag = CheckParameter("greaterThanOrEqualTo", field, { value }); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: LessThanOrEqualTo() fails because Invalid parameter."); + if (!CheckParameter("greaterThanOrEqualTo", field, { value })) { return this; } CheckIsNeedAnd(); whereClause += field + " <= ? "; - whereArgs.push_back(value); + bindArgs.push_back(value); return this; } @@ -338,9 +307,7 @@ AbsPredicates *AbsPredicates::LessThanOrEqualTo(const std::string &field, const */ AbsPredicates *AbsPredicates::OrderByAsc(const std::string &field) { - bool chekParaFlag = CheckParameter("orderByAsc", field, {}); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: OrderByAsc() fails because Invalid parameter."); + if (!CheckParameter("orderByAsc", field, {})) { return this; } if (isSorted) { @@ -357,9 +324,7 @@ AbsPredicates *AbsPredicates::OrderByAsc(const std::string &field) */ AbsPredicates *AbsPredicates::OrderByDesc(const std::string &field) { - bool chekParaFlag = CheckParameter("orderByDesc", field, {}); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: OrderByDesc() fails because Invalid parameter."); + if (!CheckParameter("orderByDesc", field, {})) { return this; } if (isSorted) { @@ -379,32 +344,26 @@ AbsPredicates *AbsPredicates::Distinct() /** * Restricts the max number of return records. */ -AbsPredicates *AbsPredicates::Limit(int limit) +AbsPredicates *AbsPredicates::Limit(const int limit) { - limit = (limit <= 0) ? -1 : limit; - this->limit = limit; + this->limit = (limit <= 0) ? -1 : limit; return this; } /** * Restricts the max number of return records. */ -AbsPredicates *AbsPredicates::Limit(int offset, int limit) +AbsPredicates *AbsPredicates::Limit(const int offset, const int limit) { - limit = (limit <= 0) ? -1 : limit; - this->limit = limit; - - return Offset(offset); + return this->Limit(limit)->Offset(offset); } /** * Configures to specify the start position of the returned result. */ -AbsPredicates *AbsPredicates::Offset(int offset) +AbsPredicates *AbsPredicates::Offset(const int offset) { - offset = (offset < 0) ? -1 : offset; - this->offset = offset; - + this->offset = (offset < 0) ? -1 : offset; return this; } @@ -414,13 +373,11 @@ AbsPredicates *AbsPredicates::Offset(int offset) AbsPredicates *AbsPredicates::GroupBy(const std::vector &fields) { if (fields.empty()) { - LOG_WARN("AbsPredicates: groupBy() fails because fields can't be null."); + LOG_WARN("groupBy() fails because fields can't be null."); return this; } for (auto &field : fields) { - bool chekParaFlag = CheckParameter("GroupBy", field, {}); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: GroupBy() fails because Invalid parameter."); + if (!CheckParameter("GroupBy", field, {})) { return this; } group += field + ","; @@ -437,61 +394,65 @@ AbsPredicates *AbsPredicates::GroupBy(const std::vector &fields) */ AbsPredicates *AbsPredicates::IndexedBy(const std::string &indexName) { - bool chekParaFlag = CheckParameter("indexedBy", indexName, {}); - if (!chekParaFlag) { - LOG_WARN("AbsPredicates: IndexedBy() fails because Invalid parameter."); + if (!CheckParameter("indexedBy", indexName, {})) { return this; } index = RemoveQuotes(indexName); return this; } +AbsPredicates *AbsPredicates::In(const std::string &field, const std::vector &values) +{ + std::vector bindArgs; + std::for_each(values.begin(), values.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + return In(field, bindArgs); +} + /** * Configures to match the specified field whose data type is String array and values are within a given range. */ -AbsPredicates *AbsPredicates::In(const std::string &field, const std::vector &values) +AbsPredicates *AbsPredicates::In(const std::string &field, const std::vector &values) { bool chekParaFlag = CheckParameter("in", field, {}); if (!chekParaFlag) { - LOG_WARN("AbsPredicates: In() fails because Invalid parameter."); return this; } if (values.empty()) { - LOG_WARN("AbsPredicates: in() fails because values can't be null."); + LOG_WARN("in() fails because values can't be null."); return this; } CheckIsNeedAnd(); - std::vector replaceValues; - for (auto &value : values) { - replaceValues.push_back("?"); - whereArgs.push_back(std::move(value)); - } + std::vector replaceValues(values.size(), "?"); + bindArgs.insert(bindArgs.end(), values.begin(), values.end()); AppendWhereClauseWithInOrNotIn(" IN ", field, replaceValues); return this; } +AbsPredicates *AbsPredicates::NotIn(const std::string &field, const std::vector &values) +{ + std::vector bindArgs; + std::for_each(values.begin(), values.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + return NotIn(field, bindArgs); +} + /** * Configures to match the specified field whose data type is String array and values are out of a given range. */ -AbsPredicates *AbsPredicates::NotIn(const std::string &field, const std::vector &values) +AbsPredicates *AbsPredicates::NotIn(const std::string &field, const std::vector &values) { bool chekParaFlag = CheckParameter("notIn", field, {}); if (!chekParaFlag) { - LOG_WARN("AbsPredicates: NotIn() fails because Invalid parameter."); return this; } if (values.empty()) { - LOG_WARN("AbsPredicates: notIn() fails because values is null."); + LOG_WARN("fails as values is null."); return this; } CheckIsNeedAnd(); - std::vector replaceValues; - for (auto &value : values) { - replaceValues.push_back("?"); - whereArgs.push_back(std::move(value)); - } + std::vector replaceValues(values.size(), "?"); + bindArgs.insert(bindArgs.end(), values.begin(), values.end()); AppendWhereClauseWithInOrNotIn(" NOT IN ", field, replaceValues); return this; } @@ -501,29 +462,29 @@ void AbsPredicates::Initial() distinct = false; isNeedAnd = false; isSorted = false; - whereArgs.clear(); + bindArgs.clear(); whereClause.clear(); order.clear(); group.clear(); index.clear(); - limit = INT_MIN; - offset = INT_MIN; + limit = INIT_LIMIT_VALUE; + offset = INIT_OFFSET_VALUE; } /** * Check the parameter validity. */ bool AbsPredicates::CheckParameter( - const std::string &methodName, const std::string &field, const std::initializer_list &args) const + const std::string &methodName, const std::string &field, const std::initializer_list &args) const { if (field.empty()) { - LOG_WARN("QueryImpl(): string 'field' is empty."); + LOG_WARN("%{public}s: string 'field' is empty.", methodName.c_str()); return false; } - if (args.size() != 0) { - for (auto &i : args) { - if (i.empty()) { - LOG_WARN("QueryImpl(): value is empty."); + for (auto &arg : args) { + if (auto pval = std::get_if(&arg.value)) { + if ((*pval).empty()) { + LOG_WARN("%{public}s: value is empty.", methodName.c_str()); return false; } } @@ -558,6 +519,11 @@ void AbsPredicates::AppendWhereClauseWithInOrNotIn( whereClause += field + StringUtils::SurroundWithFunction(methodName, ",", replaceValues); } +std::string AbsPredicates::GetStatement() const +{ + return SqliteSqlBuilder::BuildSqlStringFromPredicates(*this); +} + std::string AbsPredicates::GetWhereClause() const { return whereClause; @@ -573,12 +539,31 @@ void AbsPredicates::SetWhereClause(const std::string &whereClause) std::vector AbsPredicates::GetWhereArgs() const { + std::vector whereArgs; + for (auto &arg : this->bindArgs) { + std::string temp; + if (!arg.GetString(temp)) { + LOG_WARN("No matching type, empty string instead."); + } + whereArgs.push_back(temp); + } return whereArgs; } void AbsPredicates::SetWhereArgs(const std::vector &whereArgs) { - this->whereArgs = whereArgs; + this->bindArgs.clear(); + std::for_each(whereArgs.begin(), whereArgs.end(), [this](const auto &it) { bindArgs.push_back(ValueObject(it)); }); +} + +std::vector AbsPredicates::GetBindArgs() const +{ + return bindArgs; +} + +void AbsPredicates::SetBindArgs(const std::vector &bindArgs) +{ + this->bindArgs = bindArgs; } std::string AbsPredicates::GetOrder() const diff --git a/relational_store/frameworks/native/rdb/src/abs_rdb_predicates.cpp b/relational_store/frameworks/native/rdb/src/abs_rdb_predicates.cpp index 14568a17..cf0a1e35 100644 --- a/relational_store/frameworks/native/rdb/src/abs_rdb_predicates.cpp +++ b/relational_store/frameworks/native/rdb/src/abs_rdb_predicates.cpp @@ -15,6 +15,8 @@ #include "abs_rdb_predicates.h" +#include + #include "logger.h" #include "rdb_trace.h" @@ -29,9 +31,7 @@ AbsRdbPredicates::AbsRdbPredicates(const std::string &tableName) return; } tableName_ = std::move(tableName); -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) predicates_.tables_.push_back(tableName_); -#endif } AbsRdbPredicates::AbsRdbPredicates(const std::vector &tables) @@ -42,9 +42,7 @@ AbsRdbPredicates::AbsRdbPredicates(const std::vector &tables) return; } tableName_ = *(tables.begin()); -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) predicates_.tables_ = std::move(tables); -#endif } void AbsRdbPredicates::Clear() @@ -145,26 +143,21 @@ std::string AbsRdbPredicates::ToString() const for (const auto& item : GetWhereArgs()) { args += item + ", "; } - return "TableName = " + GetTableName() + ", {WhereClause:" + GetWhereClause() + ", whereArgs:{" + args + "}" + return "TableName = " + GetTableName() + ", {WhereClause:" + GetWhereClause() + ", bindArgs:{" + args + "}" + ", order:" + GetOrder() + ", group:" + GetGroup() + ", index:" + GetIndex() + ", limit:" + std::to_string(GetLimit()) + ", offset:" + std::to_string(GetOffset()) + ", distinct:" + std::to_string(IsDistinct()) + ", isNeedAnd:" + std::to_string(IsNeedAnd()) + ", isSorted:" + std::to_string(IsSorted()) + "}"; } -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) AbsRdbPredicates* AbsRdbPredicates::InDevices(std::vector &devices) { - for (const auto& device : devices) { - LOG_INFO("%{public}.6s", device.c_str()); - } predicates_.devices_ = devices; return this; } AbsRdbPredicates* AbsRdbPredicates::InAllDevices() { - LOG_INFO("enter"); predicates_.devices_.clear(); return this; } @@ -179,16 +172,20 @@ const DistributedRdb::PredicatesMemo& AbsRdbPredicates::GetDistributedPredicates return predicates_; } -AbsRdbPredicates* AbsRdbPredicates::EqualTo(const std::string &field, const std::string &value) +AbsRdbPredicates* AbsRdbPredicates::EqualTo(const std::string &field, const ValueObject &value) { DISTRIBUTED_DATA_HITRACE("AbsRdbPredicates::EqualTo"); - predicates_.AddOperation(DistributedRdb::EQUAL_TO, field, value); + if (auto pval = std::get_if(&value.value)) { + predicates_.AddOperation(DistributedRdb::EQUAL_TO, field, *pval); + } return (AbsRdbPredicates *)AbsPredicates::EqualTo(field, value); } -AbsRdbPredicates* AbsRdbPredicates::NotEqualTo(const std::string &field, const std::string &value) +AbsRdbPredicates* AbsRdbPredicates::NotEqualTo(const std::string &field, const ValueObject &value) { - predicates_.AddOperation(DistributedRdb::NOT_EQUAL_TO, field, value); + if (auto pval = std::get_if(&value.value)) { + predicates_.AddOperation(DistributedRdb::NOT_EQUAL_TO, field, *pval); + } return (AbsRdbPredicates *)AbsPredicates::NotEqualTo(field, value); } @@ -221,5 +218,4 @@ AbsRdbPredicates* AbsRdbPredicates::OrderByDesc(const std::string &field) predicates_.AddOperation(DistributedRdb::ORDER_BY, field, isAsc); return (AbsRdbPredicates *)AbsPredicates::OrderByDesc(field); } -#endif } // namespace OHOS::NativeRdb \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp b/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp index 83ada7e7..0956c7b7 100644 --- a/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp +++ b/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp @@ -66,20 +66,15 @@ void AbsSharedResultSet::FillBlock(int startRowIndex, AppDataFwk::SharedBlock *b return; } -void AbsSharedResultSet::InitBlock() -{ - if (sharedBlock_ == nullptr) { - AppDataFwk::SharedBlock::Create(sharedBlockName_, DEFAULT_BLOCK_SIZE, sharedBlock_); - } - return; -} - /** * Get current shared block */ AppDataFwk::SharedBlock *AbsSharedResultSet::GetBlock() { - InitBlock(); + if (sharedBlock_ != nullptr) { + return sharedBlock_; + } + AppDataFwk::SharedBlock::Create(sharedBlockName_, DEFAULT_BLOCK_SIZE, sharedBlock_); return sharedBlock_; } diff --git a/relational_store/frameworks/native/rdb/src/rdb_helper.cpp b/relational_store/frameworks/native/rdb/src/rdb_helper.cpp index c2daf683..fad63f55 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_helper.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_helper.cpp @@ -16,9 +16,7 @@ #include "rdb_helper.h" #include "logger.h" -#include "rdb_common.h" #include "rdb_errno.h" -#include "rdb_store_impl.h" #include "rdb_store_manager.h" #include "rdb_trace.h" #include "sqlite_global_config.h" @@ -38,7 +36,7 @@ std::shared_ptr RdbHelper::GetRdbStore( { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); SqliteGlobalConfig::InitSqliteGlobalConfig(); - return RdbStoreManager::GetInstance().GetRdbStore(config, errCode, version, openCallback);; + return RdbStoreManager::GetInstance().GetRdbStore(config, errCode, version, openCallback); } void RdbHelper::ClearCache() @@ -53,14 +51,13 @@ static void DeleteRdbKeyFiles(const std::string &dbFileName) #endif } - int RdbHelper::DeleteRdbStore(const std::string &dbFileName) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); if (dbFileName.empty()) { return E_EMPTY_FILE_NAME; } - RdbStoreManager::GetInstance().Remove(dbFileName); // maybe need to return here + RdbStoreManager::GetInstance().Delete(dbFileName); // maybe need to return here if (access(dbFileName.c_str(), F_OK) != 0) { return E_OK; // not not exist } diff --git a/relational_store/frameworks/native/rdb/src/rdb_predicates.cpp b/relational_store/frameworks/native/rdb/src/rdb_predicates.cpp index f373a77b..466714d6 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_predicates.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_predicates.cpp @@ -17,7 +17,6 @@ #include "logger.h" #include "string_utils.h" -#include "sqlite_sql_builder.h" namespace OHOS { namespace NativeRdb { @@ -119,16 +118,6 @@ RdbPredicates *RdbPredicates::On(const std::vector &clauses) return this; } -std::string RdbPredicates::GetStatement() -{ - return SqliteSqlBuilder::BuildSqlStringFromPredicates(*this); -} - -std::vector RdbPredicates::GetBindArgs() -{ - return GetWhereArgs(); -} - std::string RdbPredicates::ProcessJoins() const { std::string builder = GetTableName(); diff --git a/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp b/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp index bb339664..6054d533 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp @@ -69,16 +69,20 @@ void RdbServiceProxy::OnSyncComplete(uint32_t seqNum, Details &&result) void RdbServiceProxy::OnDataChange(const Origin &origin, const PrimaryFields &primaries, ChangeInfo &&changeInfo) { + LOG_DEBUG("store:%{public}s data change from :%{public}s, dataType:%{public}d, origin:%{public}d.", + SqliteUtils::Anonymous(origin.store).c_str(), + origin.id.empty() ? "empty" : SqliteUtils::Anonymous(*origin.id.begin()).c_str(), + origin.dataType, origin.origin); auto name = RemoveSuffix(origin.store); observers_.ComputeIfPresent(name, - [&origin, &primaries, info = std::move(changeInfo)](const auto &key, const ObserverMapValue &value) mutable { - auto size = value.first.size(); - for (const auto &observer : value.first) { - size--; - observer->OnChange(origin, primaries, (size > 0) ? ChangeInfo(info) : std::move(info)); - } - return true; - }); + [&origin, &primaries, info = std::move(changeInfo)](const auto &key, const std::list &value) + mutable { + auto size = value.size(); + for (const auto ¶ms : value) { + params.observer->OnChange(origin, primaries, --size > 0 ? ChangeInfo(info) : std::move(info)); + } + return !value.empty(); + }); } std::string RdbServiceProxy::ObtainDistributedTableName(const std::string &device, const std::string &table) @@ -185,7 +189,7 @@ int32_t RdbServiceProxy::DoAsync(const RdbSyncerParam& param, const Option &opti if (callback != nullptr) { asyncOption.seqNum = GetSeqNum(); if (!syncCallbacks_.Insert(asyncOption.seqNum, callback)) { - LOG_INFO("insert callback failed"); + LOG_INFO("insert callback failed"); return RDB_ERROR; } } @@ -235,26 +239,27 @@ std::string RdbServiceProxy::RemoveSuffix(const std::string& name) int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, RdbStoreObserver *observer) { + if (observer == nullptr) { + return RDB_ERROR; + } if (option.mode < SubscribeMode::REMOTE || option.mode >= SUBSCRIBE_MODE_MAX) { LOG_ERROR("subscribe mode invalid"); return RDB_ERROR; } if (DoSubscribe(param, option) != RDB_OK) { - LOG_INFO("communicate to server failed"); return RDB_ERROR; } auto name = RemoveSuffix(param.storeName_); - observers_.Compute( - name, [observer] (const auto& key, ObserverMapValue& value) { - for (const auto& element : value.first) { - if (element == observer) { - LOG_ERROR("duplicate observer"); - return true; - } + observers_.Compute(name, [observer, ¶m, &option](const auto &key, std::list &value) { + for (const auto &element : value) { + if (element.observer == observer) { + LOG_ERROR("duplicate observer"); + return true; } - value.first.push_back(observer); - return true; - }); + } + value.push_back({ observer, param.bundleName_, option }); + return true; + }); return RDB_OK; } @@ -273,14 +278,21 @@ int32_t RdbServiceProxy::DoSubscribe(const RdbSyncerParam ¶m, const Subscrib int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, RdbStoreObserver *observer) { - DoUnSubscribe(param); + if (observer == nullptr) { + LOG_ERROR("observer is null"); + return RDB_ERROR; + } + if (DoUnSubscribe(param) != RDB_OK) { + return RDB_ERROR; + } auto name = RemoveSuffix(param.storeName_); - observers_.ComputeIfPresent( - name, [observer](const auto& key, ObserverMapValue& value) { - LOG_INFO("before remove size=%{public}d", static_cast(value.first.size())); - value.first.remove(observer); - LOG_INFO("after remove size=%{public}d", static_cast(value.first.size())); - return !(value.first.empty()); + observers_.ComputeIfPresent(name, [observer](const auto &key, std::list &value) { + LOG_INFO("before remove size=%{public}d", static_cast(value.size())); + value.remove_if([observer](const ObserverParam ¶m) { + return param.observer == observer; + }); + LOG_INFO("after remove size=%{public}d", static_cast(value.size())); + return !(value.empty()); }); return RDB_OK; } @@ -317,18 +329,20 @@ int32_t RdbServiceProxy::RemoteQuery(const RdbSyncerParam& param, const std::str return RDB_OK; } -RdbServiceProxy::ObserverMap RdbServiceProxy::ExportObservers() +RdbServiceProxy::Observers RdbServiceProxy::ExportObservers() { return observers_; } -void RdbServiceProxy::ImportObservers(ObserverMap &observers) +void RdbServiceProxy::ImportObservers(Observers &observers) { LOG_INFO("enter"); - SubscribeOption option {SubscribeMode::REMOTE}; - observers.ForEach([this, &option](const std::string& key, const ObserverMapValue& value) { - for (auto& observer : value.first) { - Subscribe(value.second, option, observer); + observers.ForEach([this](const std::string &key, const std::list &value) { + RdbSyncerParam syncerParam; + for (const auto ¶m : value) { + syncerParam.bundleName_ = param.bundleName; + syncerParam.storeName_ = key; + Subscribe(syncerParam, param.subscribeOption, param.observer); } return false; }); @@ -344,4 +358,15 @@ int32_t RdbServiceProxy::GetSchema(const RdbSyncerParam ¶m) } return status; } + +int32_t RdbServiceProxy::Delete(const RdbSyncerParam ¶m) +{ + MessageParcel reply; + int32_t status = IPC_SEND(static_cast(RdbServiceCode::RDB_SERVICE_CMD_DELETE), reply, param); + if (status != RDB_OK) { + LOG_ERROR("status:%{public}d, bundleName:%{public}s, storeName:%{public}s", status, param.bundleName_.c_str(), + SqliteUtils::Anonymous(param.storeName_).c_str()); + } + return status; +} } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/rdb_sql_utils.cpp b/relational_store/frameworks/native/rdb/src/rdb_sql_utils.cpp index 20b8f691..6cc19636 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_sql_utils.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_sql_utils.cpp @@ -40,6 +40,7 @@ namespace NativeRdb { */ std::string RdbSqlUtils::GetDefaultDatabasePath(const std::string &baseDir, const std::string &name, int &errorCode) { + errorCode = E_OK; std::string databasePath = baseDir + "/rdb"; if (access(databasePath.c_str(), F_OK) != 0) { if (MKDIR(databasePath.c_str())) { diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp index 934dc2a1..62c18e63 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp @@ -17,13 +17,14 @@ #include +#include #include #include "logger.h" #include "rdb_errno.h" +#include "rdb_sql_utils.h" #include "rdb_store.h" #include "rdb_trace.h" -#include "rdb_sql_utils.h" #include "sqlite_global_config.h" #include "sqlite_sql_builder.h" #include "sqlite_utils.h" @@ -145,7 +146,7 @@ std::map RdbStoreImpl::GetModifyTime( sql.append(" where hash_key in ("); sql.append(GetSqlArgs(hashKeys.size())); sql.append(")"); - auto resultSet = QueryByStep(sql, std::move(hashKeys)); + auto resultSet = QueryByStep(sql, hashKeys); int count = 0; if (resultSet == nullptr || resultSet->GetRowCount(count) != E_OK || count <= 0) { LOG_ERROR("get resultSet err."); @@ -179,7 +180,7 @@ std::map RdbStoreImpl::GetModifyTimeByRowId( RawDataParser::Convert(key, value); args.emplace_back(ValueObject(value)); } - auto resultSet = QueryByStep(sql, std::move(args)); + auto resultSet = QueryByStep(sql, args); int count = 0; if (resultSet == nullptr || resultSet->GetRowCount(count) != E_OK || count <= 0) { LOG_ERROR("get resultSet err."); @@ -373,7 +374,7 @@ int RdbStoreImpl::InnerInsert(int64_t &outRowId, const std::string &table, if (val.GetType() == ValueObject::TYPE_ASSET || val.GetType() == ValueObject::TYPE_ASSETS) { SetAssetStatusWhileInsert(val); } - bindArgs.push_back(std::move(val)); // columnValue + bindArgs.push_back(val); // columnValue split = ","; } @@ -416,20 +417,40 @@ void RdbStoreImpl::SetAssetStatusWhileInsert(ValueObject &val) int RdbStoreImpl::Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, const std::vector &whereArgs) +{ + std::vector bindArgs; + std::for_each( + whereArgs.begin(), whereArgs.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + return UpdateWithConflictResolution( + changedRows, table, values, whereClause, bindArgs, ConflictResolution::ON_CONFLICT_NONE); +} + +int RdbStoreImpl::Update(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &bindArgs) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); return UpdateWithConflictResolution( - changedRows, table, values, whereClause, whereArgs, ConflictResolution::ON_CONFLICT_NONE); + changedRows, table, values, whereClause, bindArgs, ConflictResolution::ON_CONFLICT_NONE); } int RdbStoreImpl::Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) { return Update( - changedRows, predicates.GetTableName(), values, predicates.GetWhereClause(), predicates.GetWhereArgs()); + changedRows, predicates.GetTableName(), values, predicates.GetWhereClause(), predicates.GetBindArgs()); } int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, const std::vector &whereArgs, ConflictResolution conflictResolution) +{ + std::vector bindArgs; + std::for_each( + whereArgs.begin(), whereArgs.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + return UpdateWithConflictResolution( + changedRows, table, values, whereClause, bindArgs, conflictResolution); +} + +int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &bindArgs, ConflictResolution conflictResolution) { if (table.empty()) { return E_EMPTY_TABLE_NAME; @@ -448,7 +469,7 @@ int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::stri std::stringstream sql; sql << "UPDATE" << conflictClause << " " << table << " SET "; - std::vector bindArgs; + std::vector tmpBindArgs; const char *split = ""; for (auto &[key, val] : values.values_) { sql << split; @@ -457,7 +478,7 @@ int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::stri } else { sql << key << "=?"; // columnName } - bindArgs.push_back(val); // columnValue + tmpBindArgs.push_back(val); // columnValue split = ","; } @@ -465,16 +486,14 @@ int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::stri sql << " WHERE " << whereClause; } - for (auto &iter : whereArgs) { - bindArgs.push_back(ValueObject(iter)); - } + tmpBindArgs.insert(tmpBindArgs.end(), bindArgs.begin(), bindArgs.end()); SqliteConnection *connection = connectionPool->AcquireConnection(false); if (connection == nullptr) { return E_CON_OVER_LIMIT; } - errCode = connection->ExecuteForChangedRowCount(changedRows, sql.str(), bindArgs); + errCode = connection->ExecuteForChangedRowCount(changedRows, sql.str(), tmpBindArgs); connectionPool->ReleaseConnection(connection); if (errCode == E_OK) { DoCloudSync(table); @@ -485,11 +504,20 @@ int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::stri int RdbStoreImpl::Delete(int &deletedRows, const AbsRdbPredicates &predicates) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); - return Delete(deletedRows, predicates.GetTableName(), predicates.GetWhereClause(), predicates.GetWhereArgs()); + return Delete(deletedRows, predicates.GetTableName(), predicates.GetWhereClause(), predicates.GetBindArgs()); } int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std::string &whereClause, const std::vector &whereArgs) +{ + std::vector bindArgs; + std::for_each( + whereArgs.begin(), whereArgs.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + return Delete(deletedRows, table, whereClause, bindArgs); +} + +int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &bindArgs) { if (table.empty()) { return E_EMPTY_TABLE_NAME; @@ -501,11 +529,6 @@ int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std:: sql << " WHERE " << whereClause; } - std::vector bindArgs; - for (auto &iter : whereArgs) { - bindArgs.push_back(ValueObject(iter)); - } - SqliteConnection *connection = connectionPool->AcquireConnection(false); if (connection == nullptr) { return E_CON_OVER_LIMIT; @@ -521,21 +544,19 @@ int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std:: #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) std::shared_ptr RdbStoreImpl::Query( - const AbsRdbPredicates &predicates, const std::vector columns) + const AbsRdbPredicates &predicates, const std::vector &columns) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); - std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns); - return QuerySql(sql, selectionArgs); + return QuerySql(sql, predicates.GetBindArgs()); } std::shared_ptr RdbStoreImpl::QueryByStep( - const AbsRdbPredicates &predicates, const std::vector columns) + const AbsRdbPredicates &predicates, const std::vector &columns) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); - std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns); - return QueryByStep(sql, selectionArgs); + return QueryByStep(sql, predicates.GetBindArgs()); } std::shared_ptr RdbStoreImpl::RemoteQuery(const std::string &device, @@ -558,56 +579,55 @@ std::shared_ptr RdbStoreImpl::RemoteQuery(const std::string &device, return std::make_shared(remoteResultSet); } -std::shared_ptr RdbStoreImpl::Query(int &errCode, bool distinct, const std::string &table, - const std::vector &columns, const std::string &selection, - const std::vector &selectionArgs, const std::string &groupBy, const std::string &having, - const std::string &orderBy, const std::string &limit) +std::shared_ptr RdbStoreImpl::Query(int &errCode, bool distinct, + const std::string &table, const std::vector &columns, + const std::string &whereClause, const std::vector &bindArgs, const std::string &groupBy, + const std::string &indexName, const std::string &orderBy, const int &limit, const int &offset) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::string sql; - errCode = SqliteSqlBuilder::BuildQueryString(distinct, table, columns, selection, groupBy, having, orderBy, limit, - "", sql); + errCode = SqliteSqlBuilder::BuildQueryString( + distinct, table, columns, whereClause, groupBy, indexName, orderBy, limit, offset, sql); if (errCode != E_OK) { return nullptr; } - auto resultSet = QuerySql(sql, selectionArgs); + auto resultSet = QuerySql(sql, bindArgs); return resultSet; } std::shared_ptr RdbStoreImpl::QuerySql(const std::string &sql, - const std::vector &selectionArgs) + const std::vector &sqlArgs) +{ + std::vector bindArgs; + std::for_each(sqlArgs.begin(), sqlArgs.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + return std::make_shared(shared_from_this(), connectionPool, path, sql, bindArgs); +} + +std::shared_ptr RdbStoreImpl::QuerySql(const std::string &sql, + const std::vector &bindArgs) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); - return std::make_shared(shared_from_this(), connectionPool, path, sql, selectionArgs); + return std::make_shared(shared_from_this(), connectionPool, path, sql, bindArgs); } #endif #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) || defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) std::shared_ptr RdbStoreImpl::Query( - const AbsRdbPredicates &predicates, const std::vector columns) + const AbsRdbPredicates &predicates, const std::vector &columns) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); LOG_DEBUG("RdbStoreImpl::Query on called."); - std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns); - return QueryByStep(sql, selectionArgs); + return QueryByStep(sql, predicates.GetBindArgs()); } #endif int RdbStoreImpl::Count(int64_t &outValue, const AbsRdbPredicates &predicates) { - LOG_DEBUG("RdbStoreImpl::Count on called."); - std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildCountString(predicates); - std::vector bindArgs; - std::vector whereArgs = predicates.GetWhereArgs(); - for (const auto& whereArg : whereArgs) { - bindArgs.emplace_back(whereArg); - } - - return ExecuteAndGetLong(outValue, sql, bindArgs); + return ExecuteAndGetLong(outValue, sql, predicates.GetBindArgs()); } int RdbStoreImpl::ExecuteSql(const std::string &sql, const std::vector &bindArgs) @@ -1279,14 +1299,16 @@ int RdbStoreImpl::Restore(const std::string backupPath, const std::vector RdbStoreImpl::QueryByStep(const std::string &sql, - const std::vector &selectionArgs) + const std::vector &sqlArgs) { - return std::make_shared(shared_from_this(), connectionPool, sql, selectionArgs); + std::vector bindArgs; + std::for_each(sqlArgs.begin(), sqlArgs.end(), [&bindArgs](const auto &it) { bindArgs.push_back(ValueObject(it)); }); + return std::make_shared(shared_from_this(), connectionPool, sql, bindArgs); } -std::shared_ptr RdbStoreImpl::QueryByStep(const std::string &sql, std::vector &&args) +std::shared_ptr RdbStoreImpl::QueryByStep(const std::string &sql, const std::vector &args) { - return std::make_shared(shared_from_this(), connectionPool, sql, std::move(args)); + return std::make_shared(shared_from_this(), connectionPool, sql, args); } #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) @@ -1307,10 +1329,16 @@ int RdbStoreImpl::SetDistributedTables(const std::vector &tables, i LOG_ERROR("Fail to set distributed tables, error=%{public}d", errorCode); return errorCode; } - if (type == DistributedRdb::DISTRIBUTED_CLOUD && distributedConfig.autoSync) { + if (type != DistributedRdb::DISTRIBUTED_CLOUD || !distributedConfig.autoSync) { + return E_OK; + } + { std::unique_lock lock(rwMutex_); cloudTables_.insert(tables.begin(), tables.end()); } + for (auto &table : tables) { + DoCloudSync(table); + } return E_OK; } @@ -1597,11 +1625,5 @@ int RdbStoreImpl::Notify(const std::string &event) } return E_OK; } - -bool RdbStoreImpl::DropDeviceData(const std::vector &devices, const DropOption &option) -{ - LOG_INFO("not implement"); - return true; -} #endif -} // namespace OHOS::NativeRdb +} // namespace OHOS::NativeRdb \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp index a71f6cd6..1cf2d6b1 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp @@ -26,11 +26,13 @@ #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) #if !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) +#include "rdb_manager_impl.h" #include "rdb_security_manager.h" #endif #include "security_policy.h" #endif #include "sqlite_utils.h" +#include "string_utils.h" namespace OHOS { namespace NativeRdb { @@ -156,6 +158,25 @@ int RdbStoreManager::ProcessOpenCallback( return openCallback.OnOpen(rdbStore); } + +bool RdbStoreManager::Delete(const std::string &path) +{ +#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) + auto tokens = StringUtils::Split(path, "/"); + if (!tokens.empty()) { + DistributedRdb::RdbSyncerParam param; + param.storeName_ = *tokens.rbegin(); + auto [err, service] = DistributedRdb::RdbManagerImpl::GetInstance().GetRdbService(param); + if (err == E_OK && service != nullptr) { + err = service->Delete(param); + } + LOG_DEBUG("service delete store, storeName:%{public}s, err = %{public}d", + SqliteUtils::Anonymous(param.storeName_).c_str(), err); + } +#endif + return Remove(path); +} + int RdbStoreManager::SetSecurityLabel(const RdbStoreConfig &config) { #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) diff --git a/relational_store/frameworks/native/rdb/src/security_policy.cpp b/relational_store/frameworks/native/rdb/src/security_policy.cpp index 074c6411..69e19738 100644 --- a/relational_store/frameworks/native/rdb/src/security_policy.cpp +++ b/relational_store/frameworks/native/rdb/src/security_policy.cpp @@ -17,7 +17,7 @@ #include "logger.h" #include "rdb_errno.h" -#include "filemanagement/file_api/interfaces/kits/security_label.h" +#include "security_label.h" namespace OHOS { namespace NativeRdb { diff --git a/relational_store/frameworks/native/rdb/src/share_block.cpp b/relational_store/frameworks/native/rdb/src/share_block.cpp index 7f30cf69..a367f2ca 100644 --- a/relational_store/frameworks/native/rdb/src/share_block.cpp +++ b/relational_store/frameworks/native/rdb/src/share_block.cpp @@ -120,22 +120,17 @@ void FillSharedBlockOpt(SharedBlockInfo *info) return; } int retryCount = 0; - bool gotException = false; - while (!gotException) { + while (true) { int err = sqlite3_step(info->statement); - if (err == SQLITE_DONE) { - break; - } else if (err == SQLITE_LOCKED || err == SQLITE_BUSY) { + if (err == SQLITE_LOCKED || err == SQLITE_BUSY) { LOG_WARN("Database locked, retrying"); - if (retryCount > RETRY_TIME) { - gotException = true; - } else { + if (retryCount <= RETRY_TIME) { usleep(SLEEP_TIME); retryCount++; + continue; } - } else { - gotException = true; } + break; } info->totalRows = serializer.GetTotalRows(); info->startPos = serializer.GetStartPos(); diff --git a/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp b/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp index 622c19fe..9a3a918a 100644 --- a/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp +++ b/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp @@ -25,7 +25,7 @@ using namespace OHOS::Rdb; SharedBlockSerializerInfo::SharedBlockSerializerInfo(AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *stat, int numColumns, int startPos) : sharedBlock_(sharedBlock), statement_(stat), anumColumns(numColumns), atotalRows(0), astartPos(startPos), - raddedRows(0), risFull(false) + raddedRows(0) { } @@ -35,13 +35,11 @@ int SharedBlockSerializerInfo::AddRow(int addedRows) { // Allocate a new field directory for the row. int status = sharedBlock_->AllocRow(); - if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { - risFull = true; - return SQLITE_FULL; + if (status == AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { + raddedRows = addedRows + 1; + return SQLITE_OK; } - - raddedRows = addedRows + 1; - return SQLITE_OK; + return SQLITE_FULL; } int SharedBlockSerializerInfo::Reset(int startPos) @@ -57,7 +55,6 @@ int SharedBlockSerializerInfo::Reset(int startPos) } astartPos = startPos; raddedRows = 0; - risFull = false; return SQLITE_OK; } @@ -68,40 +65,24 @@ int SharedBlockSerializerInfo::Finish(int addedRows, int totalRows) return SQLITE_OK; } -int SharedBlockSerializerInfo::PutString(int row, int column, const char *text, int sizeIncludingNull) -{ - int status = sharedBlock_->PutString(row, column, text, sizeIncludingNull); - if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { - sharedBlock_->FreeLastRow(); - risFull = true; - return SQLITE_FULL; - } - - return SQLITE_OK; -} - int SharedBlockSerializerInfo::PutLong(int row, int column, sqlite3_int64 value) { int status = sharedBlock_->PutLong(row, column, value); - if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { - sharedBlock_->FreeLastRow(); - risFull = true; - return SQLITE_FULL; + if (status == AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { + return SQLITE_OK; } - - return SQLITE_OK; + sharedBlock_->FreeLastRow(); + return SQLITE_FULL; } int SharedBlockSerializerInfo::PutDouble(int row, int column, double value) { int status = sharedBlock_->PutDouble(row, column, value); - if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { - sharedBlock_->FreeLastRow(); - risFull = true; - return SQLITE_FULL; + if (status == AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { + return SQLITE_OK; } - - return SQLITE_OK; + sharedBlock_->FreeLastRow(); + return SQLITE_FULL; } int SharedBlockSerializerInfo::PutBlob(int row, int column, const void *blob, int len) @@ -117,26 +98,22 @@ int SharedBlockSerializerInfo::PutBlob(int row, int column, const void *blob, in } int status = (sharedBlock_->*action)(row, column, blob, len); - if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { - sharedBlock_->FreeLastRow(); - risFull = true; - return SQLITE_FULL; + if (status == AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { + return SQLITE_OK; } - - return SQLITE_OK; + sharedBlock_->FreeLastRow(); + return SQLITE_FULL; } int SharedBlockSerializerInfo::PutNull(int row, int column) { int status = sharedBlock_->PutNull(row, column); - if (status != AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { - sharedBlock_->FreeLastRow(); - risFull = true; - LOG_ERROR("Failed allocating space for a null in column %{public}d, error=%{public}d", column, status); - return SQLITE_FULL; + if (status == AppDataFwk::SharedBlock::SHARED_BLOCK_OK) { + return SQLITE_OK; } - - return SQLITE_OK; + sharedBlock_->FreeLastRow(); + LOG_ERROR("Failed allocating space for a null in column %{public}d, error=%{public}d", column, status); + return SQLITE_FULL; } int SharedBlockSerializerInfo::PutOther(int row, int column) @@ -144,20 +121,5 @@ int SharedBlockSerializerInfo::PutOther(int row, int column) sharedBlock_->FreeLastRow(); return SQLITE_ERROR; } - -int SharedBlockSerializerInfo::GetTotalRows() const -{ - return atotalRows; -} - -int SharedBlockSerializerInfo::GetAddedRows() const -{ - return raddedRows; -} - -int SharedBlockSerializerInfo::GetStartPos() const -{ - return astartPos; -} } // namespace NativeRdb } // namespace OHOS \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp index 823f4fe1..6ed2890d 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp @@ -686,30 +686,6 @@ int SqliteConnection::ExecuteGetString( return errCode; } -std::shared_ptr SqliteConnection::BeginStepQuery( - int &errCode, const std::string &sql, const std::vector &selectionArgs) const -{ - if (!stepStatement) { - return nullptr; - } - errCode = stepStatement->Prepare(dbHandle, sql); - if (errCode != E_OK) { - return nullptr; - } - - std::vector bindArgs; - for (auto item : selectionArgs) { - bindArgs.push_back(ValueObject(item)); - } - - errCode = stepStatement->BindArguments(bindArgs); - if (errCode != E_OK) { - return nullptr; - } - - return stepStatement; -} - std::shared_ptr SqliteConnection::BeginStepQuery(int &errCode, const std::string &sql, const std::vector &args) const { diff --git a/relational_store/frameworks/native/rdb/src/sqlite_shared_result_set.cpp b/relational_store/frameworks/native/rdb/src/sqlite_shared_result_set.cpp index c2c9c4bc..247b62b7 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_shared_result_set.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_shared_result_set.cpp @@ -29,9 +29,9 @@ namespace NativeRdb { using namespace OHOS::Rdb; SqliteSharedResultSet::SqliteSharedResultSet(std::shared_ptr store, SqliteConnectionPool *connectionPool, - std::string path, std::string sql, const std::vector &bindArgs) + std::string path, std::string sql, const std::vector &bindArgs) : AbsSharedResultSet(path), store_(store), connectionPool_(connectionPool), resultSetBlockCapacity(0), - isOnlyFillResultSetBlock(false), qrySql(sql), selectionArgVec(bindArgs), rowNum(NO_COUNT) + isOnlyFillResultSetBlock(false), qrySql(sql), bindArgs_(std::move(bindArgs)), rowNum(NO_COUNT) { } @@ -47,7 +47,7 @@ std::shared_ptr SqliteSharedResultSet::PrepareStep(SqliteConnec } std::shared_ptr sqliteStatement = connection->BeginStepQuery(errCode, - qrySql, selectionArgVec); + qrySql, bindArgs_); if (sqliteStatement == nullptr) { connection->EndStepQuery(); } @@ -152,40 +152,34 @@ int SqliteSharedResultSet::PickFillBlockStartPosition(int resultSetPosition, int void SqliteSharedResultSet::FillSharedBlock(int requiredPos) { ClearBlock(); - - std::vector bindArgs; - size_t size = selectionArgVec.size(); - bindArgs.reserve(size); - for (size_t i = 0; i < size; i++) { - ValueObject vauObj(selectionArgVec[i]); - bindArgs.push_back(vauObj); - } - SqliteConnection* connection = connectionPool_->AcquireConnection(true); if (connection == nullptr) { return; } - + AppDataFwk::SharedBlock *sharedBlock = GetBlock(); + if (sharedBlock == nullptr) { + return; + } if (rowNum == NO_COUNT) { - connection->ExecuteForSharedBlock(rowNum, qrySql, bindArgs, GetBlock(), requiredPos, requiredPos, true); - resultSetBlockCapacity = static_cast(GetBlock()->GetRowNum()); + connection->ExecuteForSharedBlock(rowNum, qrySql, bindArgs_, sharedBlock, requiredPos, requiredPos, true); + resultSetBlockCapacity = static_cast(sharedBlock->GetRowNum()); if (resultSetBlockCapacity > 0) { - GetBlock()->SetStartPos(requiredPos); - GetBlock()->SetBlockPos(0); - GetBlock()->SetLastPos(requiredPos + resultSetBlockCapacity); + sharedBlock->SetStartPos(requiredPos); + sharedBlock->SetBlockPos(0); + sharedBlock->SetLastPos(requiredPos + resultSetBlockCapacity); } } else { int blockRowNum = rowNum; int startPos = isOnlyFillResultSetBlock ? requiredPos : PickFillBlockStartPosition(requiredPos, resultSetBlockCapacity); - connection->ExecuteForSharedBlock(blockRowNum, qrySql, bindArgs, GetBlock(), startPos, requiredPos, false); - int currentBlockCapacity = static_cast(GetBlock()->GetRowNum()); - GetBlock()->SetStartPos((uint32_t)startPos); - GetBlock()->SetBlockPos(requiredPos - startPos); - GetBlock()->SetLastPos(startPos + currentBlockCapacity); + connection->ExecuteForSharedBlock(blockRowNum, qrySql, bindArgs_, sharedBlock, startPos, requiredPos, false); + int currentBlockCapacity = static_cast(sharedBlock->GetRowNum()); + sharedBlock->SetStartPos((uint32_t)startPos); + sharedBlock->SetBlockPos(requiredPos - startPos); + sharedBlock->SetLastPos(startPos + currentBlockCapacity); LOG_INFO("requiredPos= %{public}d, startPos_= %{public}" PRIu32 ", lastPos_= %{public}" PRIu32 ", blockPos_= %{public}" PRIu32 ".", - requiredPos, GetBlock()->GetStartPos(), GetBlock()->GetLastPos(), GetBlock()->GetBlockPos()); + requiredPos, sharedBlock->GetStartPos(), sharedBlock->GetLastPos(), sharedBlock->GetBlockPos()); } connectionPool_->ReleaseConnection(connection); } diff --git a/relational_store/frameworks/native/rdb/src/sqlite_sql_builder.cpp b/relational_store/frameworks/native/rdb/src/sqlite_sql_builder.cpp index 7b99651a..43cca8e3 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_sql_builder.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_sql_builder.cpp @@ -15,7 +15,8 @@ #include "sqlite_sql_builder.h" -#include +#include +#include #include "logger.h" #include "rdb_errno.h" @@ -75,35 +76,12 @@ std::string SqliteSqlBuilder::BuildUpdateString(const ValuesBucket &values, cons return sql; } -std::string SqliteSqlBuilder::BuildUpdateStringOnlyWhere(const ValuesBucket &values, const std::string &tableName, - const std::vector &whereArgs, const std::string &index, const std::string &whereClause, - const std::string &group, const std::string &order, int limit, int offset, std::vector &bindArgs, - ConflictResolution conflictResolution) -{ - std::string sql; - - sql.append("UPDATE") - .append(g_onConflictClause[static_cast(conflictResolution)]) - .append(" ") - .append(tableName) - .append(" SET "); - - if (!whereArgs.empty()) { - for (size_t i = 0; i < whereArgs.size(); i++) { - bindArgs.push_back(ValueObject(whereArgs[i])); - } - } - - sql.append(BuildSqlStringFromPredicates(index, whereClause, group, order, limit, offset)); - return sql; -} - /** * Build a query SQL string using the given condition for SQLite. */ -int SqliteSqlBuilder::BuildQueryString(bool distinct, const std::string &table, const std::vector &columns, - const std::string &where, const std::string &groupBy, const std::string &having, const std::string &orderBy, - const std::string &limit, const std::string &offset, std::string &outSql) +int SqliteSqlBuilder::BuildQueryString(bool distinct, const std::string &table, + const std::vector &columns, const std::string &whereClause, const std::string &groupBy, + const std::string &indexName, const std::string &orderBy, const int &limit, const int &offset, std::string &outSql) { if (table.empty()) { return E_EMPTY_TABLE_NAME; @@ -114,43 +92,16 @@ int SqliteSqlBuilder::BuildQueryString(bool distinct, const std::string &table, if (distinct) { sql.append("DISTINCT "); } - int errorCode = 0; if (columns.size() != 0) { - AppendColumns(sql, columns, errorCode); + AppendColumns(sql, columns); } else { sql.append("* "); } - int climit = std::stoi(limit); - int coffset = std::stoi(offset); sql.append("FROM ").append(table).append( - BuildSqlStringFromPredicates(having, where, groupBy, orderBy, climit, coffset)); + BuildSqlStringFromPredicates(indexName, whereClause, groupBy, orderBy, limit, offset)); outSql = sql; - return errorCode; -} - -/** - * Build a query SQL string using the given condition for SQLite. - */ -std::string SqliteSqlBuilder::BuildQueryStringWithExpr(const std::string &tableName, bool distinct, - const std::string &index, const std::string &whereClause, const std::string &group, const std::string &order, - int limit, int offset, std::vector &expr) -{ - std::string sql; - - sql.append("SELECT "); - if (distinct) { - sql.append("DISTINCT "); - } - if (expr.size() != 0) { - AppendExpr(sql, expr); - } else { - sql.append("* "); - } - sql.append("FROM ").append(tableName).append( - BuildSqlStringFromPredicates(index, whereClause, group, order, limit, offset)); - - return sql; + return E_OK; } /** @@ -171,8 +122,8 @@ std::string SqliteSqlBuilder::BuildSqlStringFromPredicates(const std::string &in { std::string sqlString; - std::string limitStr = (limit == INT_MIN) ? "" : std::to_string(limit); - std::string offsetStr = (offset == INT_MIN) ? "" : std::to_string(offset); + std::string limitStr = (limit == AbsPredicates::INIT_LIMIT_VALUE) ? "" : std::to_string(limit); + std::string offsetStr = (offset == AbsPredicates::INIT_OFFSET_VALUE) ? "" : std::to_string(offset); AppendClause(sqlString, " INDEXED BY ", index); AppendClause(sqlString, " WHERE ", whereClause); @@ -184,13 +135,14 @@ std::string SqliteSqlBuilder::BuildSqlStringFromPredicates(const std::string &in return sqlString; } -std::string SqliteSqlBuilder::BuildSqlStringFromPredicates(const AbsRdbPredicates &predicates) +std::string SqliteSqlBuilder::BuildSqlStringFromPredicates(const AbsPredicates &predicates) { - std::string sqlString; - - std::string limitStr = (predicates.GetLimit() == INT_MIN) ? "" : std::to_string(predicates.GetLimit()); - std::string offsetStr = (predicates.GetOffset() == INT_MIN) ? "" : std::to_string(predicates.GetOffset()); + std::string limitStr = + (predicates.GetLimit() == AbsPredicates::INIT_LIMIT_VALUE) ? "" : std::to_string(predicates.GetLimit()); + std::string offsetStr = + (predicates.GetOffset() == AbsPredicates::INIT_OFFSET_VALUE) ? "" : std::to_string(predicates.GetOffset()); + std::string sqlString; AppendClause(sqlString, " INDEXED BY ", predicates.GetIndex()); AppendClause(sqlString, " WHERE ", predicates.GetWhereClause()); AppendClause(sqlString, " GROUP BY ", predicates.GetGroup()); @@ -204,10 +156,10 @@ std::string SqliteSqlBuilder::BuildSqlStringFromPredicates(const AbsRdbPredicate std::string SqliteSqlBuilder::BuildSqlStringFromPredicatesNoWhere(const std::string &index, const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset) { - std::string sqlString; - std::string limitStr = (limit == INT_MIN) ? "" : std::to_string(limit); - std::string offsetStr = (offset == INT_MIN) ? "" : std::to_string(offset); + std::string limitStr = (limit == AbsPredicates::INIT_LIMIT_VALUE) ? "" : std::to_string(limit); + std::string offsetStr = (offset == AbsPredicates::INIT_OFFSET_VALUE) ? "" : std::to_string(offset); + std::string sqlString; AppendClause(sqlString, " INDEXED BY ", index); AppendClause(sqlString, " ", whereClause); AppendClause(sqlString, " GROUP BY ", group); @@ -230,7 +182,7 @@ void SqliteSqlBuilder::AppendClause(std::string &builder, const std::string &nam /** * Add the names that are non-null in columns to s, separating them with commas. */ -void SqliteSqlBuilder::AppendColumns(std::string &builder, const std::vector &columns, int &errorCode) +void SqliteSqlBuilder::AppendColumns(std::string &builder, const std::vector &columns) { size_t length = columns.size(); for (size_t i = 0; i < length; i++) { @@ -247,24 +199,6 @@ void SqliteSqlBuilder::AppendColumns(std::string &builder, const std::vector &exprs) -{ - size_t length = exprs.size(); - - for (size_t i = 0; i < length; i++) { - std::string expr = exprs[i]; - - if (expr.size() != 0) { - if (i > 0) { - builder.append(", "); - } - builder.append(expr); - } - } - - builder += ' '; -} - std::string SqliteSqlBuilder::BuildQueryString( const AbsRdbPredicates &predicates, const std::vector &columns) { @@ -274,11 +208,11 @@ std::string SqliteSqlBuilder::BuildQueryString( std::string groupStr = predicates.GetGroup(); std::string indexStr = predicates.GetIndex(); std::string orderStr = predicates.GetOrder(); - std::string limitStr = std::to_string(predicates.GetLimit()); - std::string offsetStr = std::to_string(predicates.GetOffset()); + int limit = predicates.GetLimit(); + int offset = predicates.GetOffset(); std::string sqlStr; BuildQueryString( - distinct, tableNameStr, columns, whereClauseStr, groupStr, indexStr, orderStr, limitStr, offsetStr, sqlStr); + distinct, tableNameStr, columns, whereClauseStr, groupStr, indexStr, orderStr, limit, offset, sqlStr); return sqlStr; } diff --git a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp index 12f4aca9..a99338a1 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp @@ -94,7 +94,7 @@ int SqliteStatement::BindArguments(const std::vector &bindArgs) con abindArgs.push_back(i); } - for (int i = count; i < numParameters; i++) { + for (int i = count; i < numParameters; i++) { // TD: when count <> numParameters ValueObject val; abindArgs.push_back(val); } diff --git a/relational_store/frameworks/native/rdb/src/step_result_set.cpp b/relational_store/frameworks/native/rdb/src/step_result_set.cpp index 28211692..b6400bf4 100644 --- a/relational_store/frameworks/native/rdb/src/step_result_set.cpp +++ b/relational_store/frameworks/native/rdb/src/step_result_set.cpp @@ -30,18 +30,8 @@ namespace NativeRdb { using namespace OHOS::Rdb; StepResultSet::StepResultSet(std::shared_ptr rdb, SqliteConnectionPool *connectionPool, - const std::string &sql, const std::vector &selectionArgs) - : rdb(rdb), connectionPool_(connectionPool), sql(sql), isAfterLast(false), - rowCount(INIT_POS), sqliteStatement(nullptr), connection_(connectionPool_->AcquireConnection(true)) -{ - for (auto arg : selectionArgs) { - args_.push_back(ValueObject(std::move(arg))); - } -} - -StepResultSet::StepResultSet(std::shared_ptr rdb, SqliteConnectionPool *pool, - const std::string &sql, std::vector &&args) - : rdb(rdb), connectionPool_(pool), sql(sql), args_(std::move(args)), isAfterLast(false), + const std::string &sql, const std::vector &selectionArgs) + : rdb(rdb), connectionPool_(connectionPool), sql(sql), args_(std::move(selectionArgs)), isAfterLast(false), rowCount(INIT_POS), sqliteStatement(nullptr), connection_(connectionPool_->AcquireConnection(true)) { } diff --git a/relational_store/frameworks/native/rdb/src/string_utils.cpp b/relational_store/frameworks/native/rdb/src/string_utils.cpp index 52242138..936b8986 100644 --- a/relational_store/frameworks/native/rdb/src/string_utils.cpp +++ b/relational_store/frameworks/native/rdb/src/string_utils.cpp @@ -32,7 +32,7 @@ std::string StringUtils::SurroundWithFunction(const std::string &function, const std::string builder(function); builder += "("; bool isFirst = true; - for (auto &text : array) { + for (const auto &text : array) { if (!isFirst) { builder = builder + " " + separator + " "; } else { @@ -44,6 +44,22 @@ std::string StringUtils::SurroundWithFunction(const std::string &function, const return builder; } +std::vector StringUtils::Split(const std::string &str, const std::string &delim) +{ + std::vector res; + size_t pos = 0; + while (pos < str.size()) { + size_t found = str.find(delim, pos); + if (found == std::string::npos) { + res.push_back(str.substr(pos)); + break; + } + res.push_back(str.substr(pos, found - pos)); + pos = found + delim.size(); + } + return res; +} + StringUtils::StringUtils() {} StringUtils::~StringUtils() {} } // namespace NativeRdb diff --git a/relational_store/frameworks/native/rdb/src/value_object.cpp b/relational_store/frameworks/native/rdb/src/value_object.cpp index 92121c9c..69035a23 100644 --- a/relational_store/frameworks/native/rdb/src/value_object.cpp +++ b/relational_store/frameworks/native/rdb/src/value_object.cpp @@ -24,7 +24,7 @@ ValueObject::ValueObject() { } -ValueObject::ValueObject(ValueObject::Type val) noexcept : value(std::move(val)) +ValueObject::ValueObject(Type val) noexcept : value(std::move(val)) { } @@ -132,7 +132,28 @@ int ValueObject::GetBool(bool &val) const int ValueObject::GetString(std::string &val) const { - return Get(val); + if (Get(val) == 0) { + return E_OK; + } + + double ftmp; + if (Get(ftmp) == 0) { + val = std::to_string(ftmp); + return E_OK; + } + + int64_t itmp; + if (Get(itmp) == 0) { + val = std::to_string(itmp); + return E_OK; + } + + bool btmp; + if (Get(btmp) == 0) { + val = std::to_string(btmp); + return E_OK; + } + return E_INVALID_OBJECT_TYPE; } int ValueObject::GetBlob(std::vector &val) const diff --git a/relational_store/frameworks/native/rdb/src/values_bucket.cpp b/relational_store/frameworks/native/rdb/src/values_bucket.cpp index 6b166b93..a09e39c4 100644 --- a/relational_store/frameworks/native/rdb/src/values_bucket.cpp +++ b/relational_store/frameworks/native/rdb/src/values_bucket.cpp @@ -91,11 +91,6 @@ void ValuesBucket::Put(const std::string &columnName, const ValueObject &value) values_.insert_or_assign(columnName, value); } -void ValuesBucket::Put(const std::string &columnName, ValueObject &&value) -{ - values_.insert_or_assign(columnName, std::move(value)); -} - void ValuesBucket::Delete(const std::string &columnName) { values_.erase(columnName); diff --git a/relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp b/relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp index 40d041ac..2645d719 100644 --- a/relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp +++ b/relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp @@ -56,26 +56,25 @@ RdbPredicates RdbUtils::ToPredicates(const DataShareAbsPredicates &predicates, c std::string RdbUtils::ToString(const DataSharePredicatesObject &predicatesObject) { - std::string str = " "; if (auto *val = std::get_if(&predicatesObject.value)) { - str = std::to_string(*val); + return std::to_string(*val); } if (auto *val = std::get_if(&predicatesObject.value)) { - str = std::to_string(*val); + return std::to_string(*val); } if (auto *val = std::get_if(&predicatesObject.value)) { - str = *val; + return *val; } if (auto *val = std::get_if(&predicatesObject.value)) { - str = std::to_string(*val); + return std::to_string(*val); } if (auto *val = std::get_if(&predicatesObject.value)) { - str = std::to_string(*val); + return std::to_string(*val); } if (auto *val = std::get_if(&predicatesObject.value)) { LOG_INFO("RdbUtils::ToString No matching type"); } - return str; + return " "; } std::shared_ptr RdbUtils::ToResultSetBridge(std::shared_ptr resultSet) diff --git a/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h b/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h index 6caef642..22550d7b 100644 --- a/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h +++ b/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h @@ -314,10 +314,11 @@ public: private: std::string mName; sptr ashmem_; - void *mData; + uint8_t *mData; size_t mSize; bool mReadOnly; - static const size_t ROW_OFFSETS_NUM = 100; + static const size_t ROW_NUM_IN_A_GROUP = 128; + static const uint32_t GROUP_NUM = 128; /** * Default setting for SQLITE_MAX_COLUMN is 2000. * We can set it at compile time to as large as 32767 @@ -327,8 +328,6 @@ private: struct SharedBlockHeader { /* Offset of the lowest unused byte in the block. */ uint32_t unusedOffset; - /* Offset of the first row group. */ - uint32_t firstRowGroupOffset; /* Row numbers of the row group block. */ uint32_t rowNums; /* Column numbers of the row group block. */ @@ -339,11 +338,11 @@ private: uint32_t lastPos_; /* current position of the current block. */ uint32_t blockPos_; + uint32_t groupOffset[GROUP_NUM]; }; struct RowGroupHeader { - uint32_t rowOffsets[ROW_OFFSETS_NUM]; - uint32_t nextGroupOffset; + uint32_t rowOffsets[ROW_NUM_IN_A_GROUP]; }; SharedBlockHeader *mHeader; @@ -352,30 +351,21 @@ private: * Allocate a portion of the block. Returns the offset of the allocation. * Returns 0 if there isn't enough space. */ - uint32_t Alloc(size_t size, bool aligned = false); + inline uint32_t Alloc(size_t size); - uint32_t *GetRowOffset(uint32_t row); + inline uint32_t *AllocRowOffset(); - uint32_t *AllocRowOffset(); - - int PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type); + inline int PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type); static int CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, SharedBlock *&outSharedBlock); - uint32_t OffsetFromPtr(void *ptr); - - void *OffsetToPtr(uint32_t offset, uint32_t bufferSize = 0); - - /** - * Convert utf8 string to utf16. - */ - static std::u16string ToUtf16(std::string str); - - /** - * Convert utf16 string to utf8. - */ - static std::string ToUtf8(std::u16string str16); + inline void *OffsetToPtr(uint32_t offset, uint32_t bufferSize = 0) { + if (offset + bufferSize > mSize) { + return nullptr; + } + return mData + offset; + } }; } // namespace AppDataFwk } // namespace OHOS diff --git a/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h b/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h index 84e854af..d322b0f2 100644 --- a/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h +++ b/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h @@ -30,6 +30,7 @@ public: TRANS_NOTIFY_DATA_CHANGE, TRANS_BUTT, }; + enum Action : int32_t { CLEAR_CLOUD_INFO, CLEAR_CLOUD_DATA_AND_INFO, diff --git a/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h b/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h index 05a4ed72..02d9f7d5 100644 --- a/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h +++ b/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h @@ -21,6 +21,8 @@ #include #include "abs_predicates.h" +#include "value_object.h" + namespace OHOS { namespace NativeRdb { /** @@ -39,16 +41,24 @@ public: API_EXPORT ~PredicatesUtils() {} /** - * @brief Set the parameter of whereClause and whereArgs of the specified Predicates. + * @brief Set the parameter of whereClause and bindArgs of the specified Predicates. + */ + [[deprecated("Use SetWhereClauseAndArgs(AbsPredicates *, const std::string &," + " const std::vector &) instead.")]] + API_EXPORT static void SetWhereClauseAndArgs(AbsPredicates *predicates, const std::string &whereClause, + const std::vector &whereArgs); + + /** + * @brief Set the parameter of whereClause and bindArgs of the specified Predicates. */ - API_EXPORT static void SetWhereClauseAndArgs(AbsPredicates *predicates, std::string whereClause, - std::vector whereArgs); + API_EXPORT static void SetWhereClauseAndArgs(AbsPredicates *predicates, const std::string &whereClause, + const std::vector &bindArgs); /** * @brief Sets parameters of the specified Predicates including distinct, index, group, order, limit and offset. */ - API_EXPORT static void SetAttributes(AbsPredicates *predicates, bool isDistinct, std::string index, - std::string group, std::string order, int limit, int offset); + API_EXPORT static void SetAttributes(AbsPredicates *predicates, bool isDistinct, const std::string &index, + const std::string &group, const std::string &order, const int limit, const int offset); }; } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h b/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h index f977eecd..fa2accf3 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h @@ -16,14 +16,19 @@ #ifndef NATIVE_RDB_ABSPREDICATES_H #define NATIVE_RDB_ABSPREDICATES_H +#include #include #include + #include "rdb_visibility.h" +#include "value_object.h" namespace OHOS { namespace NativeRdb { class API_EXPORT AbsPredicates { public: + static constexpr int INIT_LIMIT_VALUE = INT_MIN; + static constexpr int INIT_OFFSET_VALUE = INT_MIN; API_EXPORT AbsPredicates(); API_EXPORT virtual ~AbsPredicates(); @@ -33,10 +38,15 @@ public: CROSS }; + API_EXPORT std::string GetStatement() const; API_EXPORT std::string GetWhereClause() const; API_EXPORT void SetWhereClause(const std::string &whereClause); + [[deprecated("Use GetBindArgs() instead.")]] API_EXPORT std::vector GetWhereArgs() const; + API_EXPORT std::vector GetBindArgs() const; + [[deprecated("Use SetBindArgs() instead.")]] API_EXPORT void SetWhereArgs(const std::vector &whereArgs); + API_EXPORT void SetBindArgs(const std::vector &bindArgs); API_EXPORT std::string GetOrder() const; API_EXPORT void SetOrder(const std::string &order); API_EXPORT int GetLimit() const; @@ -49,8 +59,8 @@ public: public: API_EXPORT virtual void Clear(); - API_EXPORT virtual AbsPredicates *EqualTo(const std::string &field, const std::string &value); - API_EXPORT virtual AbsPredicates *NotEqualTo(const std::string &field, const std::string &value); + API_EXPORT virtual AbsPredicates *EqualTo(const std::string &field, const ValueObject &value); + API_EXPORT virtual AbsPredicates *NotEqualTo(const std::string &field, const ValueObject &value); API_EXPORT virtual AbsPredicates *BeginWrap(); API_EXPORT virtual AbsPredicates *EndWrap(); API_EXPORT virtual AbsPredicates *Or(); @@ -62,26 +72,31 @@ public: API_EXPORT virtual AbsPredicates *IsNotNull(const std::string &field); API_EXPORT virtual AbsPredicates *Like(const std::string &field, const std::string &value); API_EXPORT virtual AbsPredicates *Glob(const std::string &field, const std::string &value); - API_EXPORT virtual AbsPredicates *Between(std::string field, std::string low, std::string high); - API_EXPORT virtual AbsPredicates *NotBetween(std::string field, std::string low, std::string high); - API_EXPORT virtual AbsPredicates *GreaterThan(const std::string &field, const std::string &value); - API_EXPORT virtual AbsPredicates *LessThan(const std::string &field, const std::string &value); - API_EXPORT virtual AbsPredicates *GreaterThanOrEqualTo(const std::string &field, const std::string &value); - API_EXPORT virtual AbsPredicates *LessThanOrEqualTo(const std::string &field, const std::string &value); + API_EXPORT virtual AbsPredicates *Between( + const std::string &field, const ValueObject &low, const ValueObject &high); + API_EXPORT virtual AbsPredicates *NotBetween( + const std::string &field, const ValueObject &low, const ValueObject &high); + API_EXPORT virtual AbsPredicates *GreaterThan(const std::string &field, const ValueObject &value); + API_EXPORT virtual AbsPredicates *LessThan(const std::string &field, const ValueObject &value); + API_EXPORT virtual AbsPredicates *GreaterThanOrEqualTo(const std::string &field, const ValueObject &value); + API_EXPORT virtual AbsPredicates *LessThanOrEqualTo(const std::string &field, const ValueObject &value); API_EXPORT virtual AbsPredicates *OrderByAsc(const std::string &field); API_EXPORT virtual AbsPredicates *OrderByDesc(const std::string &field); API_EXPORT virtual AbsPredicates *Distinct(); - API_EXPORT virtual AbsPredicates *Limit(int limit); - API_EXPORT virtual AbsPredicates *Limit(int offset, int limit); - API_EXPORT virtual AbsPredicates *Offset(int offset); + API_EXPORT virtual AbsPredicates *Limit(const int limit); + API_EXPORT virtual AbsPredicates *Limit(const int offset, const int limit); + API_EXPORT virtual AbsPredicates *Offset(const int offset); API_EXPORT virtual AbsPredicates *GroupBy(const std::vector &fields); API_EXPORT virtual AbsPredicates *IndexedBy(const std::string &indexName); + [[deprecated("Use In(const std::string &, const std::vector &) instead.")]] API_EXPORT virtual AbsPredicates *In(const std::string &field, const std::vector &values); + API_EXPORT virtual AbsPredicates *In(const std::string &field, const std::vector &values); + [[deprecated("Use NotIn(const std::string &, const std::vector &) instead.")]] API_EXPORT virtual AbsPredicates *NotIn(const std::string &field, const std::vector &values); - + API_EXPORT virtual AbsPredicates *NotIn(const std::string &field, const std::vector &values); private: std::string whereClause; - std::vector whereArgs; + std::vector bindArgs; std::string order; std::string group; std::string index; @@ -93,7 +108,7 @@ private: void Initial(); bool CheckParameter( - const std::string &methodName, const std::string &field, const std::initializer_list &args) const; + const std::string &methodName, const std::string &field, const std::initializer_list &args) const; std::string RemoveQuotes(const std::string &source) const; void CheckIsNeedAnd(); void AppendWhereClauseWithInOrNotIn(const std::string &methodName, const std::string &field, diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h b/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h index f1e513c6..d709938e 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h @@ -57,6 +57,7 @@ public: /** * @brief Obtains the parameters of the current AbsRdbPredicates object. */ + [[deprecated("Use GetStatement() instead.")]] API_EXPORT std::string ToString() const; /** @@ -94,7 +95,7 @@ public: * * @return Returns the self. */ - API_EXPORT AbsRdbPredicates* EqualTo(const std::string &field, const std::string &value) override; + API_EXPORT AbsRdbPredicates* EqualTo(const std::string &field, const ValueObject &value) override; /** * @brief Restricts the value of the field to be not equal to the specified value to the remote AbsRdbPredicates. @@ -106,7 +107,7 @@ public: * * @return Returns the self. */ - API_EXPORT AbsRdbPredicates* NotEqualTo(const std::string &field, const std::string &value) override; + API_EXPORT AbsRdbPredicates* NotEqualTo(const std::string &field, const ValueObject &value) override; /** * @brief Adds an and condition to the remote AbsRdbPredicates. diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h b/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h index 73dc022f..b9095a41 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h @@ -215,7 +215,6 @@ public: protected: int CheckState(int columnIndex); void ClearBlock(); - void InitBlock(); void ClosedBlock(); virtual void Finalize(); diff --git a/relational_store/interfaces/inner_api/rdb/include/distributeddata_relational_store_ipc_interface_code.h b/relational_store/interfaces/inner_api/rdb/include/distributeddata_relational_store_ipc_interface_code.h index 69ca73e6..491bcd20 100644 --- a/relational_store/interfaces/inner_api/rdb/include/distributeddata_relational_store_ipc_interface_code.h +++ b/relational_store/interfaces/inner_api/rdb/include/distributeddata_relational_store_ipc_interface_code.h @@ -75,6 +75,7 @@ enum class RdbServiceInterfaceCode { RDB_SERVICE_CMD_UNSUBSCRIBE, RDB_SERVICE_CMD_REMOTE_QUERY, RDB_SERVICE_CMD_GET_SCHEMA, + RDB_SERVICE_CMD_DELETE, RDB_SERVICE_CMD_MAX }; } // namespace RelationalStore diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_predicates.h b/relational_store/interfaces/inner_api/rdb/include/rdb_predicates.h index 67be56ec..c6134283 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_predicates.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_predicates.h @@ -70,16 +70,6 @@ public: */ API_EXPORT RdbPredicates *On(const std::vector &clauses); - /** - * @brief Get statement with predicates. - */ - API_EXPORT std::string GetStatement(); - - /** - * @brief Get arguments with predicates. - */ - API_EXPORT std::vector GetBindArgs(); - private: std::string ProcessJoins() const; std::string GetGrammar(int type) const; diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_service.h b/relational_store/interfaces/inner_api/rdb/include/rdb_service.h index 528fbf53..4d3dbc49 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_service.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_service.h @@ -57,6 +57,9 @@ public: virtual int32_t GetSchema(const RdbSyncerParam ¶m) = 0; + //only use param.storeName_ + virtual int32_t Delete(const RdbSyncerParam ¶m) = 0; + inline static constexpr const char *SERVICE_NAME = "relational_store"; }; } diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_store.h b/relational_store/interfaces/inner_api/rdb/include/rdb_store.h index 08b1e29c..847ce7f1 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_store.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_store.h @@ -42,7 +42,6 @@ public: */ using Briefs = DistributedRdb::Briefs; using AsyncBrief = DistributedRdb::AsyncBrief; - using SyncCallback = AsyncBrief; /** * @brief Use AsyncBrief replace DistributedRdb::AsyncBrief namespace. @@ -126,9 +125,22 @@ public: * @param whereClause Indicates the where clause. * @param whereArgs Indicates the where arguments. */ + [[deprecated("Use Update(int &, const std::string &, const ValuesBucket &, const std::string &," + " const std::vector &) instead.")]] virtual int Update(int &changedRows, const std::string &table, const ValuesBucket &values, - const std::string &whereClause = "", - const std::vector &whereArgs = std::vector()) = 0; + const std::string &whereClause, const std::vector &whereArgs) = 0; + + /** + * @brief Updates data in the database based on specified conditions. + * + * @param table Indicates the target table. + * @param values Indicates the row of data to be updated in the database. + * The key-value pairs are associated with column names of the database table. + * @param whereClause Indicates the where clause. + * @param bindArgs Indicates the where arguments. + */ + virtual int Update(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause = "", const std::vector &bindArgs = {}) = 0; /** * @brief Updates data in the database based on a a specified instance object of RdbPredicates. @@ -140,8 +152,25 @@ public: * @param whereArgs Indicates the where arguments. * @param conflictResolution Indicates the {@link ConflictResolution} to insert data into the table. */ + [[deprecated("Use UpdateWithConflictResolution(int &, const std::string &, const ValuesBucket &, " + "const std::string &, const std::vector &," + " ConflictResolution conflictResolution) instead.")]] virtual int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, - const std::string &whereClause = "", const std::vector &whereArgs = std::vector(), + const std::string &whereClause, const std::vector &whereArgs, + ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; + + /** + * @brief Updates data in the database based on a a specified instance object of RdbPredicates. + * + * @param table Indicates the target table. + * @param values Indicates the row of data to be updated in the database. + * The key-value pairs are associated with column names of the database table. + * @param whereClause Indicates the where clause. + * @param whereArgs Indicates the where arguments. + * @param conflictResolution Indicates the {@link ConflictResolution} to insert data into the table. + */ + virtual int UpdateWithConflictResolution(int &changedRows, const std::string &table, + const ValuesBucket &values, const std::string &whereClause = "", const std::vector &bindArgs = {}, ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; /** @@ -151,8 +180,20 @@ public: * @param whereClause Indicates the where clause. * @param whereArgs Indicates the where arguments. */ + [[deprecated("Use Delete(int &, const std::string &, const std::string &, const std::vector &) " + "instead.")]] + virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &whereArgs) = 0; + + /** + * @brief Deletes data from the database based on specified conditions. + * + * @param table Indicates the target table. + * @param whereClause Indicates the where clause. + * @param bindArgs Indicates the where arguments. + */ virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause = "", - const std::vector &whereArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; /** * @brief Queries data in the database based on specified conditions. @@ -160,35 +201,54 @@ public: * @param distinct Indicates whether to eliminate all duplicate records in the result set. * @param table Indicates the target table. * @param columns Indicates the columns to query. If the value is empty array, the query applies to all columns. - * @param selection Indicates the selection. - * @param selectionArgs Indicates the selection arguments. + * @param whereClause Indicates the selection. + * @param bindArgs Indicates the selection arguments. * @param groupBy Indicates the groupBy argument. - * @param having Indicates the having argument. + * @param indexName Indicates the index by argument. * @param orderBy Indicates the orderBy argument. * @param limit Indicates the limit argument. */ virtual std::shared_ptr Query(int &errCode, bool distinct, const std::string &table, - const std::vector &columns, const std::string &selection = "", - const std::vector &selectionArgs = std::vector(), const std::string &groupBy = "", - const std::string &having = "", const std::string &orderBy = "", const std::string &limit = "") = 0; + const std::vector &columns, const std::string &whereClause = "", + const std::vector &bindArgs = {}, const std::string &groupBy = "", + const std::string &indexName = "", const std::string &orderBy = "", + const int &limit = AbsPredicates::INIT_LIMIT_VALUE, const int &offset = AbsPredicates::INIT_LIMIT_VALUE) = 0; /** * @brief Queries data in the database based on SQL statement. * * @param sql Indicates the SQL statement to execute. - * @param selectionArgs Indicates the selection arguments. + * @param sqlArgs Indicates the selection arguments. */ + [[deprecated("Use QuerySql(const std::string &, const std::vector &) instead.")]] virtual std::shared_ptr QuerySql( - const std::string &sql, const std::vector &selectionArgs = std::vector()) = 0; + const std::string &sql, const std::vector &sqlArgs) = 0; /** * @brief Queries data in the database based on SQL statement. * * @param sql Indicates the SQL statement to execute. - * @param selectionArgs Indicates the selection arguments. + * @param bindArgs Indicates the selection arguments. */ - virtual std::shared_ptr QueryByStep( - const std::string &sql, const std::vector &selectionArgs = std::vector()) = 0; + virtual std::shared_ptr QuerySql( + const std::string &sql, const std::vector &bindArgs = {}) = 0; + /** + * @brief Queries data in the database based on SQL statement. + * + * @param sql Indicates the SQL statement to execute. + * @param sqlArgs Indicates the selection arguments. + */ + [[deprecated("Use ExecuteSql(const std::string &, const std::vector &) instead.")]] + virtual std::shared_ptr QueryByStep(const std::string &sql, const std::vector &sqlArgs) = 0; + + /** + * @brief Queries data in the database based on SQL statement. + * + * @param sql Indicates the SQL statement to execute. + * @param args Indicates the selection arguments. + */ + virtual std::shared_ptr QueryByStep(const std::string &sql, + const std::vector &args = {}) = 0; /** * @brief Executes an SQL statement that contains specified parameters. @@ -196,8 +256,7 @@ public: * @param sql Indicates the SQL statement to execute. * @param bindArgs Indicates the {@link ValueObject} values of the parameters in the SQL statement. */ - virtual int ExecuteSql( - const std::string &sql, const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteSql(const std::string &sql, const std::vector &bindArgs = {}) = 0; /** * @brief Executes an SQL statement that contains specified parameters and get a long integer value. @@ -206,7 +265,7 @@ public: * @param bindArgs Indicates the {@link ValueObject} values of the parameters in the SQL statement. */ virtual int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; /** * @brief Executes an SQL statement that contains specified parameters. @@ -215,7 +274,7 @@ public: * @param bindArgs Indicates the {@link ValueObject} values of the parameters in the SQL statement. */ virtual int ExecuteAndGetString(std::string &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; /** * @brief Executes for last insert row id that contains specified parameters. @@ -224,7 +283,7 @@ public: * @param bindArgs Indicates the {@link ValueObject} values of the parameters in the SQL statement. */ virtual int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; /** * @brief Executes for change row count that contains specified parameters. @@ -233,7 +292,7 @@ public: * @param bindArgs Indicates the {@link ValueObject} values of the parameters in the SQL statement. */ virtual int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; /** * @brief Restores a database from a specified encrypted or unencrypted database file. @@ -241,8 +300,7 @@ public: * @param databasePath Indicates the database file path. * @param destEncryptKey Indicates the database encrypt key. */ - virtual int Backup(const std::string databasePath, - const std::vector destEncryptKey = std::vector()) = 0; + virtual int Backup(const std::string databasePath, const std::vector destEncryptKey = {}) = 0; /** * @brief Attaches a database. @@ -268,7 +326,7 @@ public: * @param columns Indicates the columns to query. If the value is empty array, the query applies to all columns. */ virtual std::shared_ptr Query( - const AbsRdbPredicates &predicates, const std::vector columns) = 0; + const AbsRdbPredicates &predicates, const std::vector &columns) = 0; /** * @brief Queries data in the database based on specified conditions. @@ -277,7 +335,7 @@ public: * @param columns Indicates the columns to query. If the value is empty array, the query applies to all columns. */ virtual std::shared_ptr QueryByStep( - const AbsRdbPredicates &predicates, const std::vector columns) = 0; + const AbsRdbPredicates &predicates, const std::vector &columns) = 0; /** * @brief Queries remote data in the database based on specified conditions before Synchronizing Data. @@ -286,8 +344,8 @@ public: * @param predicates Indicates the specified query condition by the instance object of {@link AbsRdbPredicates}. * @param columns Indicates the columns to query. If the value is empty array, the query applies to all columns. */ - virtual std::shared_ptr RemoteQuery(const std::string &device, const AbsRdbPredicates &predicates, - const std::vector &columns, int &errCode) = 0; + virtual std::shared_ptr RemoteQuery(const std::string &device, + const AbsRdbPredicates &predicates, const std::vector &columns, int &errCode) = 0; /** * @brief Updates data in the database based on a a specified instance object of AbsRdbPredicates. @@ -305,6 +363,9 @@ public: */ virtual int Delete(int &deletedRows, const AbsRdbPredicates &predicates) = 0; + /** + * @brief Gets the version of the database. + */ virtual int GetVersion(int &version) = 0; /** @@ -363,7 +424,7 @@ public: * @param backupPath Indicates the name that saves the database file path. * @param newKey Indicates the database new key. */ - virtual int Restore(const std::string backupPath, const std::vector &newKey = std::vector()) = 0; + virtual int Restore(const std::string backupPath, const std::vector &newKey = {}) = 0; /** * @brief Set table to be distributed table. @@ -391,7 +452,8 @@ public: * @param device Indicates the remote device. * @param predicate Indicates the AbsRdbPredicates {@link AbsRdbPredicates} object. */ - virtual int Sync(const SyncOption& option, const AbsRdbPredicates& predicate, const AsyncBrief& async) = 0; + virtual int Sync( + const SyncOption &option, const AbsRdbPredicates &predicate, const AsyncBrief &async) = 0; /** * @brief Sync data between devices or cloud. @@ -399,7 +461,8 @@ public: * @param device Indicates the remote device. * @param predicate Indicates the AbsRdbPredicates {@link AbsRdbPredicates} object. */ - virtual int Sync(const SyncOption& option, const std::vector& tables, const AsyncDetail& async) = 0; + virtual int Sync( + const SyncOption &option, const std::vector &tables, const AsyncDetail &async) = 0; /** * @brief Subscribe to event changes. @@ -416,16 +479,6 @@ public: */ virtual int Notify(const std::string &event) = 0; - /** - * @brief Drop the specified devices Data. - * - * User must use UDID - * - * @param devices Indicates the specified devices. - * @param option Indicates the drop option. - */ - virtual bool DropDeviceData(const std::vector& devices, const DropOption& option) = 0; - /** * @brief Get the the specified column modify time. * @@ -437,14 +490,6 @@ public: */ virtual std::map GetModifyTime( const std::string &table, const std::string &columnName, std::vector &keys) = 0; - - /** - * @brief Queries data in the database based on SQL statement. - * - * @param sql Indicates the SQL statement to execute. - * @param args Indicates the selection arguments. - */ - virtual std::shared_ptr QueryByStep(const std::string &sql, std::vector &&args) = 0; }; } // namespace OHOS::NativeRdb #endif diff --git a/relational_store/interfaces/inner_api/rdb/include/values_bucket.h b/relational_store/interfaces/inner_api/rdb/include/values_bucket.h index de26b402..58013279 100644 --- a/relational_store/interfaces/inner_api/rdb/include/values_bucket.h +++ b/relational_store/interfaces/inner_api/rdb/include/values_bucket.h @@ -112,7 +112,6 @@ public: * @param columnName Indicates the name of the column. */ API_EXPORT void Put(const std::string &columnName, const ValueObject &value); - API_EXPORT void Put(const std::string &columnName, ValueObject &&value); /** * @brief Delete the ValueObject object for the given column name. diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/abs_rdb_predicates.h b/relational_store/interfaces/inner_api/rdb/mock/include/abs_rdb_predicates.h deleted file mode 100644 index 68885f55..00000000 --- a/relational_store/interfaces/inner_api/rdb/mock/include/abs_rdb_predicates.h +++ /dev/null @@ -1,57 +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 NATIVE_RDB_ABSRDBPREDICATES_H -#define NATIVE_RDB_ABSRDBPREDICATES_H - -#include "abs_predicates.h" - -namespace OHOS::NativeRdb { -class AbsRdbPredicates : public AbsPredicates { -public: - explicit AbsRdbPredicates(const std::string &tableName); - explicit AbsRdbPredicates(const std::vector &tables); - ~AbsRdbPredicates() override {} - - void Clear() override; - - std::string ToString() const; - - std::string GetTableName() const; - - virtual void InitialParam(); - virtual std::vector GetJoinTypes(); - virtual void SetJoinTypes(const std::vector &joinTypes); - virtual std::vector GetJoinTableNames(); - virtual void SetJoinTableNames(const std::vector &joinTableNames); - virtual std::vector GetJoinConditions(); - virtual void SetJoinConditions(const std::vector &joinConditions); - virtual std::string GetJoinClause() const; - virtual int GetJoinCount() const; - virtual void SetJoinCount(int joinCount); - -protected: - std::vector joinTypes; - std::vector joinTableNames; - std::vector joinConditions; - int joinCount = 0; - -private: - std::string tableName_; -}; -} // namespace OHOS::NativeRdb - -#endif \ No newline at end of file diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/rdb_predicates.h b/relational_store/interfaces/inner_api/rdb/mock/include/rdb_predicates.h index 4c6d4aaf..b4acf697 100644 --- a/relational_store/interfaces/inner_api/rdb/mock/include/rdb_predicates.h +++ b/relational_store/interfaces/inner_api/rdb/mock/include/rdb_predicates.h @@ -32,8 +32,6 @@ public: RdbPredicates *LeftOuterJoin(const std::string &tableName); RdbPredicates *Using(const std::vector &fields); RdbPredicates *On(const std::vector &clauses); - std::string GetStatement(); - std::vector GetBindArgs(); private: std::string ProcessJoins() const; diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store.h b/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store.h index 08fee1c0..f13062a9 100644 --- a/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store.h +++ b/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store.h @@ -46,33 +46,38 @@ public: int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues, ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; virtual int Update(int &changedRows, const std::string &table, const ValuesBucket &values, - const std::string &whereClause = "", - const std::vector &whereArgs = std::vector()) = 0; + const std::string &whereClause, const std::vector &whereArgs) = 0; + virtual int Update(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &bindArgs) = 0; virtual int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, - const std::string &whereClause = "", const std::vector &whereArgs = std::vector(), - ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; - virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause = "", - const std::vector &whereArgs = std::vector()) = 0; - virtual std::shared_ptr QueryByStep( - const std::string &sql, const std::vector &selectionArgs = std::vector()) = 0; - virtual int ExecuteSql( - const std::string &sql, const std::vector &bindArgs = std::vector()) = 0; + const std::string &whereClause, const std::vector &whereArgs, + ConflictResolution conflictResolution) = 0; + virtual int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &bindArgs, + ConflictResolution conflictResolution) = 0; + virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &whereArgs) = 0; + virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &bindArgs) = 0; + virtual std::shared_ptr QueryByStep(const std::string &sql, + const std::vector &sqlArgs) = 0; + virtual std::shared_ptr QueryByStep(const std::string &sql, const std::vector &args) = 0; + virtual int ExecuteSql(const std::string &sql, const std::vector &bindArgs = {}) = 0; virtual int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; virtual int ExecuteAndGetString(std::string &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; virtual int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; virtual int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()) = 0; - virtual int Backup(const std::string databasePath, - const std::vector destEncryptKey = std::vector()) = 0; + const std::vector &bindArgs = {}) = 0; + virtual int Backup(const std::string databasePath, const std::vector destEncryptKey = {}) = 0; virtual int Attach( const std::string &alias, const std::string &pathName, const std::vector destEncryptKey) = 0; virtual int Count(int64_t &outValue, const AbsRdbPredicates &predicates) = 0; virtual std::shared_ptr Query( - const AbsRdbPredicates &predicates, const std::vector columns) = 0; + const AbsRdbPredicates &predicates, const std::vector &columns) = 0; virtual int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) = 0; virtual int Delete(int &deletedRows, const AbsRdbPredicates &predicates) = 0; @@ -87,8 +92,7 @@ public: virtual bool IsOpen() const = 0; virtual bool IsReadOnly() const = 0; virtual bool IsMemoryRdb() const = 0; - virtual int Restore(const std::string backupPath, const std::vector &newKey = std::vector()) = 0; - virtual std::shared_ptr QueryByStep(const std::string &sql, std::vector &&args) = 0; + virtual int Restore(const std::string backupPath, const std::vector &newKey = {}) = 0; }; } // namespace OHOS::NativeRdb #endif diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h b/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h index a272bb2e..41a89aa1 100644 --- a/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h +++ b/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h @@ -108,7 +108,6 @@ public: * @param columnName Indicates the name of the column. */ void Put(const std::string &columnName, const ValueObject &value); - void Put(const std::string &columnName, ValueObject &&value); /** * @brief Delete the ValueObject object for the given column name. diff --git a/relational_store/interfaces/ndk/src/relational_predicates.cpp b/relational_store/interfaces/ndk/src/relational_predicates.cpp index 5e33fd58..e8e2838c 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates.cpp +++ b/relational_store/interfaces/ndk/src/relational_predicates.cpp @@ -13,24 +13,27 @@ * limitations under the License. */ +#include "relational_predicates.h" + +#include + #include "logger.h" #include "oh_predicates.h" -#include "relational_store_error_code.h" -#include "relational_predicates.h" #include "relational_predicates_objects.h" +#include "relational_store_error_code.h" #include "sqlite_global_config.h" using namespace OHOS::NativeRdb; namespace OHOS { namespace RdbNdk { -OH_Predicates *RelationalPredicate::EqualTo(OH_Predicates *predicates, const char *field, OH_VObject *objects) +OH_Predicates *RelationalPredicate::EqualTo(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (!values.empty()) { self->predicates_.EqualTo(field, values[0]); } @@ -38,14 +41,14 @@ OH_Predicates *RelationalPredicate::EqualTo(OH_Predicates *predicates, const cha } OH_Predicates *RelationalPredicate::NotEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *objects) + OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (!values.empty()) { self->predicates_.NotEqualTo(field, values[0]); } @@ -112,28 +115,30 @@ OH_Predicates *RelationalPredicate::IsNotNull(OH_Predicates *predicates, const c return self; } -OH_Predicates *RelationalPredicate::Like(OH_Predicates *predicates, const char *field, OH_VObject *objects) +OH_Predicates *RelationalPredicate::Like(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (!values.empty()) { - self->predicates_.Like(field, values[0]); + if (auto pval = std::get_if(&values[0].value)) { + self->predicates_.Like(field, std::move(*pval)); + } } return self; } -OH_Predicates *RelationalPredicate::Between(OH_Predicates *predicates, const char *field, OH_VObject *objects) +OH_Predicates *RelationalPredicate::Between(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); // The number of arguments required for the between method is 2 if (values.size() != 2) { LOG_ERROR("size is %{public}zu", values.size()); @@ -145,14 +150,14 @@ OH_Predicates *RelationalPredicate::Between(OH_Predicates *predicates, const cha } OH_Predicates *RelationalPredicate::NotBetween(OH_Predicates *predicates, const char *field, - OH_VObject *objects) + OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); // The number of arguments required for the between method is 2 if (values.size() != 2) { LOG_ERROR("size is %{public}zu", values.size()); @@ -163,14 +168,14 @@ OH_Predicates *RelationalPredicate::NotBetween(OH_Predicates *predicates, const } OH_Predicates *RelationalPredicate::GreaterThan(OH_Predicates *predicates, const char *field, - OH_VObject *objects) + OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (!values.empty()) { self->predicates_.GreaterThan(field, values[0]); } @@ -178,14 +183,14 @@ OH_Predicates *RelationalPredicate::GreaterThan(OH_Predicates *predicates, const } OH_Predicates *RelationalPredicate::LessThan(OH_Predicates *predicates, const char *field, - OH_VObject *objects) + OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (!values.empty()) { self->predicates_.LessThan(field, values[0]); } @@ -193,28 +198,28 @@ OH_Predicates *RelationalPredicate::LessThan(OH_Predicates *predicates, const ch } OH_Predicates *RelationalPredicate::GreaterThanOrEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *objects) + OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (!values.empty()) { self->predicates_.GreaterThanOrEqualTo(field, values[0]); } return self; } OH_Predicates *RelationalPredicate::LessThanOrEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *objects) + OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (!values.empty()) { self->predicates_.LessThanOrEqualTo(field, values[0]); } @@ -268,7 +273,7 @@ OH_Predicates *RelationalPredicate::Offset(OH_Predicates *predicates, unsigned i OH_Predicates *RelationalPredicate::GroupBy(OH_Predicates *predicates, char const *const *fields, int length) { auto self = GetSelf(predicates); - if (self == nullptr || fields == nullptr || length == 0) { + if (self == nullptr || fields == nullptr || length <= 0) { return self; } std::vector vec; @@ -280,14 +285,14 @@ OH_Predicates *RelationalPredicate::GroupBy(OH_Predicates *predicates, char cons return self; } -OH_Predicates *RelationalPredicate::In(OH_Predicates *predicates, const char *field, OH_VObject *objects) +OH_Predicates *RelationalPredicate::In(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (values.size() > OHOS::NativeRdb::GlobalExpr::SQLITE_MAX_COLUMN) { return self; } @@ -296,14 +301,14 @@ OH_Predicates *RelationalPredicate::In(OH_Predicates *predicates, const char *fi return self; } -OH_Predicates *RelationalPredicate::NotIn(OH_Predicates *predicates, const char *field, OH_VObject *objects) +OH_Predicates *RelationalPredicate::NotIn(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); - auto selfObjects = RelationalPredicatesObjects::GetSelf(objects); + auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); if (self == nullptr || selfObjects == nullptr || field == nullptr) { return self; } - std::vector values = selfObjects->Get(); + std::vector values = selfObjects->Get(); if (values.size() > OHOS::NativeRdb::GlobalExpr::SQLITE_MAX_COLUMN) { return self; } diff --git a/relational_store/interfaces/ndk/src/relational_predicates.h b/relational_store/interfaces/ndk/src/relational_predicates.h index 60555a1a..d2982075 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates.h +++ b/relational_store/interfaces/ndk/src/relational_predicates.h @@ -50,11 +50,11 @@ private: static OH_Predicates *Limit(OH_Predicates *predicates, unsigned int value); static OH_Predicates *Offset(OH_Predicates *predicates, unsigned int rowOffset); static OH_Predicates *GroupBy(OH_Predicates *predicates, char const *const *fields, int length); - static OH_Predicates *In(OH_Predicates *predicates, const char *field, OH_VObject *objects); - static OH_Predicates *NotIn(OH_Predicates *predicates, const char *field, OH_VObject *objects); + static OH_Predicates *In(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); + static OH_Predicates *NotIn(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); static OH_Predicates *Clear(OH_Predicates *predicates); static int Destroy(OH_Predicates *predicates); - static bool GetObjects(OH_Predicates *predicates, OH_VObject *objects, + static bool GetObjects(OH_Predicates *predicates, OH_VObject *valueObject, std::vector &values); OHOS::NativeRdb::RdbPredicates predicates_; }; diff --git a/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp b/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp index 4d3c70b6..aba10430 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp +++ b/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp @@ -31,7 +31,7 @@ int RelationalPredicatesObjects::PutInt64(OH_VObject *objects, int64_t *value, u self->values_.clear(); self->values_.reserve(count); for (uint32_t i = 0; i < count; i++) { - self->values_.push_back(std::to_string(value[i])); + self->values_.push_back(value[i]); } return OH_Rdb_ErrCode::RDB_OK; } @@ -45,7 +45,7 @@ int RelationalPredicatesObjects::PutDouble(OH_VObject *objects, double *value, u self->values_.clear(); self->values_.reserve(count); for (uint32_t i = 0; i < count; i++) { - self->values_.push_back(std::to_string(value[i])); + self->values_.push_back(value[i]); } return OH_Rdb_ErrCode::RDB_OK; } @@ -97,16 +97,16 @@ RelationalPredicatesObjects::RelationalPredicatesObjects() destroy = Destroy; } -RelationalPredicatesObjects *RelationalPredicatesObjects::GetSelf(OH_VObject *objects) +RelationalPredicatesObjects *RelationalPredicatesObjects::GetSelf(OH_VObject *valueObject) { - if (objects == nullptr || objects->id != OHOS::RdbNdk::RDB_PREDICATES_OBJECTS_CID) { - LOG_ERROR("predicates objects invalid. is null %{public}d", (objects == nullptr)); + if (valueObject == nullptr || valueObject->id != OHOS::RdbNdk::RDB_PREDICATES_OBJECTS_CID) { + LOG_ERROR("predicates objects invalid. is null %{public}d", (valueObject == nullptr)); return nullptr; } - return static_cast(objects); + return static_cast(valueObject); } -std::vector &RelationalPredicatesObjects::Get() +std::vector &RelationalPredicatesObjects::Get() { return values_; } diff --git a/relational_store/interfaces/ndk/src/relational_predicates_objects.h b/relational_store/interfaces/ndk/src/relational_predicates_objects.h index cae33636..9d0c342e 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates_objects.h +++ b/relational_store/interfaces/ndk/src/relational_predicates_objects.h @@ -16,24 +16,27 @@ #ifndef RELATIONAL_VALUE_OBJECT_IMPL_H #define RELATIONAL_VALUE_OBJECT_IMPL_H -#include "oh_value_object.h" -#include #include +#include + +#include "oh_value_object.h" +#include "value_object.h" namespace OHOS { namespace RdbNdk { +using ValueObject = NativeRdb::ValueObject; class RelationalPredicatesObjects : public OH_VObject { public: RelationalPredicatesObjects(); static RelationalPredicatesObjects *GetSelf(OH_VObject *objects); - std::vector &Get(); + std::vector &Get(); private: static int PutInt64(OH_VObject *objects, int64_t *value, uint32_t count); static int PutDouble(OH_VObject *objects, double *value, uint32_t count); static int PutText(OH_VObject *objects, const char *value); static int PutTexts(OH_VObject *objects, const char **value, uint32_t count); static int Destroy(OH_VObject *objects); - std::vector values_; + std::vector values_; }; } // namespace RdbNdk } // namespace OHOS diff --git a/relational_store/interfaces/ndk/src/relational_store.cpp b/relational_store/interfaces/ndk/src/relational_store.cpp index 7042094d..f48e84ae 100644 --- a/relational_store/interfaces/ndk/src/relational_store.cpp +++ b/relational_store/interfaces/ndk/src/relational_store.cpp @@ -13,8 +13,6 @@ * limitations under the License. */ -#include "relational_store_impl.h" - #include "logger.h" #include "rdb_errno.h" #include "rdb_helper.h" @@ -80,9 +78,10 @@ RelationalStore *GetRelationalStore(OH_Rdb_Store *store) OH_Rdb_Store *OH_Rdb_GetOrOpen(const OH_Rdb_Config *config, int *errCode) { - if (config == nullptr || config->selfSize != sizeof(OH_Rdb_Config)) { - LOG_ERROR("Parameters set error:config is NULL ? %{public}d or config size error %{public}d vs %{public}zu", - (config == nullptr), config->selfSize, sizeof(OH_Rdb_Config)); + if (config == nullptr || config->selfSize != sizeof(OH_Rdb_Config) || errCode == nullptr) { + LOG_ERROR("Parameters set error:config is NULL ? %{public}d and config size is %{public}zu or " + "errCode is NULL ? %{public}d ", + (config == nullptr), sizeof(OH_Rdb_Config), (errCode == nullptr)); return nullptr; } @@ -180,7 +179,7 @@ OH_Cursor *OH_Rdb_Query(OH_Rdb_Store *store, OH_Predicates *predicates, const ch return nullptr; } std::vector columns; - if (columnNames != nullptr) { + if (columnNames != nullptr && length > 0) { columns.reserve(length); for (int i = 0; i < length; i++) { columns.push_back(columnNames[i]); @@ -248,7 +247,7 @@ int OH_Rdb_Commit(OH_Rdb_Store *store) int OH_Rdb_Backup(OH_Rdb_Store *store, const char *databasePath) { auto rdbStore = GetRelationalStore(store); - if (rdbStore == nullptr) { + if (rdbStore == nullptr || databasePath == nullptr) { return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; } return rdbStore->GetStore()->Backup(databasePath); diff --git a/relational_store/interfaces/ndk/src/relational_value_object.cpp b/relational_store/interfaces/ndk/src/relational_value_object.cpp deleted file mode 100644 index d1fd2b93..00000000 --- a/relational_store/interfaces/ndk/src/relational_value_object.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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 "logger.h" -#include "oh_value_object.h" -#include "relational_store_error_code.h" -#include "relational_value_object_impl.h" - -using namespace OHOS::RdbNdk; - -int Rdb_ValueObject_PutInt64(OH_VObject *valueObject, int64_t *value, uint32_t count) -{ - if (valueObject == nullptr || value == nullptr || valueObject->id != OHOS::RdbNdk::RDB_VOBJECT_CID) { - LOG_ERROR("Parameters set error:valueObject is NULL ? %{public}d, value is NULL ? %{public}d", - (valueObject == nullptr), (value == nullptr)); - return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; - } - - auto vObject = static_cast(valueObject); - vObject->getValue().clear(); - if (count == 1) { - vObject->getValue().push_back(std::to_string(*value)); - } else { - for (uint32_t i = 0; i < count; i++) { - vObject->getValue().push_back(std::to_string(value[i])); - } - }; - return OH_Rdb_ErrCode::RDB_OK; -} - -int Rdb_ValueObject_PutDouble(OH_VObject *valueObject, double *value, uint32_t count) -{ - if (valueObject == nullptr || value == nullptr || valueObject->id != OHOS::RdbNdk::RDB_VOBJECT_CID) { - LOG_ERROR("Parameters set error:valueObject is NULL ? %{public}d, value is NULL ? %{public}d", - (valueObject == nullptr), (value == nullptr)); - return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; - } - - auto vObject = static_cast(valueObject); - vObject->getValue().clear(); - if (count == 1) { - vObject->getValue().push_back(std::to_string(*value)); - } else { - for (uint32_t i = 0; i < count; i++) { - vObject->getValue().push_back(std::to_string(value[i])); - } - } - return OH_Rdb_ErrCode::RDB_OK; -} - -int Rdb_ValueObject_PutText(OH_VObject *valueObject, const char *value) -{ - if (valueObject == nullptr || value == nullptr || valueObject->id != OHOS::RdbNdk::RDB_VOBJECT_CID) { - LOG_ERROR("Parameters set error:valueObject is NULL ? %{public}d, value is NULL ? %{public}d", - (valueObject == nullptr), (value == nullptr)); - return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; - } - - std::string textValue(value); - auto vObject = static_cast(valueObject); - vObject->getValue().clear(); - vObject->getValue().push_back(textValue); - return OH_Rdb_ErrCode::RDB_OK; -} - -int Rdb_ValueObject_PutTexts(OH_VObject *valueObject, const char **value, uint32_t count) -{ - if (valueObject == nullptr || value == nullptr || valueObject->id != OHOS::RdbNdk::RDB_VOBJECT_CID) { - LOG_ERROR("Parameters set error:valueObject is NULL ? %{public}d, value is NULL ? %{public}d", - (valueObject == nullptr), (value == nullptr)); - return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; - } - - auto vObject = static_cast(valueObject); - vObject->getValue().clear(); - for (uint32_t i = 0; i < count; i++) { - std::string textValue(value[i]); - vObject->getValue().push_back(textValue); - } - return OH_Rdb_ErrCode::RDB_OK; -} - -int Rdb_DestroyValueObject(OH_VObject *valueObject) -{ - if (valueObject == nullptr || valueObject->id != OHOS::RdbNdk::RDB_VOBJECT_CID) { - LOG_ERROR("Parameters set error:valueObject is NULL ? %{public}d", (valueObject == nullptr)); - return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; - } - delete static_cast(valueObject); - return OH_Rdb_ErrCode::RDB_OK; -} - -OHOS::RdbNdk::ValueObjectImpl::ValueObjectImpl() -{ - id = RDB_VOBJECT_CID; - putInt64 = Rdb_ValueObject_PutInt64; - putDouble = Rdb_ValueObject_PutDouble; - putText = Rdb_ValueObject_PutText; - putTexts = Rdb_ValueObject_PutTexts; - destroyValueObject = Rdb_DestroyValueObject; -} - -std::vector &OHOS::RdbNdk::ValueObjectImpl::getValue() -{ - return value; -} \ No newline at end of file diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js index 80043f5b..c6d40d65 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js @@ -252,9 +252,8 @@ describe('rdbStoreDistributedTest', function () { console.log(TAG + "************* testRdbStoreDistributed0009 start *************"); let predicates = new dataRdb.RdbPredicates("employee") try { - predicates = predicates.inDevices("1234567890"); + predicates = predicates.inDevices(["1234567890"]); console.log(TAG + "inDevices success"); - expect(predicates).assertEqual(predicates); } catch (err) { console.log(TAG + "inDevices failed"); expect(null).assertFail(); @@ -291,7 +290,7 @@ describe('rdbStoreDistributedTest', function () { it('testRdbStoreDistributed0011', 0, async function (done) { console.log(TAG + "************* testRdbStoreDistributed0011 start *************"); let predicates = new dataRdb.RdbPredicates("employee") - predicates = predicates.inDevices("12345678abcd"); + predicates = predicates.inDevices(["12345678abcd"]); rdbStore.sync(dataRdb.SyncMode.SYNC_MODE_PUSH, predicates); console.log(TAG + "sync push success"); expect(rdbStore).assertEqual(rdbStore); diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js index 57a2b19e..a9fedda8 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js @@ -21,7 +21,6 @@ const TAG = "[RDB_JSKITS_TEST]" const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)" -var rdbStore var context const STORE_CONFIG_ENCRYPT = { name: "Encrypt.db", @@ -36,7 +35,7 @@ const STORE_CONFIG_WRONG = { encrypt: false, } -async function CreatRdbStore(context, STORE_CONFIG) { +async function CreateRdbStore(context, STORE_CONFIG) { let rdbStore = await data_rdb.getRdbStore(context, STORE_CONFIG, 1) await rdbStore.executeSql(CREATE_TABLE_TEST, null) let u8 = new Uint8Array([1, 2, 3]) @@ -71,133 +70,111 @@ async function CreatRdbStore(context, STORE_CONFIG) { } describe('rdbEncryptTest', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll') - - }) - - beforeEach(async function () { - console.info(TAG + 'beforeEach') - - }) - - afterEach(async function () { - console.info(TAG + 'afterEach') - await data_rdb.deleteRdbStore(context, STORE_CONFIG_ENCRYPT.name) - await data_rdb.deleteRdbStore(context, STORE_CONFIG_UNENCRYPT.name) - await data_rdb.deleteRdbStore(context, STORE_CONFIG_WRONG.name) - }) - - afterAll(async function () { - console.info(TAG + 'afterAll') - }) - - console.log(TAG + "*************Unit Test Begin*************") - - /** - * @tc.name RDB encrypted test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0010 - * @tc.desc RDB create encrypt db test - */ - it('RdbEncryptTest_0010', 0, async function (done) { - await console.log(TAG + "************* RdbEncryptTest_0010 start *************") - context = ability_featureAbility.getContext() - let storePromise = data_rdb.getRdbStore(context, STORE_CONFIG_ENCRYPT, 1); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - } catch (err) { - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - - done() - await console.log(TAG + "************* RdbEncryptTest_0010 end *************") - }) - - /** - * @tc.name RDB unencrypted test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0020 - * @tc.desc RDB create unencrypted db test - */ - it('RdbEncryptTest_0020', 0, async function (done) { - await console.log(TAG + "************* RdbEncryptTest_0020 start *************") + beforeAll(async function () { + console.info(TAG + 'beforeAll') + }) + + beforeEach(async function () { + console.info(TAG + 'beforeEach') + }) + + afterEach(async function () { + console.info(TAG + 'afterEach') + await data_rdb.deleteRdbStore(context, STORE_CONFIG_ENCRYPT.name) + await data_rdb.deleteRdbStore(context, STORE_CONFIG_UNENCRYPT.name) + await data_rdb.deleteRdbStore(context, STORE_CONFIG_WRONG.name) + }) + + afterAll(async function () { + console.info(TAG + 'afterAll') + }) + + console.log(TAG + "*************Unit Test Begin*************") + + /** + * @tc.name RDB encrypted test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0010 + * @tc.desc RDB create encrypt db test + */ + it('RdbEncryptTest_0010', 0, async function () { + await console.log(TAG + "************* RdbEncryptTest_0010 start *************") + try { context = ability_featureAbility.getContext() - let storePromise = data_rdb.getRdbStore(context, STORE_CONFIG_UNENCRYPT, 1); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - } catch (err) { - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - - done() - await console.log(TAG + "************* RdbEncryptTest_0020 end *************") - }) - - - /** - * @tc.name RDB Encrypt test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0030 - * @tc.desc RDB Encrypt function test - */ - it('RdbEncryptTest_0030', 0, async function (done) { - await console.log(TAG + "************* RdbEncryptTest_0030 start *************") - context = ability_featureAbility.getContext() - rdbStore = await CreatRdbStore(context, STORE_CONFIG_ENCRYPT) - let predicates = new data_rdb.RdbPredicates("test") - predicates.equalTo("name", "zhangsan") - let resultSet = await rdbStore.query(predicates) - try { - console.log(TAG + "After restore resultSet query done") - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = resultSet.getLong(resultSet.getColumnIndex("id")) - const name = resultSet.getString(resultSet.getColumnIndex("name")) - const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) - expect(1).assertEqual(id) - expect("zhangsan").assertEqual(name) - expect(1).assertEqual(blobType[0]) - } catch (err) { - expect(false).assertTrue() - } + await data_rdb.getRdbStore(context, STORE_CONFIG_ENCRYPT, 1); + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect(null).assertFail(); + } + await console.log(TAG + "************* RdbEncryptTest_0010 end *************") + }) + + /** + * @tc.name RDB unencrypted test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0020 + * @tc.desc RDB create unencrypted db test + */ + it('RdbEncryptTest_0020', 0, async function () { + await console.log(TAG + "************* RdbEncryptTest_0020 start *************") + context = ability_featureAbility.getContext() + try { + await data_rdb.getRdbStore(context, STORE_CONFIG_UNENCRYPT, 1); + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect(null).assertFail(); + } + await console.log(TAG + "************* RdbEncryptTest_0020 end *************") + }) + + + /** + * @tc.name RDB Encrypt test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0030 + * @tc.desc RDB Encrypt function test + */ + it('RdbEncryptTest_0030', 0, async function () { + await console.log(TAG + "************* RdbEncryptTest_0030 start *************") + context = ability_featureAbility.getContext() + let rdbStore = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT) + let predicates = new data_rdb.RdbPredicates("test") + predicates.equalTo("name", "zhangsan") + let resultSet = await rdbStore.query(predicates) + try { + console.log(TAG + "After restore resultSet query done") + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = resultSet.getLong(resultSet.getColumnIndex("id")) + const name = resultSet.getString(resultSet.getColumnIndex("name")) + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) + expect(1).assertEqual(id) + expect("zhangsan").assertEqual(name) + expect(1).assertEqual(blobType[0]) + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail() + } finally { resultSet.close() resultSet = null rdbStore = null - done() - await console.log(TAG + "************* RdbEncryptTest_0030 end *************") - }) - - /** - * @tc.name RDB Encrypt test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0040 - * @tc.desc RDB Encrypt function test - */ - it('RdbEncryptTest_0040', 0, async function () { - await console.log(TAG + "************* RdbEncryptTest_0040 start *************") - context = ability_featureAbility.getContext() - rdbStore = await CreatRdbStore(context, STORE_CONFIG_ENCRYPT) - rdbStore = null - - try { - rdbStore = await CreatRdbStore(context, STORE_CONFIG_WRONG) - expect(false).assertTrue() - } catch (err) { - console.log(TAG + "CreatRdbStore done") - } + } + await console.log(TAG + "************* RdbEncryptTest_0030 end *************") + }) + + /** + * @tc.name RDB Encrypt test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0040 + * @tc.desc RDB Encrypt function test + */ + it('RdbEncryptTest_0040', 0, async function () { + await console.log(TAG + "************* RdbEncryptTest_0040 start *************") + context = ability_featureAbility.getContext() + await CreateRdbStore(context, STORE_CONFIG_ENCRYPT) + try { + await CreateRdbStore(context, STORE_CONFIG_WRONG) + expect().assertFail() + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + } - await console.log(TAG + "************* RdbEncryptTest_0040 end *************") - }) - console.log(TAG + "*************Unit Test End*************") - } -) + await console.log(TAG + "************* RdbEncryptTest_0040 end *************") + }) + console.log(TAG + "*************Unit Test End*************") +}) \ No newline at end of file diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js index 0bcaaf3e..39a5ea72 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js @@ -23,6 +23,7 @@ const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIM const STORE_CONFIG = { name: "rdbstore.db", } + describe('rdbStoreTest', function () { beforeAll(async function () { console.info(TAG + 'beforeAll') @@ -48,22 +49,13 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0010 * @tc.desc rdb store getRdbStore test */ - it('testRdbStore0001', 0, async function (done) { + it('testRdbStore0001', 0, async function () { console.log(TAG + "************* testRdbStore0001 start *************"); - let storePromise = dataRdb.getRdbStore(STORE_CONFIG, 1); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - } catch (e) { - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - done(); + try { + await dataRdb.getRdbStore(STORE_CONFIG, 1); + } catch (err) { + expect().assertFail() + } console.log(TAG + "************* testRdbStore0001 end *************"); }) @@ -72,23 +64,15 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0020 * @tc.desc rdb store getRdbStore and create table */ - it('testRdbStore0002', 0, async function (done) { + it('testRdbStore0002', 0, async function () { console.log(TAG + "************* testRdbStore0002 start *************"); - let storePromise = dataRdb.getRdbStore(STORE_CONFIG, 2); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - await store.executeSql(CREATE_TABLE_TEST); - } catch (e) { - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - done(); + try { + let store = await dataRdb.getRdbStore(STORE_CONFIG, 2); + await store.executeSql(CREATE_TABLE_TEST); + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail() + } console.log(TAG + "************* testRdbStore0002 end *************"); }) @@ -97,23 +81,18 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0030 * @tc.desc rdb store getRdbStore with wrong path */ - it('testRdbStore0003', 0, async function (done) { + it('testRdbStore0003', 0, async function () { console.log(TAG + "************* testRdbStore0003 start *************"); let storeConfig = { name: "/wrong/rdbstore.db", } - try{ - dataRdb.getRdbStore(storeConfig, 4).then(async (ret) => { - await console.info(TAG + "getRdbStore done" + ret); - expect(null).assertFail(); - }).catch((err) => { - console.info(TAG + "getRdbStore with wrong path"); - }) - } catch(e) { - console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) - expect("401").assertEqual(e.code) - done(); + try { + await dataRdb.getRdbStore(storeConfig, 4); + expect().assertFail() + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect("401").assertEqual(err.code) console.info(TAG + "************* testRdbStore0003 end *************"); } }) @@ -123,25 +102,15 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0040 * @tc.desc rdb store deleteRdbStore */ - it('testRdbStore0004', 0, async function (done) { + it('testRdbStore0004', 0, async function () { console.log(TAG + "************* testRdbStore0004 start *************"); - - let storePromise = dataRdb.getRdbStore(STORE_CONFIG, 6); - storePromise.then(async (store) => { - console.log(TAG + "getRdbStore done:" + store); - try { - await store.executeSql(CREATE_TABLE_TEST); - } catch (e) { - console.log(TAG + "create table error"); - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - done(); + try { + let store = await dataRdb.getRdbStore(STORE_CONFIG, 6); + await store.executeSql(CREATE_TABLE_TEST); + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail() + } console.log(TAG + "************* testRdbStore0004 end *************"); }) @@ -150,36 +119,30 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0050 * @tc.desc rdb store setVersion & getVersion */ - it('testRdbStore0005', 0, async function (done) { + it('testRdbStore0005', 0, async function () { console.log(TAG + "************* testRdbStore0005 start *************"); - let storePromise = dataRdb.getRdbStore(STORE_CONFIG, 2); - storePromise.then(async (store) => { - try { - expect(2).assertEqual(store.getVersion()) - store.setVersion(5) - expect(5).assertEqual(store.getVersion()) - store.setVersion(2147483647) - expect(2147483647).assertEqual(store.getVersion()) - store.setVersion(-2147483648) - expect(-2147483648).assertEqual(store.getVersion()) - - // Exceeds the range of 32-bit signed integer value. - store.setVersion(2147483647000) - expect(-1000).assertEqual(store.getVersion()) - store.setVersion(-2147483648100) - expect(-100).assertEqual(store.getVersion()) - store = null - } catch (e) { - expect(null).assertFail(); - } - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null + let store = await dataRdb.getRdbStore(STORE_CONFIG, 2); + try { + expect(2).assertEqual(store.getVersion()) + store.setVersion(5) + expect(5).assertEqual(store.getVersion()) + store.setVersion(2147483647) + expect(2147483647).assertEqual(store.getVersion()) + store.setVersion(-2147483648) + expect(-2147483648).assertEqual(store.getVersion()) + + // Exceeds the range of 32-bit signed integer value. + store.setVersion(2147483647000) + expect(-1000).assertEqual(store.getVersion()) + store.setVersion(-2147483648100) + expect(-100).assertEqual(store.getVersion()) + store = null + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail() + } await dataRdb.deleteRdbStore("rdbstore.db"); - done(); console.log(TAG + "************* testRdbStore0005 end *************"); }) diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js index c120b4bc..47d00332 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js @@ -23,6 +23,7 @@ const STORE_CONFIG = { } var rdbStore = undefined; + describe('rdbStoreUpdateTest', function () { beforeAll(async function () { console.info(TAG + 'beforeAll') @@ -50,7 +51,7 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0001 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0001', 0, async function (done) { + it('testRdbStoreUpdate0001', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0001 start *************"); var u8 = new Uint8Array([1, 2, 3]) { @@ -63,7 +64,7 @@ describe('rdbStoreUpdateTest', function () { let ret = await rdbStore.insert("test", valueBucket) expect(1).assertEqual(ret); } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "name": "lisi", @@ -73,41 +74,36 @@ describe('rdbStoreUpdateTest', function () { } let predicates = await new dataRdb.RdbPredicates("test") await predicates.equalTo("id", "1") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new dataRdb.RdbPredicates("test") - let resultSet = await rdbStore.query(predicates) + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(1).assertEqual(id); - await expect("lisi").assertEqual(name); - await expect(20).assertEqual(age); - await expect(200.5).assertEqual(salary); - await expect(4).assertEqual(blobType[0]); - await expect(5).assertEqual(blobType[1]); - await expect(6).assertEqual(blobType[2]); - await expect(false).assertEqual(resultSet.goToNextRow()) - resultSet.close() - resultSet = null - } + predicates = await new dataRdb.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) - // await updatePromise + await expect(1).assertEqual(id); + await expect("lisi").assertEqual(name); + await expect(20).assertEqual(age); + await expect(200.5).assertEqual(salary); + await expect(4).assertEqual(blobType[0]); + await expect(5).assertEqual(blobType[1]); + await expect(6).assertEqual(blobType[2]); + await expect(false).assertEqual(resultSet.goToNextRow()) + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail() } - - done(); console.log(TAG + "************* testRdbStoreUpdate0001 end *************"); }) @@ -116,61 +112,39 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0002 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0002', 0, async function (done) { + it('testRdbStoreUpdate0002', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0002 start *************"); - { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - try { - let predicates = new dataRdb.RdbPredicates("") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with null table name"); - }) - } catch (err) { - console.log( - "catch err: update with null table name failed, err: code=" + err.code + " message=" + err.message) - expect("401").assertEqual(err.code) - } - try { - const emptyBucket = {}; - let predicates = await new dataRdb.RdbPredicates("test") - let updatePromise = rdbStore.update(emptyBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong valueBucket"); - }) - } catch (err) { - console.log("catch err: update with wrong valueBucket failed, err: code=" + err.code - + " message=" + err.message) - expect("401").assertEqual(err.code) - } - try { - let predicates = await new dataRdb.RdbPredicates("test") - await predicates.equalTo("aaa", "null") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong condition"); - }) - } catch (err) { - console.log("catch err: update with wrong condition failed, err: code=" + err.code - + " message=" + err.message) - } + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + try { + let predicates = new dataRdb.RdbPredicates("") + await rdbStore.update(valueBucket, predicates) + expect().assertFail() + } catch (err) { + console.log(TAG + `empty failed, errcode:${JSON.stringify(err)}.`); + expect("401").assertEqual(err.code) + } + try { + const emptyBucket = {}; + let predicates = await new dataRdb.RdbPredicates("test") + await rdbStore.update(emptyBucket, predicates) + expect().assertFail() + } catch (err) { + console.log(TAG + `test failed, errcode:${JSON.stringify(err)}.`); + } + try { + let predicates = await new dataRdb.RdbPredicates("test") + await predicates.equalTo("aaa", "null") + await rdbStore.update(valueBucket, predicates); + expect().assertFail() + } catch (err) { + console.log(TAG + `aaa failed, errcode:${JSON.stringify(err)}.`); } - done(); console.log(TAG + "************* testRdbStoreUpdate0002 end *************"); }) @@ -179,41 +153,30 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0003 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0003', 0, async function (done) { + it('testRdbStoreUpdate0003', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0003 start *************"); - { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - "wrongColumn": 100.5, - } - { - let predicates = new dataRdb.RdbPredicates("wrongTable") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong table name"); - }) - // await updatePromise - } - { - let predicates = await new dataRdb.RdbPredicates("test") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong column name"); - }) - // await updatePromise - } + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + "wrongColumn": 100.5, + } + try { + let predicates = new dataRdb.RdbPredicates("wrongTable") + await rdbStore.update(valueBucket, predicates) + expect().assertFail(); + } catch (err) { + console.log(TAG + `wrongTable failed, errcode:${JSON.stringify(err)}.`); + } + try { + let predicates = await new dataRdb.RdbPredicates("test") + await rdbStore.update(valueBucket, predicates) + expect().assertFail(); + } catch (err) { + console.log(TAG + `test failed, errcode:${JSON.stringify(err)}.`); } - done(); console.log(TAG + "************* testRdbStoreUpdate0003 end *************"); }) @@ -222,44 +185,34 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0004 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0004', 0, async function (done) { + it('testRdbStoreUpdate0004', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0004 start *************"); - { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - { - let predicates = await new dataRdb.RdbPredicates("test") - await predicates.equalTo("aaa", "null") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong condition"); - }) - // await updatePromise - } - { - const emptyBucket = {}; - let predicates = await new dataRdb.RdbPredicates("test") - await predicates.equalTo("name", "zhangsan") - await predicates.equalTo("age", 18) - await predicates.equalTo("null", 100.5) - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong condition"); - }) - } + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + try { + let predicates = await new dataRdb.RdbPredicates("test") + await predicates.equalTo("aaa", "null") + await rdbStore.update(valueBucket, predicates) + expect().assertFail(); + } catch (err) { + console.log(TAG + `test failed, errcode:${JSON.stringify(err)}.`); + } + try { + const emptyBucket = {}; + let predicates = await new dataRdb.RdbPredicates("test") + await predicates.equalTo("name", "zhangsan") + await predicates.equalTo("age", 18) + await predicates.equalTo("null", 100.5) + await rdbStore.update(emptyBucket, predicates) + expect().assertFail(); + } catch (err) { + console.log(TAG + `emptyBucket failed, errcode:${JSON.stringify(err)}.`); } - done(); console.log(TAG + "************* testRdbStoreUpdate0004 end *************"); }) @@ -268,7 +221,7 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0005 * @tc.desc resultSet Update Extra long character test */ - it('testRdbStoreUpdate0005', 0, async function (done) { + it('testRdbStoreUpdate0005', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0005 start *************"); var u8 = new Uint8Array([1, 2, 3]) { @@ -280,7 +233,7 @@ describe('rdbStoreUpdateTest', function () { } await rdbStore.insert("test", valueBucket) } - { + try { var u8 = new Uint8Array([4, 5, 6]) var nameStr = "abcd" + "e".repeat(2000) + "./&*$!@()" const valueBucket = { @@ -291,28 +244,25 @@ describe('rdbStoreUpdateTest', function () { } let predicates = await new dataRdb.RdbPredicates("test") await predicates.equalTo("name", "xiaoming") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new dataRdb.RdbPredicates("test") - predicates.equalTo("age", 20) - let resultSet = await rdbStore.query(predicates) - expect(true).assertEqual(resultSet.goToFirstRow()) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - await expect(nameStr).assertEqual(name); - resultSet.close() - resultSet = null - } + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) + predicates = await new dataRdb.RdbPredicates("test") + predicates.equalTo("age", 20) + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + await expect(nameStr).assertEqual(name); + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); } - - done(); console.log(TAG + "************* testRdbStoreUpdate0005 end *************"); }) @@ -321,7 +271,7 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0006 * @tc.desc resultSet Update Extra long character test */ - it('testRdbStoreUpdate0006', 0, async function (done) { + it('testRdbStoreUpdate0006', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0006 start *************"); var u8 = new Uint8Array([1, 2, 3]) { @@ -333,7 +283,7 @@ describe('rdbStoreUpdateTest', function () { } await rdbStore.insert("test", valueBucket) } - { + try { var u8 = new Uint8Array([4, 5, 6]) var nameStr = "橘子是水果" + "e".repeat(2000) const valueBucket = { @@ -344,28 +294,25 @@ describe('rdbStoreUpdateTest', function () { } let predicates = await new dataRdb.RdbPredicates("test") await predicates.equalTo("name", "xiaohua") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new dataRdb.RdbPredicates("test") - predicates.equalTo("age", 19) - let resultSet = await rdbStore.query(predicates) - expect(true).assertEqual(resultSet.goToFirstRow()) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - await expect(nameStr).assertEqual(name); - resultSet.close() - resultSet = null - } + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) + predicates = await new dataRdb.RdbPredicates("test") + predicates.equalTo("age", 19) + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + await expect(nameStr).assertEqual(name); + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); } - - done(); console.log(TAG + "************* testRdbStoreUpdate0006 end *************"); }) @@ -374,7 +321,7 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0007 * @tc.desc resultSet Update Extra long character test */ - it('testRdbStoreUpdate0007', 0, async function (done) { + it('testRdbStoreUpdate0007', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0007 start *************"); var u8 = new Uint8Array([1, 2, 3]) { @@ -386,7 +333,7 @@ describe('rdbStoreUpdateTest', function () { } await rdbStore.insert("test", valueBucket) } - { + try { var u8 = new Uint8Array([4, 5, 6]) var nameStr = "菠萝是水果" + "e".repeat(2000) + "好吃又不贵" const valueBucket = { @@ -397,29 +344,26 @@ describe('rdbStoreUpdateTest', function () { } let predicates = await new dataRdb.RdbPredicates("test") await predicates.equalTo("name", "xiaocan") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new dataRdb.RdbPredicates("test") - predicates.equalTo("age", 21) - let resultSet = await rdbStore.query(predicates) - expect(true).assertEqual(resultSet.goToFirstRow()) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - await expect(nameStr).assertEqual(name); - resultSet.close() - resultSet = null - } + let ret = await rdbStore.update(valueBucket, predicates); + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) + predicates = await new dataRdb.RdbPredicates("test") + predicates.equalTo("age", 21) + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + await expect(nameStr).assertEqual(name); + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); } - - done(); console.log(TAG + "************* testRdbStoreUpdate0007 end *************"); }) console.log(TAG + "*************Unit Test End*************"); -}) +}) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js index 7c0b8d79..fb766500 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js @@ -19,12 +19,11 @@ import ability_featureAbility from '@ohos.ability.featureAbility' const TAG = "[RELATIONAL_STORE_JSKITS_TEST]" const STORE_NAME = "cloud_rdb.db" -const PARAMETER_ERROR = 401; var rdbStore = undefined; var context = ability_featureAbility.getContext() -describe('rdbStoreDistributedCloudTest', function () { - beforeAll(async function (done) { +describe('rdbStoreCloud', function () { + beforeAll(async function () { console.info(TAG + 'beforeAll') const config = { "name": STORE_NAME, @@ -37,13 +36,8 @@ describe('rdbStoreDistributedCloudTest', function () { "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL," + "age INTEGER)" - try { - await rdbStore.executeSql(sqlStatement, null) - console.log(TAG + "create table employee success") - } catch (err) { - console.log(TAG + "create table employee failed") - expect(null).assertFail() - } + await rdbStore.executeSql(sqlStatement, null) + console.log(TAG + "create table employee success") sqlStatement = "CREATE TABLE IF NOT EXISTS product (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + @@ -51,14 +45,8 @@ describe('rdbStoreDistributedCloudTest', function () { "price REAL," + "vendor INTEGER," + "describe TEXT)" - try { - await rdbStore.executeSql(sqlStatement, null) - console.log(TAG + "create table product success") - done() - } catch (err) { - console.log(TAG + "create table product failed") - expect(null).assertFail() - } + await rdbStore.executeSql(sqlStatement, null) + console.log(TAG + "create table product success") sqlStatement = "CREATE TABLE IF NOT EXISTS local (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + @@ -66,19 +54,12 @@ describe('rdbStoreDistributedCloudTest', function () { "price REAL," + "vendor INTEGER," + "describe TEXT)" - try { - await rdbStore.executeSql(sqlStatement, null) - console.log(TAG + "create table local success") - done() - } catch (err) { - console.log(TAG + "create table local failed") - expect(null).assertFail() - } + await rdbStore.executeSql(sqlStatement, null) + console.log(TAG + "create table local success") } catch (err) { console.log(TAG + "create rdb store failed" + `, error code is ${err.code}, message is ${err.message}`) expect(null).assertFail() } - done() }) beforeEach(async function () { @@ -106,20 +87,20 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0001 start *************"); try { let config = { - autoSync:false + autoSync: false } rdbStore.setDistributedTables([], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config, function (err) { console.log(TAG + "set none to be distributed table cloud success"); expect(true).assertTrue(); done() + console.log(TAG + "************* testRdbStoreCloud0001 end *************"); }); } catch (err) { - console.log(TAG + `set none to be distributed table cloud failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set none to be distributed table cloud failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0001 end *************"); }) /** @@ -131,20 +112,19 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0002 start *************"); try { let config = { - autoSync:true + autoSync: true } rdbStore.setDistributedTables(['employee'], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config, function (err) { console.log(TAG + "set employee to be distributed cloud table success"); - expect(true).assertTrue(); done(); + console.log(TAG + "************* testRdbStoreCloud0002 end *************"); }) } catch (err) { - console.log(TAG + `set employee to be distributed cloud table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set employee to be distributed failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0002 end *************"); }) /** @@ -156,20 +136,20 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0003 start *************"); try { let config = { - autoSync:false + autoSync: false } rdbStore.setDistributedTables(['employee', 'product'], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config, function (err) { console.log(TAG + "set employee and product to be distributed cloud table success"); expect(true).assertTrue(); done() + console.log(TAG + "************* testRdbStoreCloud0003 end *************"); }) } catch (err) { - console.log(TAG + `set employee and product to be distributed cloud table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set employee and product to be distributed failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0003 end *************"); }) /** @@ -181,24 +161,24 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0004 start *************"); try { let config = { - autoSync:false + autoSync: false } await rdbStore.setDistributedTables(['employee', 'product'], - relationalStore.DistributedType.DISTRIBUTED_CLOUD, config).then((err)=>{ + relationalStore.DistributedType.DISTRIBUTED_CLOUD, config).then((err) => { console.log(TAG + "set employee and product to be distributed cloud table success"); expect(true).assertTrue(); done(); - }).catch((err)=>{ - console.log(TAG + `set employee and product to be distributed table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + "************* testRdbStoreCloud0004 end *************"); + }).catch((err) => { + console.log(TAG + `set employee and product as distributed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() }); } catch (err) { - console.log(TAG + `set employee and product to be distributed table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set employee and product as distributed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0004 end *************"); }) /** @@ -210,24 +190,24 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0005 start *************"); try { let config = { - autoSync:false + autoSync: false } await rdbStore.setDistributedTables(['local'], undefined, - config).then((err)=>{ + config).then((err) => { console.log(TAG + "set local to be distributed device table success"); expect(true).assertTrue(); done(); - }).catch((err)=>{ - console.log(TAG + `set local to be distributed table failed 1, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + "************* testRdbStoreCloud0005 end *************"); + }).catch((err) => { + console.log(TAG + `set local to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() }); } catch (err) { - console.log(TAG + `set local to be distributed table failed 2, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set local to be distributed table failed 2, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0005 end *************"); }) /** @@ -238,21 +218,21 @@ describe('rdbStoreDistributedCloudTest', function () { it('testRdbStoreCloud0006', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloud0006 start *************"); try { - await rdbStore.setDistributedTables(['local'], null).then((err)=>{ + await rdbStore.setDistributedTables(['local'], null).then((err) => { console.log(TAG + "set local to be distributed device table success"); expect(true).assertTrue(); done(); - }).catch((err)=>{ - console.log(TAG + `set local to be distributed table failed 1, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + "************* testRdbStoreCloud0006 end *************"); + }).catch((err) => { + console.log(TAG + `set local to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() }); } catch (err) { - console.log(TAG + `set local to be distributed table failed 2, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set local to be distributed table failed 2, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0006 end *************"); }) /** @@ -264,21 +244,21 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0007 start *************"); try { await rdbStore.setDistributedTables(['employee'], relationalStore.DistributedType.DISTRIBUTED_CLOUD - ).then((err)=>{ + ).then((err) => { console.log(TAG + "set employee to be distributed cloud table success"); expect(true).assertTrue(); done(); - }).catch((err)=>{ - console.log(TAG + `set employee to be distributed table failed 1, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + "************* testRdbStoreCloud0007 end *************"); + }).catch((err) => { + console.log(TAG + `set employee to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() }); } catch (err) { - console.log(TAG + `set employee to be distributed table failed 2, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set employee to be distributed table failed 2, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0007 end *************"); }) /** @@ -290,21 +270,21 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0008 start *************"); try { await rdbStore.setDistributedTables(['employee'], relationalStore.DistributedType.DISTRIBUTED_CLOUD, - undefined).then((err)=>{ + undefined).then((err) => { console.log(TAG + "set employee to be distributed cloud table success"); expect(true).assertTrue(); done(); - }).catch((err)=>{ - console.log(TAG + `set employee to be distributed table failed 1, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + "************* testRdbStoreCloud0008 end *************"); + }).catch((err) => { + console.log(TAG + `set employee to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() }); } catch (err) { - console.log(TAG + `set employee to be distributed table failed 2, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set employee to be distributed table failed 2, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0008 end *************"); }) /** @@ -316,21 +296,21 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0009 start *************"); try { await rdbStore.setDistributedTables(['employee'], relationalStore.DistributedType.DISTRIBUTED_CLOUD, null - ).then((err)=>{ + ).then((err) => { console.log(TAG + "set employee to be distributed cloud table success"); expect(true).assertTrue(); done(); - }).catch((err)=>{ - console.log(TAG + `set employee to be distributed table failed 1, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + "************* testRdbStoreCloud0009 end *************"); + }).catch((err) => { + console.log(TAG + `set employee to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() }); } catch (err) { - console.log(TAG + `set employee to be distributed table failed 2, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set employee to be distributed table failed 2, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0009 end *************"); }) /** @@ -345,13 +325,13 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "set local to be distributed device table success"); expect(true).assertTrue(); done(); + console.log(TAG + "************* testRdbStoreCloud0010 end *************"); }) } catch (err) { - console.log(TAG + `set employee to be distributed table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set employee to be distributed table failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0010 end *************"); }) /** @@ -363,19 +343,19 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "************* testRdbStoreCloud0011 start *************"); try { let config = { - autoSync:false + autoSync: false } rdbStore.setDistributedTables(['local'], null, config, function (err) { console.log(TAG + "set local to be distributed device table success"); expect(true).assertTrue(); done(); + console.log(TAG + "************* testRdbStoreCloud0011 end *************"); }) } catch (err) { - console.log(TAG + `set local to be distributed table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set local to be distributed table failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0011 end *************"); }) /** @@ -391,13 +371,13 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "set local to be distributed cloud table success"); expect(true).assertTrue(); done(); + console.log(TAG + "************* testRdbStoreCloud0012 end *************"); }) } catch (err) { - console.log(TAG + `set local to be distributed table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set local to be distributed table failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0012 end *************"); }) /** @@ -413,14 +393,14 @@ describe('rdbStoreDistributedCloudTest', function () { console.log(TAG + "set local to be distributed cloud table success"); expect(true).assertTrue(); done(); + console.log(TAG + "************* testRdbStoreCloud0013 end *************"); }) } catch (err) { - console.log(TAG + `set local to be distributed table failed, err code is ${err.code}, message is ${err.message}.`); - expect(false).assertTrue(); + console.log(TAG + `set local to be distributed table failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); done() } - console.log(TAG + "************* testRdbStoreCloud0013 end *************"); }) console.log(TAG + "*************Unit Test End*************"); -}) +}) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js index 2cb589c7..864330b0 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js @@ -23,7 +23,7 @@ var rdbStore = undefined; var context = ability_featureAbility.getContext() describe('rdbStoreCloudSyncTest', function () { - beforeAll(async function (done) { + beforeAll(async function () { console.info(TAG + 'beforeAll') const config = { "name": STORE_NAME, @@ -47,27 +47,17 @@ describe('rdbStoreCloudSyncTest', function () { "recycled BOOLEAN, " + "recycledTime INTEGER, " + "uuid INTEGER PRIMARY KEY)"; - try { - await rdbStore.executeSql(sql_text, null); - await rdbStore.executeSql(sql_int, null); - await rdbStore.executeSql(sql_integer, null); - console.log(TAG + "create table cloud_text cloud_int cloud_integer success"); - } catch (err) { - console.log(TAG + "create table cloud_text cloud_int cloud_integer failed"); - expect(null).assertFail(); - } + await rdbStore.executeSql(sql_text, null); + await rdbStore.executeSql(sql_int, null); + await rdbStore.executeSql(sql_integer, null); + console.log(TAG + "create table cloud_text cloud_int cloud_integer success"); let tableArray = ["cloud_text", "cloud_integer"]; const setConfig = { autoSync: false, } - let promise = rdbStore.setDistributedTables( + await rdbStore.setDistributedTables( tableArray, relationalStore.DistributedType.DISTRIBUTED_CLOUD, setConfig); - await promise.then(() => { - console.log(TAG + "set disTable success"); - }).catch((err) => { - console.log(TAG + 'set disTable fail, err: ${err}'); - }) let vBucketArray1 = new Array(); for (let i = 0; i < 5; i++) { let valueBucket = { @@ -91,10 +81,9 @@ describe('rdbStoreCloudSyncTest', function () { } await rdbStore.batchInsert("cloud_integer", vBucketArray2); } catch (err) { - console.log(TAG + "create rdb store failed" + `, error code is ${err.code}, message is ${err.message}`) - expect(null).assertFail() + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail() } - done(); }) beforeEach(async function () { @@ -118,18 +107,16 @@ describe('rdbStoreCloudSyncTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_CLOUD_SYNC_0001 * @tc.desc rdb get modify time using wrong primary key type */ - it('testRdbStoreCloudSync0001', 0, async function (done) { + it('testRdbStoreCloudSync0001', 0, async function () { console.log(TAG + "************* testRdbStoreCloudSync0001 start *************"); try { let key = new Array(); let PRIKey = [key, "test_key1", "test_key2"]; - rdbStore.getModifyTime("cloud_text", "uuid", PRIKey, function (err, data) { - console.log(TAG + 'modifyTime:' + JSON.stringify(data)); - }); + await rdbStore.getModifyTime("cloud_text", "uuid", PRIKey); + expect().assertFail(); } catch (err) { - console.log(TAG + `get modify time, err code is ${err.code}, message is ${err.message}.`); - expect(true).assertTrue(); - done(); + console.log(TAG + `get modify time, errcode:${JSON.stringify(err)}.`); + expect(err.code).assertEqual('401'); } console.log(TAG + "************* testRdbStoreCloudSync0001 end *************"); }) @@ -144,14 +131,16 @@ describe('rdbStoreCloudSyncTest', function () { try { let PRIKey = ["test_key1", "test_key2"]; rdbStore.getModifyTime("cloud_text", "uuid", PRIKey, function (err, data) { - console.log(TAG + `modifyTime:` + JSON.stringify(data)); + console.log(TAG + `modifyTime:` + JSON.stringify(err)); + done(); + expect(err.code).assertEqual(14800000); + console.log(TAG + "************* testRdbStoreCloudSync0002 end *************"); }); - expect(true).assertTrue(); - done(); } catch (err) { - console.log(TAG + `get modify time fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `get modify time fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0002 end *************"); }) /** @@ -159,17 +148,15 @@ describe('rdbStoreCloudSyncTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_CLOUD_SYNC_0003 * @tc.desc get modify time using string primary key type and promise method */ - it('testRdbStoreCloudSync0003', 0, async function (done) { + it('testRdbStoreCloudSync0003', 0, async function () { console.log(TAG + "************* testRdbStoreCloudSync0003 start *************"); + let PRIKey = ["test_key1", "test_key2"]; try { - let PRIKey = ["test_key1", "test_key2"]; - await rdbStore.getModifyTime("cloud_text", "uuid", PRIKey).then((data) => { - console.log(TAG + `modifyTime:` + JSON.stringify(data)); - expect(true).assertTrue(); - done(); - }); + await rdbStore.getModifyTime("cloud_text", "uuid", PRIKey); + expect().assertFail(); } catch (err) { - console.log(TAG + `get modify time fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `get modify time fail, errcode:${JSON.stringify(err)}.`); + expect(err.code).assertEqual(14800000); } console.log(TAG + "************* testRdbStoreCloudSync0003 end *************"); }) @@ -184,14 +171,16 @@ describe('rdbStoreCloudSyncTest', function () { try { let PRIKey = [1, 3, 4]; rdbStore.getModifyTime("cloud_text", "rowid", PRIKey, function (err, data) { - console.log(TAG + `modifyTime:` + JSON.stringify(data)); + console.log(TAG + `modifyTime:` + JSON.stringify(err)); + done(); + expect(err.code).assertEqual(14800000); + console.log(TAG + "************* testRdbStoreCloudSync0004 end *************"); }); - expect(true).assertTrue(); - done(); } catch (err) { - console.log(TAG + `get modify time fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `get modify time fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0004 end *************"); }) /** @@ -199,17 +188,15 @@ describe('rdbStoreCloudSyncTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_CLOUD_SYNC_0005 * @tc.desc get modify time using rowid and promise method */ - it('testRdbStoreCloudSync0005', 0, async function (done) { + it('testRdbStoreCloudSync0005', 0, async function () { console.log(TAG + "************* testRdbStoreCloudSync0005 start *************"); + let PRIKey = [2, 4]; try { - let PRIKey = [2, 4]; - await rdbStore.getModifyTime("cloud_text", "roWId", PRIKey).then((data) => { - console.log(TAG + `modifyTime:` + JSON.stringify(data)); - expect(true).assertTrue(); - done(); - }); + await rdbStore.getModifyTime("cloud_text", "roWId", PRIKey); + expect().assertFail(); } catch (err) { - console.log(TAG + `get modify time fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `get modify time fail, errcode:${JSON.stringify(err)}.`); + expect(err.code).assertEqual(14800000); } console.log(TAG + "************* testRdbStoreCloudSync0005 end *************"); }) @@ -219,28 +206,22 @@ describe('rdbStoreCloudSyncTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_CLOUD_SYNC_0004 * @tc.desc get modify time, but not set distributed table */ - it('testRdbStoreCloudSync0006', 0, async function (done) { + it('testRdbStoreCloudSync0006', 0, async function () { console.log(TAG + "************* testRdbStoreCloudSync0006 start *************"); + let valueBucket = { + "data": "cloud_sync_insert", + "recycled": true, + "recycledTime": 12345, + "uuid": undefined, + } + await rdbStore.insert("cloud_int", valueBucket); + let PRIKey = [0, 1, 2]; try { - for (let i = 0; i < 5; i++) { - let valueBucket = { - "data": "cloud_sync_insert", - "recycled": true, - "recycledTime": 12345, - "uuid": i, - } - let vBucketArray = new Array(); - vBucketArray.push(valueBucket); - await rdbStore.batchInsert("cloud_int", vBucketArray); - } - let PRIKey = [0, 1, 2]; - await rdbStore.getModifyTime("cloud_int", "uuid", PRIKey).then((data) => { - console.log(TAG + `modifyTime:` + JSON.stringify(data)); - }) + await rdbStore.getModifyTime("cloud_int", "uuid", PRIKey) + expect().assertFail(); } catch (err) { - console.log(TAG + `get modify time fail, err code is ${err.code}, message is ${err.message}.`); - expect(true).assertTrue(); - done(); + console.log(TAG + `get modify time fail, errcode:${JSON.stringify(err)}.`); + expect(err.code).assertEqual(14800000); } console.log(TAG + "************* testRdbStoreCloudSync0006 end *************"); }) @@ -255,14 +236,16 @@ describe('rdbStoreCloudSyncTest', function () { try { let PRIKey = [1, 2, 4]; rdbStore.getModifyTime("cloud_integer", "uuid", PRIKey, function (err, data) { - console.log(TAG + `modifyTime:` + JSON.stringify(data)); + console.log(TAG + `modifyTime:` + JSON.stringify(err)); + done(); + expect(err.code).assertEqual(14800000); + console.log(TAG + "************* testRdbStoreCloudSync0007 end *************"); }); - expect(true).assertTrue(); - done(); } catch (err) { - console.log(TAG + `get modify time fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `get modify time fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0007 end *************"); }) /** @@ -272,16 +255,16 @@ describe('rdbStoreCloudSyncTest', function () { */ it('testRdbStoreCloudSync0008', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloudSync0008 start *************"); - try { - let PRIKey = [2, 4]; - await rdbStore.getModifyTime("cloud_integer", "uuid", PRIKey).then((data) => { - console.log(TAG + `modifyTime:` + JSON.stringify(data)); - expect(true).assertTrue(); - done(); - }); - } catch (err) { - console.log(TAG + `get modify time fail, err code is ${err.code}, message is ${err.message}.`); - } + let PRIKey = [2, 4]; + await rdbStore.getModifyTime("cloud_integer", "uuid", PRIKey).then((err, data) => { + console.log(TAG + `modifyTime:` + JSON.stringify(err)); + done(); + expect().assertFail(); + }).catch((err) => { + console.log(TAG + `get modify time fail, errcode:${JSON.stringify(err)}.`); + done(); + expect(err.code).assertEqual(14800000); + }); console.log(TAG + "************* testRdbStoreCloudSync0008 end *************"); }) @@ -293,17 +276,18 @@ describe('rdbStoreCloudSyncTest', function () { it('testRdbStoreCloudSync0009', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloudSync0009 start *************"); try { - rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, function (ProgressDetail) { - console.log(TAG + `Progess:` + JSON.stringify(ProgressDetail)); - }, function (err, data) { - console.log(TAG + `cloud sync success:` + err); + rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, function (detail) { + console.log(TAG + `Progress:` + JSON.stringify(detail)); + done(); + expect(JSON.stringify(detail)).assertEqual('{"schedule":2,"code":3,"details":[]}'); + console.log(TAG + "************* testRdbStoreCloudSync0009 end *************"); + }, () => { }); - expect(true).assertTrue(); - done(); } catch (err) { - console.log(TAG + `cloud sync fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `cloud sync fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0009 end *************"); }) /** @@ -313,19 +297,21 @@ describe('rdbStoreCloudSyncTest', function () { */ it('testRdbStoreCloudSync0010', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloudSync0010 start *************"); - try { - function Progess(ProgressDetail) { - console.log(TAG + `Progess:` + JSON.stringify(ProgressDetail)); - } - await rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, Progess).then((data) => { - console.log(TAG + `cloud sync success:` + data); - }); - expect(true).assertTrue(); + + function Progress(detail) { + console.log(TAG + `Progress:` + JSON.stringify(detail)); done(); + expect(JSON.stringify(detail)).assertEqual('{"schedule":2,"code":3,"details":[]}'); + console.log(TAG + "************* testRdbStoreCloudSync0010 end *************"); + } + + try { + await rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, Progress) } catch (err) { - console.log(TAG + `cloud sync fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `cloud sync fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0010 end *************"); }) /** @@ -336,20 +322,22 @@ describe('rdbStoreCloudSyncTest', function () { it('testRdbStoreCloudSync0011', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloudSync0011 start *************"); try { - function Progess(ProgressDetail) { - console.log(TAG + `Progess:` + JSON.stringify(ProgressDetail)); + + function Progress(detail) { + console.log(TAG + `Progress:` + JSON.stringify(detail)); + done(); + expect(JSON.stringify(detail)).assertEqual('{"schedule":2,"code":3,"details":[]}'); + console.log(TAG + "************* testRdbStoreCloudSync0011 end *************"); } + let tableArray = ["cloud_text"]; - rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, tableArray, Progess, - function (err, data) { - console.log(TAG + `cloud sync success:` + err); + rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, tableArray, Progress, () => { }); - expect(true).assertTrue(); - done(); } catch (err) { - console.log(TAG + `cloud sync fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `cloud sync fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0011 end *************"); }) /** @@ -359,21 +347,22 @@ describe('rdbStoreCloudSyncTest', function () { */ it('testRdbStoreCloudSync0012', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloudSync0012 start *************"); - try { - function Progess(ProgressDetail) { - console.log(TAG + `Progess:` + JSON.stringify(ProgressDetail)); - } - let tableArray = ["cloud_text"]; - await rdbStore.cloudSync( - relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, tableArray, Progess).then((data) => { - console.log(TAG + `cloud sync success:` + data); - }); - expect(true).assertTrue(); + + function Progress(detail) { + console.log(TAG + `Progress:` + JSON.stringify(detail)); done(); + expect(JSON.stringify(detail)).assertEqual('{"schedule":2,"code":3,"details":[]}'); + console.log(TAG + "************* testRdbStoreCloudSync0012 end *************"); + } + + let tableArray = ["cloud_text"]; + try { + await rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, tableArray, Progress) } catch (err) { - console.log(TAG + `cloud sync fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `cloud sync fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0012 end *************"); }) /** @@ -383,21 +372,22 @@ describe('rdbStoreCloudSyncTest', function () { */ it('testRdbStoreCloudSync0013', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloudSync0013 start *************"); - try { - function Progess(ProgressDetail) { - console.log(TAG + `Progess:` + JSON.stringify(ProgressDetail)); - } - let tableArray = ["cloud_text"]; - await rdbStore.cloudSync( - relationalStore.SyncMode.SYNC_MODE_NATIVE_FIRST, tableArray, Progess).then((data) => { - console.log(TAG + `cloud sync success:` + data); - }); - expect(true).assertTrue(); + + function Progress(detail) { + console.log(TAG + `Progress:` + JSON.stringify(detail)); done(); + expect(JSON.stringify(detail)).assertEqual('{"schedule":2,"code":3,"details":[]}'); + console.log(TAG + "************* testRdbStoreCloudSync0013 end *************"); + } + + let tableArray = ["cloud_text"]; + try { + await rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_NATIVE_FIRST, tableArray, Progress) } catch (err) { - console.log(TAG + `cloud sync fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `cloud sync fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0013 end *************"); }) /** @@ -407,21 +397,22 @@ describe('rdbStoreCloudSyncTest', function () { */ it('testRdbStoreCloudSync0014', 0, async function (done) { console.log(TAG + "************* testRdbStoreCloudSync0014 start *************"); - try { - function Progess(ProgressDetail) { - console.log(TAG + `Progess:` + JSON.stringify(ProgressDetail)); - } - let tableArray = ["cloud_text"]; - await rdbStore.cloudSync( - relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tableArray, Progess).then((data) => { - console.log(TAG + `cloud sync success:` + data); - }); - expect(true).assertTrue(); + + function Progress(detail) { + console.log(TAG + `Progress:` + JSON.stringify(detail)); done(); + expect(JSON.stringify(detail)).assertEqual('{"schedule":2,"code":3,"details":[]}'); + console.log(TAG + "************* testRdbStoreCloudSync0014 end *************"); + } + + let tableArray = ["cloud_text"]; + try { + await rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tableArray, Progress) } catch (err) { - console.log(TAG + `cloud sync fail, err code is ${err.code}, message is ${err.message}.`); + console.log(TAG + `cloud sync fail, errcode:${JSON.stringify(err)}.`); + done(); + expect().assertFail(); } - console.log(TAG + "************* testRdbStoreCloudSync0014 end *************"); }) console.log(TAG + "*************Unit Test End*************"); }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js index cd183306..a56f3525 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js @@ -256,7 +256,7 @@ describe('rdbStoreDistributedTest', function () { console.log(TAG + "************* testRdbStoreDistributed0009 start *************"); let predicates = new data_relationalStore.RdbPredicates("employee") try { - predicates = predicates.inDevices("1234567890"); + predicates = predicates.inDevices(["1234567890"]); console.log(TAG + "inDevices success"); expect(predicates).assertEqual(predicates); } catch (err) { @@ -295,7 +295,7 @@ describe('rdbStoreDistributedTest', function () { it('testRdbStoreDistributed0011', 0, async function (done) { console.log(TAG + "************* testRdbStoreDistributed0011 start *************"); let predicates = new data_relationalStore.RdbPredicates("employee") - predicates = predicates.inDevices("12345678abcd"); + predicates = predicates.inDevices(["12345678abcd"]); rdbStore.sync(data_relationalStore.SyncMode.SYNC_MODE_PUSH, predicates); console.log(TAG + "sync push success"); expect(rdbStore).assertEqual(rdbStore); @@ -338,4 +338,111 @@ describe('rdbStoreDistributedTest', function () { console.log(TAG + "************* testRdbStoreDistributed0013 end *************"); }) console.log(TAG + "*************Unit Test End*************"); + + /** + * @tc.name subscribe test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_014 + * @tc.desc subscribe test + */ + it('testRdbStoreDistributed0014', 0, async function (done) { + console.log(TAG + "************* testRdbStoreDistributed0014 start *************"); + rdbStore.on("dataChange", data_relationalStore.SubscribeType.SUBSCRIBE_TYPE_CLOUD, (device) => { + console.log(TAG + device + " dataChange"); + }); + console.log(TAG + "on dataChange success"); + expect(rdbStore).assertEqual(rdbStore); + console.log(TAG + "************* testRdbStoreDistributed0014 end *************"); + done() + }) + + /** + * @tc.name unsubscribe test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_015 + * @tc.desc subscribe test + */ + it('testRdbStoreDistributed0015', 0, async function (done) { + console.log(TAG + "************* testRdbStoreDistributed0015 start *************"); + rdbStore.off("dataChange", data_relationalStore.SubscribeType.SUBSCRIBE_TYPE_CLOUD, (device) => { + console.log(TAG + device + " dataChange"); + }); + console.log(TAG + "off dataChange success"); + expect(rdbStore).assertEqual(rdbStore); + console.log(TAG + "************* testRdbStoreDistributed0015 end *************"); + done() + }) + + /** + * @tc.name subscribe test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_016 + * @tc.desc subscribe test + */ + it('testRdbStoreDistributed0016', 0, async function (done) { + console.log(TAG + "************* testRdbStoreDistributed0016 start *************"); + rdbStore.on("dataChange", data_relationalStore.SubscribeType.SUBSCRIBE_TYPE_CLOUD_DETAILS, (device) => { + console.log(TAG + device + " dataChange"); + }); + console.log(TAG + "on dataChange success"); + expect(rdbStore).assertEqual(rdbStore); + console.log(TAG + "************* testRdbStoreDistributed0016 end *************"); + done() + }) + + /** + * @tc.name unsubscribe test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_017 + * @tc.desc subscribe test + */ + it('testRdbStoreDistributed0017', 0, async function (done) { + console.log(TAG + "************* testRdbStoreDistributed0017 start *************"); + rdbStore.off("dataChange", data_relationalStore.SubscribeType.SUBSCRIBE_TYPE_CLOUD_DETAILS, (device) => { + console.log(TAG + device + " dataChange"); + }); + console.log(TAG + "off dataChange success"); + expect(rdbStore).assertEqual(rdbStore); + console.log(TAG + "************* testRdbStoreDistributed0017 end *************"); + done() + }) + + /** + * @tc.name unsubscribe test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_018 + * @tc.desc unsubscribe when no observer + */ + it('testRdbStoreDistributed0018', 0, async function (done) { + console.log(TAG + "************* testRdbStoreDistributed0018 start *************"); + rdbStore.off("dataChange", data_relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE); + console.log(TAG + "off dataChange success"); + expect(rdbStore).assertEqual(rdbStore); + console.log(TAG + "************* testRdbStoreDistributed0018 end *************"); + done() + }) + + /** + * @tc.name unsubscribe test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_019 + * @tc.desc unsubscribe when observer is null + */ + it('testRdbStoreDistributed0019', 0, async function (done) { + console.log(TAG + "************* testRdbStoreDistributed0019 start *************"); + rdbStore.off("dataChange", data_relationalStore.SubscribeType.SUBSCRIBE_TYPE_CLOUD, null); + console.log(TAG + "off dataChange success"); + expect(rdbStore).assertEqual(rdbStore); + console.log(TAG + "************* testRdbStoreDistributed0019 end *************"); + done() + }) + + /** + * @tc.name unsubscribe test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Distributed_020 + * @tc.desc unsubscribe when observer is undefined + */ + it('testRdbStoreDistributed0020', 0, async function (done) { + console.log(TAG + "************* testRdbStoreDistributed0020 start *************"); + rdbStore.off("dataChange", data_relationalStore.SubscribeType.SUBSCRIBE_TYPE_CLOUD_DETAILS, undefined); + console.log(TAG + "off dataChange success"); + expect(rdbStore).assertEqual(rdbStore); + console.log(TAG + "************* testRdbStoreDistributed0020 end *************"); + done() + }) + console.log(TAG + "*************Unit Test End*************"); }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js index 8d4aa87e..cc9cc04b 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js @@ -127,32 +127,15 @@ describe('rdbStoreBackupRestoreWithFAContextTest', function () { it('RdbBackupRestoreTest_0010', 0, async function (done) { await console.log(TAG + "************* RdbBackupRestoreTest_0010 start *************") - // RDB backup function test try { - let promiseBackup = rdbStore.backup(DATABASE_BACKUP_NAME) - promiseBackup.then(() => { - expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + DATABASE_BACKUP_NAME)) - expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) - }).catch((errCode) => { - expect(false).assertTrue() - }) - await promiseBackup; - } catch(err) { - expect(false).assertTrue() - } + await rdbStore.backup(DATABASE_BACKUP_NAME) + // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + DATABASE_BACKUP_NAME)) + // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) - // RDB restore function test - try { - let promiseRestore = rdbStore.restore(DATABASE_BACKUP_NAME) - promiseRestore.then(() => { - expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) - done() - }).catch((errCode) => { - expect(false).assertTrue() - }) - await promiseRestore - } catch(err) { - expect(false).assertTrue() + await rdbStore.restore(DATABASE_BACKUP_NAME) + // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) + } catch (err) { + expect().assertFail() } // RDB after restored, data query test diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js index e01ff99c..83f0ef6b 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js @@ -73,162 +73,154 @@ async function CreatRdbStore(context, STORE_CONFIG) { } describe('rdbEncryptTest', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll') - - }) - - beforeEach(async function () { - console.info(TAG + 'beforeEach') - - }) + beforeAll(async function () { + console.info(TAG + 'beforeAll') + }) - afterEach(async function () { - console.info(TAG + 'afterEach') - await data_relationalStore.deleteRdbStore(context, STORE_CONFIG_ENCRYPT.name) - await data_relationalStore.deleteRdbStore(context, STORE_CONFIG_UNENCRYPT.name) - await data_relationalStore.deleteRdbStore(context, STORE_CONFIG_WRONG.name) - }) + beforeEach(async function () { + console.info(TAG + 'beforeEach') + }) - afterAll(async function () { - console.info(TAG + 'afterAll') - }) + afterEach(async function () { + console.info(TAG + 'afterEach') + await data_relationalStore.deleteRdbStore(context, STORE_CONFIG_ENCRYPT.name) + await data_relationalStore.deleteRdbStore(context, STORE_CONFIG_UNENCRYPT.name) + await data_relationalStore.deleteRdbStore(context, STORE_CONFIG_WRONG.name) + }) - console.log(TAG + "*************Unit Test Begin*************") - - /** - * @tc.name RDB encrypted test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0010 - * @tc.desc RDB create encrypt db test - */ - it('RdbEncryptTest_0010', 0, async function (done) { - await console.log(TAG + "************* RdbEncryptTest_0010 start *************") - let storePromise = data_relationalStore.getRdbStore(context, STORE_CONFIG_ENCRYPT); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - } catch (err) { - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null + afterAll(async function () { + console.info(TAG + 'afterAll') + }) - done() - await console.log(TAG + "************* RdbEncryptTest_0010 end *************") - }) + console.log(TAG + "*************Unit Test Begin*************") - /** - * @tc.name RDB unencrypted test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0020 - * @tc.desc RDB create unencrypted db test - */ - it('RdbEncryptTest_0020', 0, async function (done) { - await console.log(TAG + "************* RdbEncryptTest_0020 start *************") - let storePromise = data_relationalStore.getRdbStore(context, STORE_CONFIG_UNENCRYPT); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - } catch (err) { - expect(null).assertFail(); - } - store = null - }).catch((err) => { + /** + * @tc.name RDB encrypted test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0010 + * @tc.desc RDB create encrypt db test + */ + it('RdbEncryptTest_0010', 0, async function (done) { + await console.log(TAG + "************* RdbEncryptTest_0010 start *************") + let storePromise = data_relationalStore.getRdbStore(context, STORE_CONFIG_ENCRYPT); + storePromise.then(async (store) => { + try { + await console.log(TAG + "getRdbStore done: " + store); + } catch (err) { expect(null).assertFail(); - }) - await storePromise - storePromise = null - - done() - await console.log(TAG + "************* RdbEncryptTest_0020 end *************") + } + store = null + }).catch((err) => { + expect(null).assertFail(); }) + await storePromise + storePromise = null + done() + await console.log(TAG + "************* RdbEncryptTest_0010 end *************") + }) - /** - * @tc.name RDB Encrypt test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0030 - * @tc.desc RDB Encrypt function test - */ - it('RdbEncryptTest_0030', 0, async function (done) { - await console.log(TAG + "************* RdbEncryptTest_0030 start *************") - let rdbStore = await CreatRdbStore(context, STORE_CONFIG_ENCRYPT) - let predicates = new data_relationalStore.RdbPredicates("test") - predicates.equalTo("name", "zhangsan") - let resultSet = await rdbStore.query(predicates) + /** + * @tc.name RDB unencrypted test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0020 + * @tc.desc RDB create unencrypted db test + */ + it('RdbEncryptTest_0020', 0, async function (done) { + await console.log(TAG + "************* RdbEncryptTest_0020 start *************") + let storePromise = data_relationalStore.getRdbStore(context, STORE_CONFIG_UNENCRYPT); + storePromise.then(async (store) => { try { - console.log(TAG + "After restore resultSet query done") - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = resultSet.getLong(resultSet.getColumnIndex("id")) - const name = resultSet.getString(resultSet.getColumnIndex("name")) - const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) - expect(1).assertEqual(id) - expect("zhangsan").assertEqual(name) - expect(1).assertEqual(blobType[0]) + await console.log(TAG + "getRdbStore done: " + store); } catch (err) { - expect(false).assertTrue() + expect(null).assertFail(); } - resultSet.close() - resultSet = null - rdbStore = null - done() - await console.log(TAG + "************* RdbEncryptTest_0030 end *************") + store = null + }).catch((err) => { + expect(null).assertFail(); }) + await storePromise + storePromise = null - /** - * @tc.name RDB Encrypt test - * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0040 - * @tc.desc RDB Encrypt function test - */ - it('RdbEncryptTest_0040', 0, async function () { - await console.log(TAG + "************* RdbEncryptTest_0040 start *************") - let rdbStore = await CreatRdbStore(context, STORE_CONFIG_ENCRYPT) - rdbStore = null + done() + await console.log(TAG + "************* RdbEncryptTest_0020 end *************") + }) - try { - rdbStore = await CreatRdbStore(context, STORE_CONFIG_WRONG) - expect(false).assertTrue() - } catch (err) { - expect(err.code).assertEqual(14800000); - } - await console.log(TAG + "************* RdbEncryptTest_0040 end *************") - }) + /** + * @tc.name RDB Encrypt test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0030 + * @tc.desc RDB Encrypt function test + */ + it('RdbEncryptTest_0030', 0, async function (done) { + await console.log(TAG + "************* RdbEncryptTest_0030 start *************") + let rdbStore = await CreatRdbStore(context, STORE_CONFIG_ENCRYPT) + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("name", "zhangsan") + let resultSet = await rdbStore.query(predicates) + try { + console.log(TAG + "After restore resultSet query done") + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = resultSet.getLong(resultSet.getColumnIndex("id")) + const name = resultSet.getString(resultSet.getColumnIndex("name")) + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) + expect(1).assertEqual(id) + expect("zhangsan").assertEqual(name) + expect(1).assertEqual(blobType[0]) + } catch (err) { + expect(false).assertTrue() + } + resultSet.close() + resultSet = null + rdbStore = null + done() + await console.log(TAG + "************* RdbEncryptTest_0030 end *************") + }) + + /** + * @tc.name RDB Encrypt test + * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0040 + * @tc.desc RDB Encrypt function test + */ + it('RdbEncryptTest_0040', 0, async function () { + await console.log(TAG + "************* RdbEncryptTest_0040 start *************") + let rdbStore = await CreatRdbStore(context, STORE_CONFIG_ENCRYPT) + rdbStore = null + + try { + rdbStore = await CreatRdbStore(context, STORE_CONFIG_WRONG) + expect(false).assertTrue() + } catch (err) { + expect(err.code).assertEqual(14800000); + } + + await console.log(TAG + "************* RdbEncryptTest_0040 end *************") + }) /** * @tc.name RDB Encrypt test * @tc.number SUB_DDM_RDB_JS_RdbEncryptTest_0050 * @tc.desc RDB Encrypt function test for setDistributedTables and insert. */ - it('RdbEncryptTest_0050', 0, async function (done) { + it('RdbEncryptTest_0050', 0, async function () { await console.log(TAG + "************* RdbEncryptTest_0050 start *************") - let rdbStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG_ENCRYPT) - await rdbStore.executeSql(CREATE_TABLE_TEST, null) - await rdbStore.setDistributedTables(['test']) - - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - let insertPromise = rdbStore.insert("test", valueBucket) - insertPromise.then(async (ret) => { + try { + let rdbStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG_ENCRYPT) + await rdbStore.executeSql(CREATE_TABLE_TEST, null) + await rdbStore.setDistributedTables(['test']) + + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let ret = await rdbStore.insert("test", valueBucket) expect(1).assertEqual(ret) - console.log(TAG + "insert first done: " + ret) - done() - }).catch((err) => { - expect(false).assertTrue() - console.log(TAG + "insert error, err: code = " + err.code + " message=" + err.message) - }) - - await insertPromise; - done() - await console.log(TAG + "************* RdbEncryptTest_0050 end *************") + } catch (err) { + console.log(TAG + `fails errcode:${JSON.stringify(err)}.`); + expect().assertFail(); + } + console.log(TAG + "************* RdbEncryptTest_0050 end *************") }) - console.log(TAG + "*************Unit Test End*************") - } -) + console.log(TAG + "*************Unit Test End*************") +}) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js index 38332583..38d48dbe 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js @@ -421,7 +421,7 @@ describe('rdbStoreInsertTest', function () { await rdbStore.insert("test", valueBucketInsert) try { await rdbStore.insert("test", valueBucket, data_relationalStore.ConflictResolution.ON_CONFLICT_ROLLBACK); - expect(null).assertFail();; + expect(null).assertFail(); } catch (err) { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message); expect(14800000).assertEqual(err.code); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js index 01950873..10daeb00 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js @@ -51,22 +51,15 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0010 * @tc.desc rdb store getRdbStore test */ - it('testRdbStore0001', 0, async function (done) { + it('testRdbStore0001', 0, async function () { console.log(TAG + "************* testRdbStore0001 start *************"); - let storePromise = data_relationalStore.getRdbStore(context, STORE_CONFIG); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - } catch (e) { - expect(null).assertFail(); - } + try { + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + console.log(TAG + "getRdbStore done: " + store); store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - done(); + } catch (e) { + expect().assertFail(); + } console.log(TAG + "************* testRdbStore0001 end *************"); }) @@ -75,23 +68,16 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0020 * @tc.desc rdb store getRdbStore and create table */ - it('testRdbStore0002', 0, async function (done) { + it('testRdbStore0002', 0, async function () { console.log(TAG + "************* testRdbStore0002 start *************"); - let storePromise = data_relationalStore.getRdbStore(context, STORE_CONFIG); - storePromise.then(async (store) => { - try { - await console.log(TAG + "getRdbStore done: " + store); - await store.executeSql(CREATE_TABLE_TEST); - } catch (e) { - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - done(); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + try { + console.log(TAG + "getRdbStore done: " + store); + await store.executeSql(CREATE_TABLE_TEST); + } catch (e) { + expect().assertFail(); + } + store = null console.log(TAG + "************* testRdbStore0002 end *************"); }) @@ -100,23 +86,17 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0030 * @tc.desc rdb store getRdbStore with wrong path */ - it('testRdbStore0003', 0, async function (done) { + it('testRdbStore0003', 0, async function () { console.log(TAG + "************* testRdbStore0003 start *************"); let storeConfig = { name: "/wrong/rdbstore.db", securityLevel: data_relationalStore.SecurityLevel.S1, } try { - data_relationalStore.getRdbStore(context, storeConfig).then(async (ret) => { - await console.info(TAG + "getRdbStore done" + ret); - expect(null).assertFail(); - }).catch((err) => { - console.info(TAG + "getRdbStore with wrong path"); - }) - } catch(e) { + await data_relationalStore.getRdbStore(context, storeConfig) + } catch (e) { console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) expect("401").assertEqual(e.code) - done(); console.info(TAG + "************* testRdbStore0003 end *************"); } }) @@ -126,24 +106,15 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0040 * @tc.desc rdb store deleteRdbStore */ - it('testRdbStore0004', 0, async function (done) { + it('testRdbStore0004', 0, async function () { console.log(TAG + "************* testRdbStore0004 start *************"); - let storePromise = data_relationalStore.getRdbStore(context, STORE_CONFIG); - storePromise.then(async (store) => { - console.log(TAG + "getRdbStore done:" + store); - try { - await store.executeSql(CREATE_TABLE_TEST); - } catch (e) { - console.log(TAG + "create table error"); - expect(null).assertFail(); - } - store = null - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - done(); + try { + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + } catch (e) { + console.log(TAG + "create table error"); + expect().assertFail(); + } console.log(TAG + "************* testRdbStore0004 end *************"); }) @@ -152,7 +123,7 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0050 * @tc.desc rdb store setVersion & getVersion */ - it('testRdbStore0005', 0, async function (done) { + it('testRdbStore0005', 0, async function () { console.log(TAG + "************* testRdbStore0005 start *************"); let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); @@ -161,13 +132,12 @@ describe('rdbStoreTest', function () { expect(5).assertEqual(store.version) store.version = 2147483647 expect(2147483647).assertEqual(store.version) - store = null } catch (e) { - expect(null).assertFail(); + expect().assertFail(); } + store = null await data_relationalStore.deleteRdbStore(context, "rdbstore.db"); - done(); console.log(TAG + "************* testRdbStore0005 end *************"); }) @@ -176,7 +146,7 @@ describe('rdbStoreTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_0060 * @tc.desc rdb store setVersion */ - it('testRdbStore0006', 0, async function (done) { + it('testRdbStore0006', 0, async function () { console.log(TAG + "************* testRdbStore0006 start *************"); let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); @@ -197,9 +167,9 @@ describe('rdbStoreTest', function () { } catch (err) { expect("401").assertEqual(err.code); } + store = null await data_relationalStore.deleteRdbStore(context, "rdbstore.db"); - done(); console.log(TAG + "************* testRdbStore0006 end *************"); }) @@ -209,27 +179,20 @@ describe('rdbStoreTest', function () { * @tc.desc rdb store getRdbStore with securityLevel * @tc.require: I5PIL6 */ - it('testRdbStore0007', 0, async function (done) { + it('testRdbStore0007', 0, async function () { console.log(TAG + "************* testRdbStore0007 start *************"); let config = { name: "secure.db", securityLevel: data_relationalStore.SecurityLevel.S3 } - let storePromise = data_relationalStore.getRdbStore(context, config); - storePromise.then(async (store) => { - try { - await store.executeSql(CREATE_TABLE_TEST); - store = null - } catch (e) { - expect(null).assertFail(); - } - }).catch((err) => { - expect(null).assertFail(); - }) - await storePromise - storePromise = null - await data_relationalStore.deleteRdbStore(context, "secure.db"); - done(); + try { + let store = await data_relationalStore.getRdbStore(context, config); + await store.executeSql(CREATE_TABLE_TEST); + store = null + await data_relationalStore.deleteRdbStore(context, "secure.db"); + } catch (e) { + expect().assertFail(); + } console.log(TAG + "************* testRdbStore0007 end *************"); }) @@ -239,25 +202,17 @@ describe('rdbStoreTest', function () { * @tc.desc rdb store getRdbStore with invalid securityLevel * @tc.require: I5PIL6 */ - it('testRdbStore0008', 0, async function (done) { + it('testRdbStore0008', 0, async function () { console.log(TAG + "************* testRdbStore0008 start *************"); let config = { name: "secure.db", securityLevel: 8 } try { - var storePromise = data_relationalStore.getRdbStore(context, config); - storePromise.then(async (ret) => { - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "getRdbStore with invalid securityLevel"); - }) + await data_relationalStore.getRdbStore(context, config); } catch (err) { expect("401").assertEqual(err.code) - done() } - storePromise = null - done(); console.log(TAG + "************* testRdbStore0008 end *************"); }) @@ -267,7 +222,7 @@ describe('rdbStoreTest', function () { * @tc.desc rdb store getRdbStore with different securityLevel * @tc.require: I5PIL6 */ - it('testRdbStore0009', 0, async function (done) { + it('testRdbStore0009', 0, async function () { console.log(TAG + "************* testRdbStore0009 start *************"); let config1 = { name: "rdbstore.db", @@ -282,20 +237,11 @@ describe('rdbStoreTest', function () { await data_relationalStore.getRdbStore(context, config1); try { - var storePromise = data_relationalStore.getRdbStore(context, config2); - storePromise.then(async (ret) => { - expect(false).assertTrue() - }).catch((err) => { - expect(14800000).assertEqual(err.code) - console.log(TAG + "getRdbStore with different securityLevel err: code = " + - err.code + " message = " + err.message); - done() - }) - } catch (e) { - expect(false).assertTrue() + await data_relationalStore.getRdbStore(context, config2); + } catch (err) { + expect(14800000).assertEqual(err.code) + console.log(TAG + "************* testRdbStore0009 end *************"); } - storePromise = null - console.log(TAG + "************* testRdbStore0009 end *************"); }) /** @@ -318,22 +264,16 @@ describe('rdbStoreTest', function () { await data_relationalStore.getRdbStore(context, config1); - try { - data_relationalStore.getRdbStore(context, config2, async (err, rdbStore) => { - if (err) { - expect(14800000).assertEqual(err.code) - console.log(TAG + "getRdbStore with different securityLevel err: code = " + - err.code + " message = " + err.message); - done() - } else { - console.log("Get RdbStore successfully.") - expect(false).assertTrue() - } - }) - } catch (e) { - expect(false).assertTrue() - } - console.log(TAG + "************* testRdbStore0010 end *************"); + data_relationalStore.getRdbStore(context, config2, async (err, rdbStore) => { + if (err) { + done() + expect(14800000).assertEqual(err.code) + console.log(TAG + "************* testRdbStore0010 end *************"); + } else { + console.log("Get RdbStore successfully.") + expect(false).assertTrue() + } + }) }) console.log(TAG + "*************Unit Test End*************"); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js index c2d1fcd8..e04ed4d0 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js @@ -54,10 +54,10 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0001 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0001', 0, async function (done) { + it('testRdbStoreUpdate0001', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0001 start *************"); - var u8 = new Uint8Array([1, 2, 3]) - { + var u8 = new Uint8Array([1, 2, 3]); + try { const valueBucket = { "name": "zhangsan", "age": 18, @@ -66,8 +66,11 @@ describe('rdbStoreUpdateTest', function () { } let ret = await rdbStore.insert("test", valueBucket) expect(1).assertEqual(ret); + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail() } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "name": "lisi", @@ -75,43 +78,40 @@ describe('rdbStoreUpdateTest', function () { "salary": 200.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("id", "1") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - let resultSet = await rdbStore.query(predicates) + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("id", "1") + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(1).assertEqual(id); - await expect("lisi").assertEqual(name); - await expect(20).assertEqual(age); - await expect(200.5).assertEqual(salary); - await expect(4).assertEqual(blobType[0]); - await expect(5).assertEqual(blobType[1]); - await expect(6).assertEqual(blobType[2]); - await expect(false).assertEqual(resultSet.goToNextRow()) - resultSet.close() - resultSet = null - } - - done(); - console.log(TAG + "************* testRdbStoreUpdate0001 end *************"); - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) - // await updatePromise + predicates = new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + + await expect(1).assertEqual(id); + await expect("lisi").assertEqual(name); + await expect(20).assertEqual(age); + await expect(200.5).assertEqual(salary); + await expect(4).assertEqual(blobType[0]); + await expect(5).assertEqual(blobType[1]); + await expect(6).assertEqual(blobType[2]); + await expect(false).assertEqual(resultSet.goToNextRow()) + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail() } + + console.log(TAG + "************* testRdbStoreUpdate0001 end *************"); }) /** @@ -119,61 +119,41 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0002 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0002', 0, async function (done) { + it('testRdbStoreUpdate0002', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0002 start *************"); - { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - try { - let predicates = new data_relationalStore.RdbPredicates("") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with null table name"); - }) - } catch (err) { - console.log( - "catch err: update with null table name failed, err: code=" + err.code + " message=" + err.message) - expect("401").assertEqual(err.code) - } - try { - const emptyBucket = {}; - let predicates = await new data_relationalStore.RdbPredicates("test") - let updatePromise = rdbStore.update(emptyBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong valueBucket"); - }) - } catch (err) { - console.log("catch err: update with wrong valueBucket failed, err: code=" + err.code - + " message=" + err.message) - expect("401").assertEqual(err.code) - } - try { - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("aaa", "null") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong condition"); - }) - } catch (err) { - console.log("catch err: update with wrong condition failed, err: code=" + err.code - + " message=" + err.message) - } + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + try { + let predicates = new data_relationalStore.RdbPredicates("") + await rdbStore.update(valueBucket, predicates) // table name should not empty + expect().assertFail() + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect("401").assertEqual(err.code) + } + try { + const emptyBucket = {}; + let predicates = new data_relationalStore.RdbPredicates("test") + await rdbStore.update(emptyBucket, predicates) // emptyBucket should not empty + expect().assertFail() + } catch (err) { + console.log(TAG + `test failed, err: ${JSON.stringify(err)}`) + expect(14800000).assertEqual(err.code) + } + try { + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("aaa", "null") // column aaa not exist + await rdbStore.update(valueBucket, predicates) + expect().assertFail() + } catch (err) { + console.log(TAG + `aaa failed, err: ${JSON.stringify(err)}`) + expect(14800000).assertEqual(err.code) } - done(); console.log(TAG + "************* testRdbStoreUpdate0002 end *************"); }) @@ -182,41 +162,32 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0003 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0003', 0, async function (done) { + it('testRdbStoreUpdate0003', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0003 start *************"); - { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - "wrongColumn": 100.5, - } - { - let predicates = new data_relationalStore.RdbPredicates("wrongTable") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong table name"); - }) - // await updatePromise - } - { - let predicates = await new data_relationalStore.RdbPredicates("test") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong column name"); - }) - // await updatePromise - } + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + "wrongColumn": 100.5, + } + try { + let predicates = new data_relationalStore.RdbPredicates("wrongTable") + await rdbStore.update(valueBucket, predicates) // wrongTable not exist + expect().assertFail() + } catch (err) { + console.log(TAG + `wrongTable failed, err: ${JSON.stringify(err)}`) + expect(14800000).assertEqual(err.code) + } + try { + let predicates = new data_relationalStore.RdbPredicates("test") + await rdbStore.update(valueBucket, predicates) // wrongColumn not exist + expect().assertFail() + } catch (err) { + console.log(TAG + `test failed, err: ${JSON.stringify(err)}`) + expect(14800000).assertEqual(err.code) } - done(); console.log(TAG + "************* testRdbStoreUpdate0003 end *************"); }) @@ -225,44 +196,35 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0004 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdate0004', 0, async function (done) { + it('testRdbStoreUpdate0004', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0004 start *************"); - { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - { - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("aaa", "null") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong condition"); - }) - // await updatePromise - } - { - const emptyBucket = {}; - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("name", "zhangsan") - await predicates.equalTo("age", 18) - await predicates.equalTo("null", 100.5) - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await console.log(TAG + "update done: " + ret); - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "update with wrong condition"); - }) - } + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + try { + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("aaa", "null") + await rdbStore.update(valueBucket, predicates) + expect().assertFail() + } catch (err) { + console.log(TAG + `test failed, err: ${JSON.stringify(err)}`) + expect(14800000).assertEqual(err.code) + } + try { + const emptyBucket = {}; + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("name", "zhangsan") + predicates.equalTo("age", 18) + predicates.equalTo("null", 100.5) + await rdbStore.update(emptyBucket, predicates) + } catch (err) { + console.log(TAG + `emptyBucket failed, err: ${JSON.stringify(err)}`) + expect(14800000).assertEqual(err.code) } - done(); console.log(TAG + "************* testRdbStoreUpdate0004 end *************"); }) @@ -271,10 +233,10 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0005 * @tc.desc resultSet Update Extra long character test */ - it('testRdbStoreUpdate0005', 0, async function (done) { + it('testRdbStoreUpdate0005', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0005 start *************"); var u8 = new Uint8Array([1, 2, 3]) - { + try { const valueBucket = { "name": "xiaoming", "age": 18, @@ -282,8 +244,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) var nameStr = "abcd" + "e".repeat(2000) + "./&*$!@()" const valueBucket = { @@ -292,30 +257,28 @@ describe('rdbStoreUpdateTest', function () { "salary": 200.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("name", "xiaoming") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - predicates.equalTo("age", 20) - let resultSet = await rdbStore.query(predicates) - expect(true).assertEqual(resultSet.goToFirstRow()) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - await expect(nameStr).assertEqual(name); - resultSet.close() - resultSet = null - } + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("name", "xiaoming") + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); - done(); - console.log(TAG + "************* testRdbStoreUpdate0005 end *************"); - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) + predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", 20) + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + await expect(nameStr).assertEqual(name); + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail() } + console.log(TAG + "************* testRdbStoreUpdate0005 end *************"); }) /** @@ -323,10 +286,10 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0006 * @tc.desc resultSet Update Extra long character test */ - it('testRdbStoreUpdate0006', 0, async function (done) { + it('testRdbStoreUpdate0006', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0006 start *************"); var u8 = new Uint8Array([1, 2, 3]) - { + try { const valueBucket = { "name": "xiaohua", "age": 18, @@ -334,8 +297,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) var nameStr = "橘子是水果" + "e".repeat(2000) const valueBucket = { @@ -344,30 +310,27 @@ describe('rdbStoreUpdateTest', function () { "salary": 200.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("name", "xiaohua") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - predicates.equalTo("age", 19) - let resultSet = await rdbStore.query(predicates) - expect(true).assertEqual(resultSet.goToFirstRow()) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - await expect(nameStr).assertEqual(name); - resultSet.close() - resultSet = null - } - - done(); - console.log(TAG + "************* testRdbStoreUpdate0006 end *************"); - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("name", "xiaohua") + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); + predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", 19) + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + await expect(nameStr).assertEqual(name); + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } + console.log(TAG + "************* testRdbStoreUpdate0006 end *************"); }) /** @@ -375,10 +338,10 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0007 * @tc.desc resultSet Update Extra long character test */ - it('testRdbStoreUpdate0007', 0, async function (done) { + it('testRdbStoreUpdate0007', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0007 start *************"); var u8 = new Uint8Array([1, 2, 3]) - { + try { const valueBucket = { "name": "xiaocan", "age": 18, @@ -386,8 +349,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) var nameStr = "菠萝是水果" + "e".repeat(2000) + "好吃又不贵" const valueBucket = { @@ -396,30 +362,27 @@ describe('rdbStoreUpdateTest', function () { "salary": 200.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("name", "xiaocan") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - predicates.equalTo("age", 21) - let resultSet = await rdbStore.query(predicates) - expect(true).assertEqual(resultSet.goToFirstRow()) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - await expect(nameStr).assertEqual(name); - resultSet.close() - resultSet = null - } - - done(); - console.log(TAG + "************* testRdbStoreUpdate0007 end *************"); - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - }) + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("name", "xiaocan") + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); + predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", 21) + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + await expect(nameStr).assertEqual(name); + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } + console.log(TAG + "************* testRdbStoreUpdate0007 end *************"); }) /** @@ -427,7 +390,7 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_Update_0008 * @tc.desc rdb update test */ - it('testRdbStoreUpdate0008', 0, async function (done) { + it('testRdbStoreUpdate0008', 0, async function () { console.log(TAG + "************* testRdbStoreUpdate0008 start *************"); try { const valueBucket = { @@ -438,11 +401,10 @@ describe('rdbStoreUpdateTest', function () { } var predicate = new dataSharePredicates.DataSharePredicates(); await rdbStore.update("test", valueBucket, predicate); - expect(null).assertFail(); + expect().assertFail() } catch (err) { - console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) expect("202").assertEqual(err.code) - done() } console.log(TAG + "************* testRdbStoreUpdate0008 end *************"); }) @@ -452,9 +414,9 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_UpdateWithConflictResolution_0001 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdateWithConflictResolution0001', 0, async function (done) { + it('testRdbStoreUpdateWithConflictResolution0001', 0, async function () { console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0001 start *************"); - { + try { var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "id": 1, @@ -464,8 +426,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "id": 2, @@ -475,9 +440,12 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert2 failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([7, 8, 9]) const valueBucket = { "id": 3, @@ -486,61 +454,58 @@ describe('rdbStoreUpdateTest', function () { "salary": 300.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("age", "19") - let updatePromise = rdbStore.update(valueBucket, predicates) - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - let resultSet = await rdbStore.query(predicates) - - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(1).assertEqual(id); - await expect("zhangsan").assertEqual(name); - await expect(18).assertEqual(age); - await expect(100.5).assertEqual(salary); - await expect(1).assertEqual(blobType[0]); - await expect(2).assertEqual(blobType[1]); - await expect(3).assertEqual(blobType[2]); - console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" - + salary + ", blobType=" + blobType); - - await expect(true).assertEqual(resultSet.goToNextRow()) - const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) - const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", "19") + let ret = await rdbStore.update(valueBucket, predicates) + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); + predicates = new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) - await expect(3).assertEqual(id_1); - await expect("wangjing").assertEqual(name_1); - await expect(20).assertEqual(age_1); - await expect(300.5).assertEqual(salary_1); - await expect(7).assertEqual(blobType_1[0]); - await expect(8).assertEqual(blobType_1[1]); - await expect(9).assertEqual(blobType_1[2]); - console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" - + salary_1 + ", blobType=" + blobType_1); - await expect(false).assertEqual(resultSet.goToNextRow()) - resultSet.close() - resultSet = null - done(); - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0001 end *************"); - } - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0001 end *************"); - }) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" + + salary + ", blobType=" + blobType); + + await expect(1).assertEqual(id); + await expect("zhangsan").assertEqual(name); + await expect(18).assertEqual(age); + await expect(100.5).assertEqual(salary); + await expect(1).assertEqual(blobType[0]); + await expect(2).assertEqual(blobType[1]); + await expect(3).assertEqual(blobType[2]); + + await expect(true).assertEqual(resultSet.goToNextRow()) + const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) + const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" + + salary_1 + ", blobType=" + blobType_1); + + await expect(3).assertEqual(id_1); + await expect("wangjing").assertEqual(name_1); + await expect(20).assertEqual(age_1); + await expect(300.5).assertEqual(salary_1); + await expect(7).assertEqual(blobType_1[0]); + await expect(8).assertEqual(blobType_1[1]); + await expect(9).assertEqual(blobType_1[2]); + await expect(false).assertEqual(resultSet.goToNextRow()) + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } + console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0001 end *************"); }) /** @@ -548,9 +513,9 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_UpdateWithConflictResolution_0002 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdateWithConflictResolution0002', 0, async function (done) { + it('testRdbStoreUpdateWithConflictResolution0002', 0, async function () { console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0002 start *************"); - { + try { var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "id": 1, @@ -560,8 +525,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "id": 2, @@ -571,8 +539,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert2 failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([7, 8, 9]) const valueBucket = { "id": 3, @@ -581,27 +552,26 @@ describe('rdbStoreUpdateTest', function () { "salary": 300.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("age", "19") - try { - await rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_NONE); - expect(null).assertFail(); - } catch(err) { - console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) - expect(14800000).assertEqual(err.code) - } + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", "19") + await rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_NONE); + expect().assertFail() + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect(14800000).assertEqual(err.code) } - { - let predicates = await new data_relationalStore.RdbPredicates("test") - let resultSet = await rdbStore.query(predicates) - + let predicates = new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + try { expect(true).assertEqual(resultSet.goToFirstRow()) const id = await resultSet.getLong(resultSet.getColumnIndex("id")) const name = await resultSet.getString(resultSet.getColumnIndex("name")) const age = await resultSet.getLong(resultSet.getColumnIndex("age")) const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" + + salary + ", blobType=" + blobType); await expect(1).assertEqual(id); await expect("zhangsan").assertEqual(name); @@ -610,8 +580,6 @@ describe('rdbStoreUpdateTest', function () { await expect(1).assertEqual(blobType[0]); await expect(2).assertEqual(blobType[1]); await expect(3).assertEqual(blobType[2]); - console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" - + salary + ", blobType=" + blobType); await expect(true).assertEqual(resultSet.goToNextRow()) const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) @@ -619,6 +587,8 @@ describe('rdbStoreUpdateTest', function () { const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" + + salary_1 + ", blobType=" + blobType_1); await expect(2).assertEqual(id_1); await expect("lisi").assertEqual(name_1); @@ -627,14 +597,15 @@ describe('rdbStoreUpdateTest', function () { await expect(4).assertEqual(blobType_1[0]); await expect(5).assertEqual(blobType_1[1]); await expect(6).assertEqual(blobType_1[2]); - console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" - + salary_1 + ", blobType=" + blobType_1); await expect(false).assertEqual(resultSet.goToNextRow()) + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); + } finally { resultSet.close() resultSet = null - done() - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0002 end *************"); } + console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0002 end *************"); }) /** @@ -642,9 +613,9 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_UpdateWithConflictResolution_0003 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdateWithConflictResolution0003', 0, async function (done) { + it('testRdbStoreUpdateWithConflictResolution0003', 0, async function () { console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0003 start *************"); - { + try { var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "id": 1, @@ -654,8 +625,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "id": 2, @@ -665,8 +639,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert2 failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([7, 8, 9]) const valueBucket = { "id": 3, @@ -675,63 +652,58 @@ describe('rdbStoreUpdateTest', function () { "salary": 300.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("age", "19") - let updatePromise = rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_ROLLBACK); - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - let resultSet = await rdbStore.query(predicates) - - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(1).assertEqual(id); - await expect("zhangsan").assertEqual(name); - await expect(18).assertEqual(age); - await expect(100.5).assertEqual(salary); - await expect(1).assertEqual(blobType[0]); - await expect(2).assertEqual(blobType[1]); - await expect(3).assertEqual(blobType[2]); - console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" - + salary + ", blobType=" + blobType); - - await expect(true).assertEqual(resultSet.goToNextRow()) - const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) - const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(3).assertEqual(id_1); - await expect("wangjing").assertEqual(name_1); - await expect(20).assertEqual(age_1); - await expect(300.5).assertEqual(salary_1); - await expect(7).assertEqual(blobType_1[0]); - await expect(8).assertEqual(blobType_1[1]); - await expect(9).assertEqual(blobType_1[2]); - console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" - + salary_1 + ", blobType=" + blobType_1); - await expect(false).assertEqual(resultSet.goToNextRow()) + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", "19") + let ret = await rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_ROLLBACK); + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); - resultSet.close() - resultSet = null - done(); - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0003 end *************"); - } - - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0003 end *************"); - }) + predicates = new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" + + salary + ", blobType=" + blobType); + + await expect(1).assertEqual(id); + await expect("zhangsan").assertEqual(name); + await expect(18).assertEqual(age); + await expect(100.5).assertEqual(salary); + await expect(1).assertEqual(blobType[0]); + await expect(2).assertEqual(blobType[1]); + await expect(3).assertEqual(blobType[2]); + + await expect(true).assertEqual(resultSet.goToNextRow()) + const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) + const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" + + salary_1 + ", blobType=" + blobType_1); + + await expect(3).assertEqual(id_1); + await expect("wangjing").assertEqual(name_1); + await expect(20).assertEqual(age_1); + await expect(300.5).assertEqual(salary_1); + await expect(7).assertEqual(blobType_1[0]); + await expect(8).assertEqual(blobType_1[1]); + await expect(9).assertEqual(blobType_1[2]); + await expect(false).assertEqual(resultSet.goToNextRow()) + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `insert2 failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } + console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0003 end *************"); }) /** @@ -739,9 +711,9 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_UpdateWithConflictResolution_0004 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdateWithConflictResolution0004', 0, async function (done) { + it('testRdbStoreUpdateWithConflictResolution0004', 0, async function () { console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0004 start *************"); - { + try { var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "id": 1, @@ -751,8 +723,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "id": 2, @@ -762,8 +737,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([7, 8, 9]) const valueBucket = { "id": 3, @@ -772,8 +750,8 @@ describe('rdbStoreUpdateTest', function () { "salary": 300.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("age", "19") + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", "19") rdbStore.beginTransaction() const valueBucketInsert = { @@ -785,57 +763,63 @@ describe('rdbStoreUpdateTest', function () { await rdbStore.insert("test", valueBucketInsert) try { await rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_ROLLBACK); - expect(null).assertFail(); + expect().assertFail() } catch (err) { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message); expect(14800000).assertEqual(err.code); } + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { - let predicates = await new data_relationalStore.RdbPredicates("test") + try { + let predicates = new data_relationalStore.RdbPredicates("test") let resultSet = await rdbStore.query(predicates) - - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(1).assertEqual(id); - await expect("zhangsan").assertEqual(name); - await expect(18).assertEqual(age); - await expect(100.5).assertEqual(salary); - await expect(1).assertEqual(blobType[0]); - await expect(2).assertEqual(blobType[1]); - await expect(3).assertEqual(blobType[2]); - console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" - + salary + ", blobType=" + blobType); - - await expect(true).assertEqual(resultSet.goToNextRow()) - const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) - const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(2).assertEqual(id_1); - await expect("lisi").assertEqual(name_1); - await expect(19).assertEqual(age_1); - await expect(200.5).assertEqual(salary_1); - await expect(4).assertEqual(blobType_1[0]); - await expect(5).assertEqual(blobType_1[1]); - await expect(6).assertEqual(blobType_1[2]); - console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" - + salary_1 + ", blobType=" + blobType_1); - await expect(false).assertEqual(resultSet.goToNextRow()) - - resultSet.close() - resultSet = null - done() - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0004 end *************"); + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" + + salary + ", blobType=" + blobType); + + await expect(1).assertEqual(id); + await expect("zhangsan").assertEqual(name); + await expect(18).assertEqual(age); + await expect(100.5).assertEqual(salary); + await expect(1).assertEqual(blobType[0]); + await expect(2).assertEqual(blobType[1]); + await expect(3).assertEqual(blobType[2]); + + await expect(true).assertEqual(resultSet.goToNextRow()) + const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) + const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" + + salary_1 + ", blobType=" + blobType_1); + + await expect(2).assertEqual(id_1); + await expect("lisi").assertEqual(name_1); + await expect(19).assertEqual(age_1); + await expect(200.5).assertEqual(salary_1); + await expect(4).assertEqual(blobType_1[0]); + await expect(5).assertEqual(blobType_1[1]); + await expect(6).assertEqual(blobType_1[2]); + await expect(false).assertEqual(resultSet.goToNextRow()) + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } + console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0004 end *************"); }) /** @@ -843,9 +827,9 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_UpdateWithConflictResolution_0005 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdateWithConflictResolution0005', 0, async function (done) { + it('testRdbStoreUpdateWithConflictResolution0005', 0, async function () { console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0005 start *************"); - { + try { var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "id": 1, @@ -855,8 +839,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert1 failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "id": 2, @@ -866,8 +853,11 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert2 failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([7, 8, 9]) const valueBucket = { "id": 3, @@ -876,68 +866,63 @@ describe('rdbStoreUpdateTest', function () { "salary": 300.5, "blobType": u8, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("age", "19") - let updatePromise = rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - let resultSet = await rdbStore.query(predicates) - - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(1).assertEqual(id); - await expect("zhangsan").assertEqual(name); - await expect(18).assertEqual(age); - await expect(100.5).assertEqual(salary); - await expect(1).assertEqual(blobType[0]); - await expect(2).assertEqual(blobType[1]); - await expect(3).assertEqual(blobType[2]); - console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" - + salary + ", blobType=" + blobType); - - await expect(true).assertEqual(resultSet.goToNextRow()) - const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) - const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(3).assertEqual(id_1); - await expect("wangjing").assertEqual(name_1); - await expect(20).assertEqual(age_1); - await expect(300.5).assertEqual(salary_1); - await expect(7).assertEqual(blobType_1[0]); - await expect(8).assertEqual(blobType_1[1]); - await expect(9).assertEqual(blobType_1[2]); - console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" - + salary_1 + ", blobType=" + blobType_1); - await expect(false).assertEqual(resultSet.goToNextRow()) - - resultSet.close() - resultSet = null - done() - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0005 end *************"); - } + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", "19") + let ret = await rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); + predicates = new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + try { - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0005 end *************"); - }) + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" + + salary + ", blobType=" + blobType); + + await expect(1).assertEqual(id); + await expect("zhangsan").assertEqual(name); + await expect(18).assertEqual(age); + await expect(100.5).assertEqual(salary); + await expect(1).assertEqual(blobType[0]); + await expect(2).assertEqual(blobType[1]); + await expect(3).assertEqual(blobType[2]); + + await expect(true).assertEqual(resultSet.goToNextRow()) + const id_1 = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name_1 = await resultSet.getString(resultSet.getColumnIndex("name")) + const age_1 = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary_1 = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType_1 = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id_1 + ", name=" + name_1 + ", age=" + age_1 + ", salary=" + + salary_1 + ", blobType=" + blobType_1); + + await expect(3).assertEqual(id_1); + await expect("wangjing").assertEqual(name_1); + await expect(20).assertEqual(age_1); + await expect(300.5).assertEqual(salary_1); + await expect(7).assertEqual(blobType_1[0]); + await expect(8).assertEqual(blobType_1[1]); + await expect(9).assertEqual(blobType_1[2]); + await expect(false).assertEqual(resultSet.goToNextRow()) + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } + console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0005 end *************"); }) - it('testRdbStoreUpdateWithConflictResolution0006', 0, async function (done) { + it('testRdbStoreUpdateWithConflictResolution0006', 0, async function () { console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0006 start *************"); - { + try { var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "id": 1, @@ -947,9 +932,12 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { var u8 = new Uint8Array([4, 5, 6]) const valueBucket = { "id": 2, @@ -959,53 +947,51 @@ describe('rdbStoreUpdateTest', function () { "blobType": u8, } await rdbStore.insert("test", valueBucket) + } catch (err) { + console.log(TAG + `insert2 failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } - { + try { const valueBucket = { "name": "zhangsan", "age": 20, "salary": 300.5, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("age", "19") - let updatePromise = rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); - updatePromise.then(async (ret) => { - await expect(1).assertEqual(ret); - await console.log(TAG + "update done: " + ret); - { - let predicates = await new data_relationalStore.RdbPredicates("test") - let resultSet = await rdbStore.query(predicates) - - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - await expect(2).assertEqual(id); - await expect("zhangsan").assertEqual(name); - await expect(20).assertEqual(age); - await expect(300.5).assertEqual(salary); - await expect(4).assertEqual(blobType[0]); - await expect(5).assertEqual(blobType[1]); - await expect(6).assertEqual(blobType[2]); - console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" - + salary + ", blobType=" + blobType); - - await expect(false).assertEqual(resultSet.goToNextRow()) - resultSet.close() - resultSet = null - done() - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0006 end *************"); - } - - }).catch((err) => { - console.log(TAG + "update error"); - expect(null).assertFail(); - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0006 end *************"); - }) + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", "19") + let ret = await rdbStore.update(valueBucket, predicates, data_relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + await expect(1).assertEqual(ret); + await console.log(TAG + "update done: " + ret); + predicates = new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + try { + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + console.log(TAG + "{id=" + id + ", name=" + name + ", age=" + age + ", salary=" + + salary + ", blobType=" + blobType); + + await expect(2).assertEqual(id); + await expect("zhangsan").assertEqual(name); + await expect(20).assertEqual(age); + await expect(300.5).assertEqual(salary); + await expect(4).assertEqual(blobType[0]); + await expect(5).assertEqual(blobType[1]); + await expect(6).assertEqual(blobType[2]); + + await expect(false).assertEqual(resultSet.goToNextRow()) + } finally { + resultSet.close() + resultSet = null + } + } catch (err) { + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) + expect().assertFail(); } + console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0006 end *************"); }) /** @@ -1013,7 +999,7 @@ describe('rdbStoreUpdateTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_UpdateWithConflictResolution_0007 * @tc.desc resultSet Update test */ - it('testRdbStoreUpdateWithConflictResolution0007', 0, async function (done) { + it('testRdbStoreUpdateWithConflictResolution0007', 0, async function () { console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0007 start *************"); try { const valueBucket = { @@ -1021,16 +1007,15 @@ describe('rdbStoreUpdateTest', function () { "age": 20, "salary": 300.5, } - let predicates = await new data_relationalStore.RdbPredicates("test") - await predicates.equalTo("age", "19") + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("age", "19") rdbStore.update(valueBucket, predicates, 6); - expect(null).assertFail(); + expect().assertFail() } catch (err) { - console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + console.log(TAG + `failed, err: ${JSON.stringify(err)}`) expect("401").assertEqual(err.code) - console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0007 end *************"); - done() } + console.log(TAG + "************* testRdbStoreUpdateWithConflictResolution0007 end *************"); }) console.log(TAG + "*************Unit Test End*************"); diff --git a/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp b/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp index 697c6501..5954dc81 100644 --- a/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp +++ b/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp @@ -77,7 +77,7 @@ HWTEST_F(DataAbilityPredicatesTest, DataAbilityPredicates_002, TestSize.Level1) EXPECT_EQ(false, predicates1->IsRawSelection()); predicates1->Clear(); - EXPECT_EQ(-1, predicates1->GetLimit()); + EXPECT_EQ(AbsPredicates::INIT_LIMIT_VALUE, predicates1->GetLimit()); EXPECT_EQ(true, predicates1->GetWhereClause().empty()); EXPECT_EQ(true, predicates1->GetWhereArgs().empty()); EXPECT_EQ(true, predicates1->GetOrder().empty()); @@ -213,7 +213,7 @@ HWTEST_F(DataAbilityPredicatesTest, DataAbilityPredicates_009, TestSize.Level1) EXPECT_EQ(newPredicates->GetWhereClause(), predicates->GetWhereClause()); EXPECT_EQ(newPredicates->GetWhereArgs(), predicates->GetWhereArgs()); EXPECT_EQ(newPredicates->GetOrder(), predicates->GetOrder()); - EXPECT_EQ(-1, newPredicates->GetLimit()); + EXPECT_EQ(AbsPredicates::INIT_LIMIT_VALUE, newPredicates->GetLimit()); outParcel.FlushBuffer(); } @@ -251,9 +251,10 @@ HWTEST_F(DataAbilityPredicatesTest, DataAbilityPredicates_010, TestSize.Level1) EXPECT_EQ(groupBy, predicates->GetGroup()); std::string order = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadString() : ""; EXPECT_EQ(order, predicates->GetOrder()); - int limit = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() : -1; + int limit = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() : AbsPredicates::INIT_LIMIT_VALUE; EXPECT_EQ(true, predicates->GetLimit() == limit); - int offset = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() : -1; + int offset = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() + : AbsPredicates::INIT_OFFSET_VALUE; EXPECT_EQ(offset, predicates->GetOffset()); predicates->Unmarshalling(coutParcel); @@ -294,9 +295,10 @@ HWTEST_F(DataAbilityPredicatesTest, DataAbilityPredicates_011, TestSize.Level1) EXPECT_EQ(groupBy, predicates->GetGroup()); std::string order = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadString() : ""; EXPECT_EQ(order, predicates->GetOrder()); - int limit = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() : -1; + int limit = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() : AbsPredicates::INIT_LIMIT_VALUE; EXPECT_EQ(limit, predicates->GetLimit()); - int offset = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() : -1; + int offset = outParcel.ReadInt32() != g_invalidObjectFlag ? outParcel.ReadInt32() + : AbsPredicates::INIT_OFFSET_VALUE; EXPECT_EQ(offset, predicates->GetOffset()); outParcel.FlushBuffer(); diff --git a/relational_store/test/native/rdb/BUILD.gn b/relational_store/test/native/rdb/BUILD.gn index 7b05128f..9a28a1e6 100644 --- a/relational_store/test/native/rdb/BUILD.gn +++ b/relational_store/test/native/rdb/BUILD.gn @@ -64,6 +64,7 @@ ohos_unittest("NativeRdbTest") { "unittest/rdb_transaction_test.cpp", "unittest/rdb_update_test.cpp", "unittest/rdb_upgrade_test.cpp", + "unittest/rdb_utils_test.cpp", "unittest/rdb_value_bucket_test.cpp", "unittest/rdb_wal_limit_test.cpp", ] diff --git a/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/rdbstore_fuzzer.cpp b/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/rdbstore_fuzzer.cpp index 73a29d50..3293e59f 100644 --- a/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/rdbstore_fuzzer.cpp +++ b/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/rdbstore_fuzzer.cpp @@ -195,11 +195,11 @@ void RdbQueryFuzz1(const uint8_t *data, size_t size) std::string vectorElem(data, data + size); AbsRdbPredicates predicates(tableName); - predicates.EqualTo("name", valName); + predicates.EqualTo("name", ValueObject(valName)); store->Query(predicates, {vectorElem}); predicates.Clear(); - predicates.NotEqualTo("name", valName); + predicates.NotEqualTo("name", ValueObject(valName)); store->Query(predicates, {vectorElem}); predicates.Clear(); @@ -239,43 +239,44 @@ void RdbQueryFuzz2(const uint8_t *data, size_t size) std::string tableName(data, data + size); std::string valName(data, data + size); - std::string valAge(data, data + size); - std::string valAgeChange(data, data + size); - std::string vectorElem(data, data + size); + ValueObject valAge(std::string(data, data + size)); + ValueObject valAgeChange(std::string(data, data + size)); + std::vector bindaArgs({std::string(data, data + size)}); + std::vector vectorElem({std::string(data, data + size)}); AbsRdbPredicates predicates(tableName); predicates.Clear(); predicates.Between("age", valAge, valAgeChange); - store->Query(predicates, {vectorElem}); + store->Query(predicates, bindaArgs); predicates.Clear(); predicates.NotBetween("age", valAge, valAgeChange); - store->Query(predicates, {vectorElem}); + store->Query(predicates, bindaArgs); predicates.Clear(); predicates.GreaterThan("age", valAge); - store->Query(predicates, {vectorElem}); + store->Query(predicates, bindaArgs); predicates.Clear(); predicates.LessThan("age", valAgeChange); - store->Query(predicates, {vectorElem}); + store->Query(predicates, bindaArgs); predicates.Clear(); predicates.GreaterThanOrEqualTo("age", valAge); - store->Query(predicates, {vectorElem}); + store->Query(predicates, bindaArgs); predicates.Clear(); predicates.LessThanOrEqualTo("age", valAgeChange); - store->Query(predicates, {vectorElem}); + store->Query(predicates, bindaArgs); predicates.Clear(); - predicates.In("name", {vectorElem}); - store->Query(predicates, {vectorElem}); + predicates.In("name", vectorElem); + store->Query(predicates, bindaArgs); predicates.Clear(); - predicates.NotIn("name", {vectorElem}); - store->Query(predicates, {vectorElem}); + predicates.NotIn("name", vectorElem); + store->Query(predicates, bindaArgs); store->ExecuteSql("DELETE FROM test"); } } diff --git a/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp b/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp index 266162f5..be02a4c7 100644 --- a/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp @@ -33,10 +33,8 @@ static std::shared_ptr rdbStore; class RdbStoreDistributedTest : public testing::Test { public: static void SetUpTestCase(); - static void TearDownTestCase() { - RdbHelper::DeleteRdbStore(RdbStoreDistributedTest::DRDB_PATH + RdbStoreDistributedTest::DRDB_NAME); - } - void SetUp() {} + static void TearDownTestCase(); + void SetUp(); void TearDown() {} void InsertValue(std::shared_ptr &store); @@ -54,26 +52,23 @@ class TestOpenCallback : public RdbOpenCallback { public: int OnCreate(RdbStore& store) override { - std::cout << "on create" << std::endl; std::string sql = "CREATE TABLE IF NOT EXISTS employee (" "id INTEGER PRIMARY KEY AUTOINCREMENT," "name TEXT NOT NULL," "age INTEGER," "salary REAL," "data BLOB)"; - std::cout << "create table return " << store.ExecuteSql(sql) << std::endl; + store.ExecuteSql(sql); return 0; } int OnOpen(RdbStore& store) override { - std::cout << "on open" << std::endl; return 0; } int OnUpgrade(RdbStore& store, int currentVersion, int targetVersion) override { - std::cout << "on upgrade" << std::endl; return 0; } }; @@ -85,7 +80,7 @@ void RdbStoreDistributedTest::SetUpTestCase() RdbHelper::DeleteRdbStore(path); int fd = open(path.c_str(), O_CREAT, S_IRWXU | S_IRWXG); if (fd < 0) { - std::cout << "open file failed" << std::endl; + return; } if (fd > 0) { close(fd); @@ -97,11 +92,18 @@ void RdbStoreDistributedTest::SetUpTestCase() config.SetName(RdbStoreDistributedTest::DRDB_NAME); TestOpenCallback callback; rdbStore = RdbHelper::GetRdbStore(config, 1, callback, errCode); - if (rdbStore == nullptr) { - std::cout << "get rdb store failed" << std::endl; - } else { - std::cout << "get rdb store success" << std::endl; - } + EXPECT_NE(nullptr, rdbStore); +} + +void RdbStoreDistributedTest::TearDownTestCase() +{ + RdbHelper::DeleteRdbStore(RdbStoreDistributedTest::DRDB_PATH + RdbStoreDistributedTest::DRDB_NAME); +} + +void RdbStoreDistributedTest::SetUp() +{ + EXPECT_NE(nullptr, rdbStore); + rdbStore->ExecuteSql("DELETE FROM test"); } void RdbStoreDistributedTest::InsertValue(std::shared_ptr &store) @@ -114,16 +116,15 @@ void RdbStoreDistributedTest::InsertValue(std::shared_ptr &store) values.PutInt("age", 18); // 18 age values.PutDouble("salary", 100.5); // 100.5 values.PutBlob("data", std::vector{ 1, 2, 3 }); - int ret = store->Insert(id, "employee", values); - EXPECT_EQ(ret, E_OK); + EXPECT_EQ(E_OK, store->Insert(id, "employee", values)); EXPECT_EQ(1, id); } void RdbStoreDistributedTest::CheckResultSet(std::shared_ptr &store) { std::shared_ptr resultSet = - store->QuerySql("SELECT * FROM employee WHERE name = ?", { "zhangsan" }); - EXPECT_NE(resultSet, nullptr); + store->QuerySql("SELECT * FROM employee WHERE name = ?", std::vector{ "zhangsan" }); + EXPECT_NE(nullptr, resultSet); int columnIndex; int intVal; @@ -131,33 +132,32 @@ void RdbStoreDistributedTest::CheckResultSet(std::shared_ptr &store) ColumnType columnType; int position; int ret = resultSet->GetRowIndex(position); - EXPECT_EQ(ret, E_OK); - EXPECT_EQ(position, -1); + EXPECT_EQ(E_OK, ret); + EXPECT_EQ(-1, position); ret = resultSet->GetColumnType(0, columnType); - EXPECT_EQ(ret, E_INVALID_STATEMENT); + EXPECT_EQ(E_INVALID_STATEMENT, ret); ret = resultSet->GoToFirstRow(); - EXPECT_EQ(ret, E_OK); + EXPECT_EQ(E_OK, ret); ret = resultSet->GetColumnIndex("id", columnIndex); - EXPECT_EQ(ret, E_OK); - EXPECT_EQ(columnIndex, 0); + EXPECT_EQ(E_OK, ret); + EXPECT_EQ(0, columnIndex); ret = resultSet->GetColumnType(columnIndex, columnType); - EXPECT_EQ(ret, E_OK); + EXPECT_EQ(E_OK, ret); EXPECT_EQ(columnType, ColumnType::TYPE_INTEGER); ret = resultSet->GetInt(columnIndex, intVal); - EXPECT_EQ(ret, E_OK); + EXPECT_EQ(E_OK, ret); EXPECT_EQ(1, intVal); ret = resultSet->GetColumnIndex("name", columnIndex); - EXPECT_EQ(ret, E_OK); + EXPECT_EQ(E_OK, ret); ret = resultSet->GetColumnType(columnIndex, columnType); - EXPECT_EQ(ret, E_OK); - EXPECT_EQ(columnType, ColumnType::TYPE_STRING); + EXPECT_EQ(E_OK, ret); + EXPECT_EQ(ColumnType::TYPE_STRING, columnType); ret = resultSet->GetString(columnIndex, strVal); - EXPECT_EQ(ret, E_OK); - std::cout << "strVal=" << strVal << std::endl; + EXPECT_EQ(E_OK, ret); EXPECT_EQ("zhangsan", strVal); } @@ -168,7 +168,33 @@ void RdbStoreDistributedTest::CheckResultSet(std::shared_ptr &store) */ HWTEST_F(RdbStoreDistributedTest, RdbStore_Distributed_001, TestSize.Level1) { - EXPECT_NE(rdbStore, nullptr) << "get rdb store failed"; + EXPECT_NE(nullptr, rdbStore); InsertValue(rdbStore); CheckResultSet(rdbStore); } + +/** + * @tc.name: RdbStore_Distributed_Test_002 + * @tc.desc: Abnormal testCase of ObtainDistributedTableName, if networkId is "" + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreDistributedTest, RdbStore_Distributed_002, TestSize.Level2) +{ + EXPECT_NE(nullptr, rdbStore); + int errCode; + EXPECT_EQ("", rdbStore->ObtainDistributedTableName("", "employee", errCode)); + EXPECT_EQ(-1, errCode); +} + +/** + * @tc.name: RdbStore_Distributed_Test_003 + * @tc.desc: Abnormal testCase of ObtainDistributedTableName, if networkId is invalid + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreDistributedTest, RdbStore_Distributed_003, TestSize.Level2) +{ + EXPECT_NE(nullptr, rdbStore); + int errCode; + EXPECT_EQ("", rdbStore->ObtainDistributedTableName("123456", "employee", errCode)); + EXPECT_EQ(-1, errCode); +} diff --git a/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp b/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp index 27825700..355772c9 100644 --- a/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp @@ -667,3 +667,29 @@ HWTEST_F(RdbStoreInsertTest, RdbStore_InsertWithConflictResolution_006_007, Test ret = resultSet->Close(); EXPECT_EQ(ret, E_OK); } + +/** + * @tc.name: RdbStore_InsertWithConflictResolution_008 + * @tc.desc: Abnormal testCase of InsertWithConflictResolution, if conflictResolution is invalid + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreInsertTest, RdbStore_InsertWithConflictResolution_008, TestSize.Level1) +{ + std::shared_ptr &store = RdbStoreInsertTest::store; + + int64_t id; + ValuesBucket values; + + values.PutInt("id", 1); + values.PutInt("age", 18); + int ret = store->InsertWithConflictResolution(id, "test", values, static_cast(6)); + EXPECT_EQ(E_INVALID_CONFLICT_FLAG, ret); + EXPECT_EQ(0, id); + + values.Clear(); + values.PutInt("id", 1); + values.PutInt("age", 18); + ret = store->InsertWithConflictResolution(id, "test", values, static_cast(-1)); + EXPECT_EQ(E_INVALID_CONFLICT_FLAG, ret); + EXPECT_EQ(0, id); +} \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp b/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp index 00c56584..0c4db7a2 100644 --- a/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp @@ -25,7 +25,6 @@ #include "rdb_helper.h" using namespace testing::ext; -using namespace OHOS::Rdb; using namespace OHOS::NativeRdb; class RdbOpenCallbackTest : public testing::Test { diff --git a/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp b/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp index 14254fde..394e7cd7 100644 --- a/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp @@ -690,6 +690,14 @@ void RdbStorePredicateTest::BasicDataTypeTest(RdbPredicates predicates1) EXPECT_EQ(E_OK, allDataTypes8->GoToFirstRow()); allDataTypes8->GetInt(0, valueInt); EXPECT_EQ(3, valueInt); + + predicates1.Clear(); + std::vector blob = {1, 2, 3}; + predicates1.EqualTo("blobValue", blob); + std::shared_ptr allDataTypes9 = RdbStorePredicateTest::store->Query(predicates1, columns); + int count = 0; + allDataTypes9->GetRowCount(count); + EXPECT_EQ(3, count); } int RdbStorePredicateTest::ResultSize(std::shared_ptr &resultSet) @@ -1635,7 +1643,7 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_ToString_025, TestSize.Level1) ->Limit(2); std::string toString = predicates1.ToString(); std::string result = "TableName = AllDataType, {WhereClause:stringValue = ? AND ( integerValue = ? OR " - "integerValue = ? ) , whereArgs:{ABCDEFGHIJKLMN, 1, 2147483647, }, order:integerValue " + "integerValue = ? ) , bindArgs:{ABCDEFGHIJKLMN, 1, 2147483647, }, order:integerValue " "DESC , group:, index:, limit:2, offset:-2147483648, distinct:0, isNeedAnd:1, isSorted:1}"; EXPECT_EQ(result, toString); } @@ -2095,7 +2103,7 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_IndexedBy_002, TestSize.Level1) HWTEST_F(RdbStorePredicateTest, RdbStore_In_001, TestSize.Level1) { RdbPredicates predicates("AllDataType"); - predicates.In("", {"1", "3"}); + predicates.In("", std::vector{ "1", "3" }); std::vector columns; std::shared_ptr allDataTypes = RdbStorePredicateTest::store->Query(predicates, columns); @@ -2111,7 +2119,7 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_In_001, TestSize.Level1) HWTEST_F(RdbStorePredicateTest, RdbStore_In_002, TestSize.Level1) { RdbPredicates predicates("AllDataType"); - predicates.In("id", {}); + predicates.In("id", std::vector{}); std::vector columns; std::shared_ptr allDataTypes = RdbStorePredicateTest::store->Query(predicates, columns); @@ -2146,9 +2154,9 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_GetStatement_GetBnidArgs_001, TestSize. RdbPredicates predicates("AllDataType"); predicates.EqualTo("stringValue", "ABCDEFGHIJKLMN") ->BeginWrap() - ->EqualTo("integerValue", "1") + ->EqualTo("integerValue", 1) ->Or() - ->EqualTo("integerValue", std::to_string(INT_MAX)) + ->EqualTo("integerValue", INT_MAX) ->EndWrap() ->OrderByDesc("integerValue") ->Limit(-1, -1); @@ -2160,8 +2168,30 @@ HWTEST_F(RdbStorePredicateTest, RdbStore_GetStatement_GetBnidArgs_001, TestSize. EXPECT_EQ(2, count); std::string statement = predicates.GetStatement(); - std::vector bindArgs = predicates.GetBindArgs(); + std::vector bindArgs = predicates.GetBindArgs(); EXPECT_EQ(statement, " WHERE stringValue = ? AND ( integerValue = ? OR integerValue = ? ) ORDER BY " "integerValue DESC LIMIT -1 OFFSET -1"); - EXPECT_EQ(bindArgs[0], "ABCDEFGHIJKLMN"); + EXPECT_EQ(bindArgs.size(), 3); +} + +/* * + * @tc.name: RdbStore_GetStatement_GetBindArgs_002 + * @tc.desc: Normal testCase of RdbPredicates for GetStatement and GetBindArgs method + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_GetStatement_GetBnidArgs_002, TestSize.Level1) +{ + RdbPredicates predicates("AllDataType"); + predicates.SetWhereClause("integerValue = 1 and "); + predicates.EqualTo("stringValue", "ABCDEFGHIJKLMN"); + + std::string statement = predicates.GetStatement(); + EXPECT_EQ(statement, " WHERE integerValue = 1 and stringValue = ? "); + + std::vector columns; + int count = 0; + std::shared_ptr resultSet = RdbStorePredicateTest::store->Query(predicates, columns); + resultSet->GetRowCount(count); + EXPECT_EQ(1, count); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp b/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp index 58bc4bbe..bff6ecb0 100644 --- a/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp @@ -1374,7 +1374,7 @@ HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_030, TestSize.Le * @tc.desc: Abnormal testcase of SqliteSharedResultSet for Close, if close resultSet twice * @tc.type: FUNC */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_031, TestSize.Level1) +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_031, TestSize.Level2) { GenerateDefaultTable(); std::vector selectionArgs; @@ -1382,12 +1382,43 @@ HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_031, TestSize.Le RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(resultSet, nullptr); - int ret = resultSet->Close(); - EXPECT_EQ(ret, E_OK); + EXPECT_EQ(E_OK, resultSet->Close()); + EXPECT_EQ(true, resultSet->IsClosed()); + EXPECT_EQ(E_STEP_RESULT_CLOSED, resultSet->GoToLastRow()); - bool isClosed = resultSet->IsClosed(); - EXPECT_EQ(isClosed, true); + bool isExpectResult = true; + EXPECT_EQ(E_STEP_RESULT_CLOSED, resultSet->IsAtLastRow(isExpectResult)); + EXPECT_NE(false, isExpectResult); - ret = resultSet->Close(); - EXPECT_EQ(ret, E_OK); -} \ No newline at end of file + EXPECT_EQ(E_STEP_RESULT_CLOSED, resultSet->IsEnded(isExpectResult)); + EXPECT_NE(false, isExpectResult); + + int columnCount; + EXPECT_EQ(E_STEP_RESULT_CLOSED, resultSet->GetColumnCount(columnCount)); + + std::string columnName; + EXPECT_EQ(E_STEP_RESULT_CLOSED, resultSet->GetColumnName(1, columnName)); + + EXPECT_EQ(E_OK, resultSet->Close()); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_032 + * @tc.desc: Normal testcase of SqliteSharedResultSet for GetRow + * @tc.type: FUNC + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_032, TestSize.Level1) +{ + GenerateAssetsTable(); + std::vector selectionArgs; + std::shared_ptr resultSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(resultSet, nullptr); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + int iRet = E_ERROR; + RowEntity rowEntity; + iRet = resultSet->GetRow(rowEntity); + EXPECT_EQ(E_OK, iRet); +} diff --git a/relational_store/test/native/rdb/unittest/rdb_step_result_get_row_test.cpp b/relational_store/test/native/rdb/unittest/rdb_step_result_get_row_test.cpp index 452492e5..7ceb159e 100644 --- a/relational_store/test/native/rdb/unittest/rdb_step_result_get_row_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_step_result_get_row_test.cpp @@ -250,4 +250,62 @@ HWTEST_F(RdbStepResultSetGetRowTest, RdbStore_StepResultSet_GetRow_004, TestSize EXPECT_EQ("", data1ValueByIndex); resultSet->Close(); -} \ No newline at end of file +} + +/* * + * @tc.name: RdbStore_StepResultSet_GetRow_005 + * @tc.desc: Abnormal testCase of GetRow for rowEntity, if params of Get() is invalid + * @tc.type: FUNC + */ +HWTEST_F(RdbStepResultSetGetRowTest, RdbStore_StepResultSet_GetRow_005, TestSize.Level2) +{ + ValuesBucket valuesBucket; + valuesBucket.PutString("data1", "keep"); + valuesBucket.PutInt("data2", 10); + + int64_t rowId; + EXPECT_EQ(E_OK, RdbStepResultSetGetRowTest::store->Insert(rowId, "test", valuesBucket)); + EXPECT_EQ(1, rowId); + + std::shared_ptr resultSet = + RdbStepResultSetGetRowTest::store->QueryByStep("SELECT data1, data2 FROM test"); + EXPECT_NE(nullptr, resultSet); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + RowEntity rowEntity; + EXPECT_EQ(E_OK, resultSet->GetRow(rowEntity)); + + EXPECT_EQ(ValueObjectType::TYPE_NULL, rowEntity.Get("data3").GetType()); + EXPECT_EQ(ValueObjectType::TYPE_NULL, rowEntity.Get(-1).GetType()); + EXPECT_EQ(ValueObjectType::TYPE_NULL, rowEntity.Get(2).GetType()); + + resultSet->Close(); +} + +/* * + * @tc.name: RdbStore_StepResultSet_GetRow_006 + * @tc.desc: Abnormal testCase of GetRow for rowEntity, if close resultSet before GetRow + * @tc.type: FUNC + */ +HWTEST_F(RdbStepResultSetGetRowTest, RdbStore_StepResultSet_GetRow_006, TestSize.Level2) +{ + ValuesBucket valuesBucket; + valuesBucket.PutString("data1", "keep"); + valuesBucket.PutInt("data2", 10); + + int64_t rowId; + EXPECT_EQ(E_OK, RdbStepResultSetGetRowTest::store->Insert(rowId, "test", valuesBucket)); + EXPECT_EQ(1, rowId); + + std::shared_ptr resultSet = + RdbStepResultSetGetRowTest::store->QueryByStep("SELECT data1, data2 FROM test"); + EXPECT_NE(nullptr, resultSet); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + EXPECT_EQ(E_OK, resultSet->Close()); + + RowEntity rowEntity; + EXPECT_EQ(E_STEP_RESULT_CLOSED, resultSet->GetRow(rowEntity)); +} diff --git a/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp b/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp index a6182930..20ac6100 100644 --- a/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp @@ -22,6 +22,7 @@ #include "rdb_errno.h" #include "rdb_helper.h" #include "rdb_open_callback.h" +#include "sqlite_sql_builder.h" using namespace testing::ext; using namespace OHOS::NativeRdb; @@ -1773,4 +1774,18 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep016, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->Close()); EXPECT_EQ(true, resultSet->IsClosed()); +} + +/* * + * @tc.name: testSqlStep017 + * @tc.desc: Abnormal testcase for build query string + * @tc.type: FUNC + */ +HWTEST_F(RdbStepResultSetTest, testSqlStep017, TestSize.Level1) +{ + std::vector columns = {"data1", "data2"}; + + std::string outSql; + int errCode = SqliteSqlBuilder::BuildQueryString(false, "", columns, "", "", "", "", 0, 0, outSql); + EXPECT_EQ(E_EMPTY_TABLE_NAME, errCode); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp index 577a3e79..82bcd1cc 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp @@ -25,7 +25,6 @@ #include "unistd.h" using namespace testing::ext; -using namespace OHOS::Rdb; using namespace OHOS::NativeRdb; class RdbStoreConfigTest : public testing::Test { diff --git a/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp b/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp index 68654de5..bec8085b 100644 --- a/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp @@ -691,4 +691,37 @@ HWTEST_F(RdbTransactionTest, RdbStore_BatchInsert_003, TestSize.Level1) } resultSet->Close(); EXPECT_EQ(100, number); +} + +/** + * @tc.name: RdbStore_BatchInsert_004 + * @tc.desc: Abnormal testCase of transaction for batchInsert, if batchInsert in transaction + * @tc.type: FUNC + */ +HWTEST_F(RdbTransactionTest, RdbStore_BatchInsert_004, TestSize.Level1) +{ + std::shared_ptr &store = RdbTransactionTest::store; + store->ExecuteSql("delete from test"); + + int id = 0; + ValuesBucket values; + std::vector valuesBuckets; + + for (int i = 0; i < 10; i++) { + values.Clear(); + values.PutInt("id", id + i); + values.PutString("name", "zhangsan"); + valuesBuckets.push_back(values); + } + + int error = store->BeginTransaction(); + EXPECT_EQ(E_OK, error); + + int64_t number = 0; + error = store->BatchInsert(number, "test", valuesBuckets); + EXPECT_EQ(E_TRANSACTION_IN_EXECUTE, error); + EXPECT_EQ(0, number); + + error = store->Commit(); + EXPECT_EQ(E_OK, error); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_update_test.cpp b/relational_store/test/native/rdb/unittest/rdb_update_test.cpp index 6df40c4f..e01fd8cc 100644 --- a/relational_store/test/native/rdb/unittest/rdb_update_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_update_test.cpp @@ -22,6 +22,7 @@ #include "rdb_errno.h" #include "rdb_helper.h" #include "rdb_open_callback.h" +#include "sqlite_sql_builder.h" using namespace testing::ext; using namespace OHOS::NativeRdb; @@ -1038,3 +1039,25 @@ HWTEST_F(RdbStoreUpdateTest, RdbStore_UpdateWithConflictResolution_006, TestSize ret = resultSet->Close(); EXPECT_EQ(ret, E_OK); } + +/** + * @tc.name: RdbStore_UpdateSqlBuilder_001 + * @tc.desc: test RdbStore UpdateSqlBuilder + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreUpdateTest, RdbStore_UpdateSqlBuilder_001, TestSize.Level1) +{ + ValuesBucket values; + values.PutString("name", std::string("zhangsan")); + values.PutInt("age", 20); + values.PutDouble("salary", 300.5); + + std::vector bindArgs; + std::string updateSql = SqliteSqlBuilder::BuildUpdateString(values, "test", std::vector{ "19" }, + "", "age = ?", "", "", INT_MIN, INT_MIN, bindArgs, ConflictResolution::ON_CONFLICT_NONE); + EXPECT_EQ(updateSql, "UPDATE test SET age=?,name=?,salary=? WHERE age = ?"); + + updateSql = SqliteSqlBuilder::BuildUpdateString(values, "test", std::vector{}, + "", "", "", "", INT_MIN, INT_MIN, bindArgs, ConflictResolution::ON_CONFLICT_NONE); + EXPECT_EQ(updateSql, "UPDATE test SET age=?,name=?,salary=?"); +} diff --git a/kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.h b/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp similarity index 34% rename from kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.h rename to relational_store/test/native/rdb/unittest/rdb_utils_test.cpp index 1dc415d6..6a845610 100644 --- a/kv_store/test/distributedtest/single_kvstore_client/distributed_test_helper.h +++ b/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp @@ -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,34 +13,60 @@ * limitations under the License. */ -#ifndef DISTRIBUTED_TEST_HELPER_INCLUDE_H -#define DISTRIBUTED_TEST_HELPER_INCLUDE_H - #include -#include -#include -#include -#include -#include "distributed_kv_data_manager.h" -#include "types.h" -#include "distributed_major.h" -#include "refbase.h" -#include "hilog/log.h" - -class DistributedTestHelper : public OHOS::DistributeSystemTest::DistributeTest { + +#include + +#include "sqlite_utils.h" +#include "string_utils.h" + +using namespace testing::ext; +using namespace OHOS::NativeRdb; + +class RdbUtilsTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp() override; - void TearDown() override; - void TestBody() override; - - OHOS::DistributedKv::Status GetRemote(const OHOS::DistributedKv::Key &key, - OHOS::DistributedKv::Value &value); - OHOS::DistributedKv::Status PutRemote(const OHOS::DistributedKv::Key &key, - const OHOS::DistributedKv::Value &value); - OHOS::DistributedKv::Status DeleteRemote(const OHOS::DistributedKv::Key &key); - OHOS::DistributedKv::Status RemoveDeviceDataRemote(); - OHOS::DistributedKv::Status SyncRemote(OHOS::DistributedKv::SyncMode mode, uint32_t delay = 0); + void SetUp(void) {}; + void TearDown(void) {}; }; -#endif // DISTRIBUTED_TEST_HELPER_INCLUDE_H \ No newline at end of file + +void RdbUtilsTest::SetUpTestCase(void) +{ +} + +void RdbUtilsTest::TearDownTestCase(void) +{ +} + +/** + * @tc.name: RdbStore_SqliteUtils_001 + * @tc.desc: Normal testCase of sqlite_utils for IsSpecial, if sqlType is special + * @tc.type: FUNC + */ +HWTEST_F(RdbUtilsTest, RdbStore_SqliteUtils_001, TestSize.Level1) +{ + EXPECT_EQ(true, SqliteUtils::IsSpecial(5)); + EXPECT_EQ(true, SqliteUtils::IsSpecial(6)); + EXPECT_EQ(true, SqliteUtils::IsSpecial(7)); +} + +/** + * @tc.name: RdbStore_SqliteUtils_002 + * @tc.desc: Abnormal testCase of sqlite_utils for Anonymous, if len(srcFile) < HEAD_SIZE + * @tc.type: FUNC + */ +HWTEST_F(RdbUtilsTest, RdbStore_SqliteUtils_002, TestSize.Level2) +{ + EXPECT_EQ("******", SqliteUtils::Anonymous("ac")); +} + +/** + * @tc.name: RdbStore_SqliteUtils_003 + * @tc.desc: Abnormal testCase of sqlite_utils for Anonymous, if len(srcFile) < MIN_SIZE + * @tc.type: FUNC + */ +HWTEST_F(RdbUtilsTest, RdbStore_SqliteUtils_003, TestSize.Level2) +{ + EXPECT_EQ("abc***", SqliteUtils::Anonymous("abc/def")); +} diff --git a/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp b/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp index 2e13f884..4ef8fc6b 100644 --- a/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp @@ -24,6 +24,7 @@ #include "sqlite_global_config.h" #include "value_object.h" #include "values_bucket.h" +#include "rdb_errno.h" using namespace testing::ext; using namespace OHOS; @@ -256,6 +257,47 @@ HWTEST_F(ValuesBucketTest, Values_Object_001, TestSize.Level1) EXPECT_EQ(valueVectorUint8, retVectorUint8); } +/** + * @tc.name: Values_Object_002 + * @tc.desc: test ValuesObject for Get + * @tc.type: FUNC + */ +HWTEST_F(ValuesBucketTest, Values_Object_002, TestSize.Level1) +{ + ValueObject val; + int valueInt; + int errCode = val.GetInt(valueInt); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); + + int64_t valueInt64; + errCode = val.GetLong(valueInt64); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); + + double valueDouble; + errCode = val.GetDouble(valueDouble); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); + + bool valueBool = false; + errCode = val.GetBool(valueBool); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); + + std::string valueString; + errCode = val.GetString(valueString); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); + + std::vector valueVectorUint8; + errCode = val.GetBlob(valueVectorUint8); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); + + AssetValue asset; + errCode = val.GetAsset(asset); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); + + auto assets = ValueObject::Assets({ asset }); + errCode = val.GetAssets(assets); + EXPECT_EQ(E_INVALID_OBJECT_TYPE, errCode); +} + /** * @tc.name: Convert from subset * @tc.desc: test ValuesObject operator @@ -333,4 +375,42 @@ HWTEST_F(ValuesBucketTest, Convert_To_Subset, TestSize.Level1) RawDataParser::Convert(input, output); nil = std::get_if(&output); EXPECT_TRUE(nil != nullptr); +} + +/** + * @tc.name: Explicit conversion + * @tc.desc: test ValuesObject operator + * @tc.type: FUNC + */ +HWTEST_F(ValuesBucketTest, Explicit_Conversion, TestSize.Level1) +{ + ValueObject valueObject; + auto blob = std::vector(10, 'm'); + valueObject = ValueObject(blob); + auto transformedBlob = ValueObject::Blob(valueObject); + ASSERT_EQ(transformedBlob.size(), 10); + + AssetValue asset{ .version = 0, .name = "123", .uri = "my test path", .createTime = "12", .modifyTime = "12"}; + valueObject = ValueObject(asset); + auto transformedAsset = ValueObject::Asset(valueObject); + ASSERT_EQ(transformedAsset.version, asset.version); + ASSERT_EQ(transformedAsset.name, asset.name); + ASSERT_EQ(transformedAsset.uri, asset.uri); + ASSERT_EQ(transformedAsset.createTime, asset.createTime); + + auto assets = ValueObject::Assets({ asset }); + valueObject = ValueObject(assets); + auto transformedAssets = ValueObject::Assets(valueObject); + ASSERT_EQ(transformedAssets.size(), 1); + auto first = transformedAssets.begin(); + ASSERT_EQ(first->version, asset.version); + ASSERT_EQ(first->name, asset.name); + ASSERT_EQ(first->uri, asset.uri); + ASSERT_EQ(first->createTime, asset.createTime); + + using Type = ValueObject::Type; + Type input = asset; + valueObject = ValueObject(input); + auto transformedType = ValueObject::Type(valueObject); + ASSERT_EQ(transformedType.index(), ValueObject::TYPE_ASSET); } \ No newline at end of file diff --git a/relational_store/test/ndk/unittest/rdb_cursor_test.cpp b/relational_store/test/ndk/unittest/rdb_cursor_test.cpp index 65ab58c9..c0e152f1 100644 --- a/relational_store/test/ndk/unittest/rdb_cursor_test.cpp +++ b/relational_store/test/ndk/unittest/rdb_cursor_test.cpp @@ -20,11 +20,12 @@ #include #include "common.h" #include "relational_store.h" +#include "relational_store_error_code.h" using namespace testing::ext; using namespace OHOS::NativeRdb; -class RdbNdkCursorTest : public testing::Test { +class RdbNativeCursorTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -44,8 +45,8 @@ public: }; OH_Rdb_Store *cursorTestRdbStore_; -OH_Rdb_Config RdbNdkCursorTest::config_ = {0}; -void RdbNdkCursorTest::SetUpTestCase(void) +OH_Rdb_Config RdbNativeCursorTest::config_ = {0}; +void RdbNativeCursorTest::SetUpTestCase(void) { InitRdbConfig(); mkdir(config_.dataBaseDir, 0770); @@ -90,27 +91,27 @@ void RdbNdkCursorTest::SetUpTestCase(void) valueBucket->destroy(valueBucket); } -void RdbNdkCursorTest::TearDownTestCase(void) +void RdbNativeCursorTest::TearDownTestCase(void) { delete cursorTestRdbStore_; cursorTestRdbStore_ = NULL; OH_Rdb_DeleteStore(&config_); } -void RdbNdkCursorTest::SetUp(void) +void RdbNativeCursorTest::SetUp(void) { } -void RdbNdkCursorTest::TearDown(void) +void RdbNativeCursorTest::TearDown(void) { } /** - * @tc.name: RDB_NDK_cursor_test_001 - * @tc.desc: Normal testCase of NDK cursor for GetColumnType. + * @tc.name: RDB_Native_cursor_test_001 + * @tc.desc: Normal testCase of cursor for GetColumnType. * @tc.type: FUNC */ -HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_001, TestSize.Level1) +HWTEST_F(RdbNativeCursorTest, RDB_Native_cursor_test_001, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -123,7 +124,7 @@ HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_001, TestSize.Level1) errCode = cursor->getColumnType(cursor, 0, &type); EXPECT_EQ(type, OH_ColumnType::TYPE_INT64); - errCode = cursor->getColumnType(cursor, 1, &type);; + errCode = cursor->getColumnType(cursor, 1, &type); EXPECT_EQ(type, OH_ColumnType::TYPE_TEXT); errCode = cursor->getColumnType(cursor, 2, &type); @@ -138,16 +139,23 @@ HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_001, TestSize.Level1) errCode = cursor->getColumnType(cursor, 5, &type); EXPECT_EQ(type, OH_ColumnType::TYPE_TEXT); + errCode = cursor->getColumnType(nullptr, 5, &type); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getColumnType(cursor, -1, &type); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getColumnType(cursor, 5, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + predicates->destroy(predicates); cursor->destroy(cursor); } /** - * @tc.name: RDB_NDK_cursor_test_002 - * @tc.desc: Normal testCase of NDK cursor for GetColumnIndex. + * @tc.name: RDB_Native_cursor_test_002 + * @tc.desc: Normal testCase of cursor for GetColumnIndex. * @tc.type: FUNC */ -HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_002, TestSize.Level1) +HWTEST_F(RdbNativeCursorTest, RDB_Native_cursor_test_002, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -171,16 +179,23 @@ HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_002, TestSize.Level1) errCode = cursor->getColumnIndex(cursor, "data5", &columnIndex); EXPECT_EQ(columnIndex, 5); + errCode = cursor->getColumnIndex(nullptr, "data5", &columnIndex); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getColumnIndex(cursor, nullptr, &columnIndex); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getColumnIndex(cursor, "data5", nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + predicates->destroy(predicates); cursor->destroy(cursor); } /** - * @tc.name: RDB_NDK_cursor_test_003 - * @tc.desc: Normal testCase of NDK cursor for GetColumnName. + * @tc.name: RDB_Native_cursor_test_003 + * @tc.desc: Normal testCase of cursor for GetColumnName. * @tc.type: FUNC */ -HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_003, TestSize.Level1) +HWTEST_F(RdbNativeCursorTest, RDB_Native_cursor_test_003, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -204,16 +219,23 @@ HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_003, TestSize.Level1) errCode = cursor->getColumnName(cursor, 5, name, 6); EXPECT_EQ(strcmp(name, "data5"), 0); + errCode = cursor->getColumnName(nullptr, 5, name, 6); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getColumnName(cursor, 5, nullptr, 6); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getColumnName(cursor, 5, name, 0); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + predicates->destroy(predicates); cursor->destroy(cursor); } /** - * @tc.name: RDB_NDK_cursor_test_004 - * @tc.desc: Normal testCase of NDK cursor for Getxxx. + * @tc.name: RDB_Native_cursor_test_004 + * @tc.desc: Normal testCase of cursor for Getxxx. * @tc.type: FUNC */ -HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_004, TestSize.Level1) +HWTEST_F(RdbNativeCursorTest, RDB_Native_cursor_test_004, TestSize.Level1) { OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -269,6 +291,82 @@ HWTEST_F(RdbNdkCursorTest, RDB_NDK_cursor_test_004, TestSize.Level1) cursor->isNull(cursor, 3, &isNull); EXPECT_EQ(isNull, true); + predicates->destroy(predicates); + cursor->destroy(cursor); +} + +/** + * @tc.name: RDB_Native_cursor_test_005 + * @tc.desc: Normal testCase of cursor for anomalous branch. + * @tc.type: FUNC + */ +HWTEST_F(RdbNativeCursorTest, RDB_Native_cursor_test_005, TestSize.Level1) +{ + OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); + + const char *columnNames[] = {"data1", "data2", "data3", "data4"}; + int len = sizeof(columnNames) / sizeof(columnNames[0]); + OH_Cursor *cursor = OH_Rdb_Query(cursorTestRdbStore_, predicates, columnNames, len); + EXPECT_NE(cursor, NULL); + + int rowCount = 0; + int errCode = cursor->getRowCount(nullptr, &rowCount); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getRowCount(cursor, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + int columnCount = 0; + errCode = cursor->getColumnCount(nullptr, &columnCount); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getColumnCount(cursor, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + errCode = cursor->goToNextRow(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + size_t size = 0; + errCode = cursor->getSize(nullptr, 0, &size); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getSize(cursor, 0, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + char data1Value[size + 1]; + errCode = cursor->getText(nullptr, 0, data1Value, size + 1); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getText(cursor, 0, nullptr, size + 1); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getText(cursor, 0, data1Value, 0); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + int64_t data2Value; + errCode = cursor->getInt64(nullptr, 1, &data2Value); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getInt64(cursor, 1, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + double data3Value; + errCode = cursor->getReal(nullptr, 2, &data3Value); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getReal(cursor, 2, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + unsigned char data4Value[size]; + errCode = cursor->getBlob(nullptr, 3, data4Value, size); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getBlob(cursor, 3, nullptr, size); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->getBlob(cursor, 3, data4Value, 0); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + bool isNull = false; + errCode = cursor->isNull(nullptr, 3, &isNull); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = cursor->isNull(cursor, 3, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + errCode = cursor->destroy(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + predicates->destroy(predicates); cursor->destroy(cursor); } \ No newline at end of file diff --git a/relational_store/test/ndk/unittest/rdb_predicates_test.cpp b/relational_store/test/ndk/unittest/rdb_predicates_test.cpp index 3bb5a643..289e1ec3 100644 --- a/relational_store/test/ndk/unittest/rdb_predicates_test.cpp +++ b/relational_store/test/ndk/unittest/rdb_predicates_test.cpp @@ -21,11 +21,12 @@ #include "common.h" #include "relational_store.h" #include "oh_value_object.h" +#include "relational_store_error_code.h" using namespace testing::ext; using namespace OHOS::NativeRdb; -class RdbNdkPredicatesTest : public testing::Test { +class RdbNativePredicatesTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -45,8 +46,8 @@ public: }; OH_Rdb_Store *predicatesTestRdbStore_; -OH_Rdb_Config RdbNdkPredicatesTest::config_ = {0}; -void RdbNdkPredicatesTest::SetUpTestCase(void) +OH_Rdb_Config RdbNativePredicatesTest::config_ = {0}; +void RdbNativePredicatesTest::SetUpTestCase(void) { InitRdbConfig(); mkdir(config_.dataBaseDir, 0770); @@ -92,27 +93,27 @@ void RdbNdkPredicatesTest::SetUpTestCase(void) valueBucket->destroy(valueBucket); } -void RdbNdkPredicatesTest::TearDownTestCase(void) +void RdbNativePredicatesTest::TearDownTestCase(void) { delete predicatesTestRdbStore_; predicatesTestRdbStore_ = NULL; OH_Rdb_DeleteStore(&config_); } -void RdbNdkPredicatesTest::SetUp(void) +void RdbNativePredicatesTest::SetUp(void) { } -void RdbNdkPredicatesTest::TearDown(void) +void RdbNativePredicatesTest::TearDown(void) { } /** - * @tc.name: RDB_NDK_predicates_test_001 - * @tc.desc: Normal testCase of NDK Predicates for EqualTo、AndOR、beginWrap and endWrap + * @tc.name: RDB_Native_predicates_test_001 + * @tc.desc: Normal testCase of Predicates for EqualTo、AndOR、beginWrap and endWrap * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_001, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_001, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -137,11 +138,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_001, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_002 - * @tc.desc: Normal testCase of NDK Predicates for NotEqualTo + * @tc.name: RDB_Native_predicates_test_002 + * @tc.desc: Normal testCase of Predicates for NotEqualTo * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_002, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_002, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -163,11 +164,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_002, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_003 - * @tc.desc: Normal testCase of NDK Predicates for GreaterThan + * @tc.name: RDB_Native_predicates_test_003 + * @tc.desc: Normal testCase of Predicates for GreaterThan * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_003, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_003, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -245,11 +246,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_003, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_004 - * @tc.desc: Normal testCase of NDK Predicates for GreaterThanOrEqualTo + * @tc.name: RDB_Native_predicates_test_004 + * @tc.desc: Normal testCase of Predicates for GreaterThanOrEqualTo * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_004, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_004, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -270,11 +271,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_004, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_005 - * @tc.desc: Normal testCase of NDK Predicates for LessThan + * @tc.name: RDB_Native_predicates_test_005 + * @tc.desc: Normal testCase of Predicates for LessThan * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_005, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_005, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -295,11 +296,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_005, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_006 - * @tc.desc: Normal testCase of NDK Predicates for LessThanOrEqualTo + * @tc.name: RDB_Native_predicates_test_006 + * @tc.desc: Normal testCase of Predicates for LessThanOrEqualTo * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_006, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_006, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -320,11 +321,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_006, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_007 - * @tc.desc: Normal testCase of NDK Predicates for IsNull. + * @tc.name: RDB_Native_predicates_test_007 + * @tc.desc: Normal testCase of Predicates for IsNull. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_007, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_007, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -341,11 +342,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_007, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_008 - * @tc.desc: Normal testCase of NDK Predicates for IsNull. + * @tc.name: RDB_Native_predicates_test_008 + * @tc.desc: Normal testCase of Predicates for IsNull. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_008, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_008, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -362,11 +363,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_008, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_009 - * @tc.desc: Normal testCase of NDK Predicates for Between + * @tc.name: RDB_Native_predicates_test_009 + * @tc.desc: Normal testCase of Predicates for Between * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_009, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_009, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -392,11 +393,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_009, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_010 - * @tc.desc: Normal testCase of NDK Predicates for NotBetween + * @tc.name: RDB_Native_predicates_test_010 + * @tc.desc: Normal testCase of Predicates for NotBetween * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_010, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_010, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -418,11 +419,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_010, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_011 - * @tc.desc: Normal testCase of NDK Predicates for OrderBy、Limit、Offset. + * @tc.name: RDB_Native_predicates_test_011 + * @tc.desc: Normal testCase of Predicates for OrderBy、Limit、Offset. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_011, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_011, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -450,11 +451,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_011, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_012 - * @tc.desc: Normal testCase of NDK Predicates for In. + * @tc.name: RDB_Native_predicates_test_012 + * @tc.desc: Normal testCase of Predicates for In. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_012, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_012, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -476,11 +477,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_012, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_013 - * @tc.desc: Normal testCase of NDK Predicates for NotIn. + * @tc.name: RDB_Native_predicates_test_013 + * @tc.desc: Normal testCase of Predicates for NotIn. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_013, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_013, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -502,11 +503,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_013, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_014 - * @tc.desc: Normal testCase of NDK Predicates for Like. + * @tc.name: RDB_Native_predicates_test_014 + * @tc.desc: Normal testCase of Predicates for Like. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_014, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_014, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -530,11 +531,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_014, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_015 - * @tc.desc: Normal testCase of NDK Predicates for GroupBy. + * @tc.name: RDB_Native_predicates_test_015 + * @tc.desc: Normal testCase of Predicates for GroupBy. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_015, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_015, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -553,11 +554,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_015, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_016 - * @tc.desc: Normal testCase of NDK Predicates for And. + * @tc.name: RDB_Native_predicates_test_016 + * @tc.desc: Normal testCase of Predicates for And. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_016, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_016, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -582,11 +583,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_016, TestSize.Level1) } /** - * @tc.name: RDB_NDK_predicates_test_017 - * @tc.desc: Normal testCase of NDK Predicates for Clear. + * @tc.name: RDB_Native_predicates_test_017 + * @tc.desc: Normal testCase of Predicates for Clear. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_017, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_017, TestSize.Level1) { int errCode = 0; OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); @@ -614,11 +615,11 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_017, TestSize.Level1) cursor->destroy(cursor); } /** - * @tc.name: RDB_NDK_predicates_test_018 - * @tc.desc: Normal testCase of NDK Predicates for table name is NULL. + * @tc.name: RDB_Native_predicates_test_018 + * @tc.desc: Normal testCase of Predicates for table name is NULL. * @tc.type: FUNC */ -HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_018, TestSize.Level1) +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_018, TestSize.Level1) { char *table = NULL; OH_Predicates *predicates = OH_Rdb_CreatePredicates(table); @@ -626,4 +627,145 @@ HWTEST_F(RdbNdkPredicatesTest, RDB_NDK_predicates_test_018, TestSize.Level1) OH_Cursor *cursor = OH_Rdb_Query(predicatesTestRdbStore_, predicates, NULL, 0); EXPECT_EQ(cursor, NULL); +} + +/** + * @tc.name: RDB_Native_predicates_test_019 + * @tc.desc: Normal testCase of Predicates for anomalous branch. + * @tc.type: FUNC + */ +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_019, TestSize.Level1) +{ + OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); + EXPECT_NE(predicates, NULL); + + OH_VObject *valueObject = OH_Rdb_CreateValueObject(); + const char *data1Value = "zhangSan"; + valueObject->putText(valueObject, data1Value); + predicates->equalTo(nullptr, "data1", valueObject); + predicates->equalTo(predicates, nullptr, valueObject); + predicates->equalTo(predicates, "data1", nullptr); + predicates->notEqualTo(nullptr, "data1", valueObject); + predicates->notEqualTo(predicates, nullptr, valueObject); + predicates->notEqualTo(predicates, "data1", nullptr); + + predicates->beginWrap(nullptr); + predicates->endWrap(nullptr); + + predicates->orOperate(nullptr); + predicates->andOperate(nullptr); + + predicates->isNull(nullptr, "data4"); + predicates->isNull(predicates, nullptr); + predicates->isNotNull(nullptr, "data4"); + predicates->isNotNull(predicates, nullptr); + + const char *data5ValueLike = "ABCD%"; + valueObject->putText(valueObject, data5ValueLike); + predicates->like(nullptr, "data5", valueObject); + predicates->like(predicates, nullptr, valueObject); + predicates->like(predicates, "data5", nullptr); + + int64_t data2Value[] = {12000, 13000}; + uint32_t len = sizeof(data2Value) / sizeof(data2Value[0]); + valueObject->putInt64(valueObject, data2Value, len); + predicates->between(nullptr, "data2", valueObject); + predicates->between(predicates, nullptr, valueObject); + predicates->between(predicates, "data2", nullptr); + predicates->notBetween(nullptr, "data2", valueObject); + predicates->notBetween(predicates, nullptr, valueObject); + predicates->notBetween(predicates, "data2", nullptr); + int64_t data2Value_1[] = {12000}; + len = sizeof(data2Value_1) / sizeof(data2Value_1[0]); + valueObject->putInt64(valueObject, data2Value_1, len); + predicates->between(predicates, "data2", valueObject); + predicates->notBetween(predicates, "data2", valueObject); + + const char *data5Value = "ABCDEFG"; + valueObject->putText(valueObject, data5Value); + predicates->greaterThan(nullptr, "data5", valueObject); + predicates->greaterThan(predicates, nullptr, valueObject); + predicates->greaterThan(predicates, "data5", nullptr); + predicates->lessThan(nullptr, "data5", valueObject); + predicates->lessThan(predicates, nullptr, valueObject); + predicates->lessThan(predicates, "data5", nullptr); + predicates->greaterThanOrEqualTo(nullptr, "data5", valueObject); + predicates->greaterThanOrEqualTo(predicates, nullptr, valueObject); + predicates->greaterThanOrEqualTo(predicates, "data5", nullptr); + predicates->lessThanOrEqualTo(nullptr, "data5", valueObject); + predicates->lessThanOrEqualTo(predicates, nullptr, valueObject); + predicates->lessThanOrEqualTo(predicates, "data5", nullptr); + + predicates->orderBy(nullptr, "data2", OH_OrderType::ASC); + predicates->orderBy(predicates, nullptr, OH_OrderType::ASC); + + predicates->distinct(nullptr); + predicates->limit(nullptr, 1); + predicates->offset(nullptr, 1); + + const char *columnNames[] = {"data1", "data2"}; + len = sizeof(columnNames) / sizeof(columnNames[0]); + predicates->groupBy(nullptr, columnNames, len); + predicates->groupBy(predicates, nullptr, len); + predicates->groupBy(predicates, columnNames, 0); + + const char *data1ValueIn[] = {"zhangSan", "liSi"}; + len = sizeof(data1ValueIn) / sizeof(data1ValueIn[0]); + valueObject->putTexts(valueObject, data1ValueIn, len); + predicates->in(nullptr, "data1", valueObject); + predicates->in(predicates, nullptr, valueObject); + predicates->in(predicates, "data1", nullptr); + predicates->notIn(nullptr, "data1", valueObject); + predicates->notIn(predicates, nullptr, valueObject); + predicates->notIn(predicates, "data1", nullptr); + + predicates->clear(nullptr); + int errCode = predicates->destroy(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + valueObject->destroy(valueObject); + predicates->destroy(predicates); +} + +/** + * @tc.name: RDB_Native_predicates_test_020 + * @tc.desc: Normal testCase of RelationalPredicatesObjects for anomalous branch. + * @tc.type: FUNC + */ +HWTEST_F(RdbNativePredicatesTest, RDB_Native_predicates_test_020, TestSize.Level1) +{ + OH_VObject *valueObject = OH_Rdb_CreateValueObject(); + int64_t data2Value[] = {12000, 13000}; + uint32_t len = sizeof(data2Value) / sizeof(data2Value[0]); + int errCode = valueObject->putInt64(nullptr, data2Value, len); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueObject->putInt64(valueObject, nullptr, len); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueObject->putInt64(valueObject, data2Value, 0); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + uint32_t count = 1; + double data3Value = 200.1; + errCode = valueObject->putDouble(nullptr, &data3Value, count); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueObject->putDouble(valueObject, nullptr, count); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueObject->putDouble(valueObject, &data3Value, 0); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + const char *data1Value = "zhangSan"; + valueObject->putText(nullptr, data1Value); + valueObject->putText(valueObject, nullptr); + + const char *data1ValueTexts[] = {"zhangSan", "liSi"}; + len = sizeof(data1ValueTexts) / sizeof(data1ValueTexts[0]); + errCode = valueObject->putTexts(nullptr, data1ValueTexts, len); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueObject->putTexts(valueObject, nullptr, len); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueObject->putTexts(valueObject, data1ValueTexts, 0); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + errCode = valueObject->destroy(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + valueObject->destroy(valueObject); } \ No newline at end of file diff --git a/relational_store/test/ndk/unittest/rdb_store_test.cpp b/relational_store/test/ndk/unittest/rdb_store_test.cpp index 645640d3..c584efc8 100644 --- a/relational_store/test/ndk/unittest/rdb_store_test.cpp +++ b/relational_store/test/ndk/unittest/rdb_store_test.cpp @@ -25,7 +25,7 @@ using namespace testing::ext; using namespace OHOS::NativeRdb; -class RdbNdkStoreTest : public testing::Test { +class RdbNativeStoreTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); @@ -34,7 +34,7 @@ public: static void InitRdbConfig() { config_.dataBaseDir = RDB_TEST_PATH; - config_.storeName = "rdb_predicates_test.db"; + config_.storeName = "rdb_store_test.db"; config_.bundleName = ""; config_.moduleName = ""; config_.securityLevel = OH_Rdb_SecurityLevel::S1; @@ -45,8 +45,8 @@ public: }; OH_Rdb_Store *storeTestRdbStore_; -OH_Rdb_Config RdbNdkStoreTest::config_ = {0}; -void RdbNdkStoreTest::SetUpTestCase(void) +OH_Rdb_Config RdbNativeStoreTest::config_ = {0}; +void RdbNativeStoreTest::SetUpTestCase(void) { InitRdbConfig(); mkdir(config_.dataBaseDir, 0770); @@ -55,7 +55,7 @@ void RdbNdkStoreTest::SetUpTestCase(void) EXPECT_NE(storeTestRdbStore_, NULL); } -void RdbNdkStoreTest::TearDownTestCase(void) +void RdbNativeStoreTest::TearDownTestCase(void) { int errCode = OH_Rdb_CloseStore(storeTestRdbStore_); EXPECT_EQ(errCode, 0); @@ -63,7 +63,7 @@ void RdbNdkStoreTest::TearDownTestCase(void) EXPECT_EQ(errCode, 0); } -void RdbNdkStoreTest::SetUp(void) +void RdbNativeStoreTest::SetUp(void) { char createTableSql[] = "CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 TEXT, data2 INTEGER, " "data3 FLOAT, data4 BLOB, data5 TEXT);"; @@ -71,7 +71,7 @@ void RdbNdkStoreTest::SetUp(void) EXPECT_EQ(errCode, 0); } -void RdbNdkStoreTest::TearDown(void) +void RdbNativeStoreTest::TearDown(void) { char dropTableSql[] = "DROP TABLE IF EXISTS test"; int errCode = OH_Rdb_Execute(storeTestRdbStore_, dropTableSql); @@ -79,11 +79,11 @@ void RdbNdkStoreTest::TearDown(void) } /** - * @tc.name: RDB_NDK_store_test_001 - * @tc.desc: Normal testCase of NDK store for Insert、Update、Query. + * @tc.name: RDB_Native_store_test_001 + * @tc.desc: Normal testCase of store for Insert、Update、Query. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_001, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_001, TestSize.Level1) { int errCode = 0; OH_VBucket* valueBucket = OH_Rdb_CreateValuesBucket(); @@ -154,11 +154,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_001, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_002 - * @tc.desc: Normal testCase of NDK store for Delete、ExecuteQuery. + * @tc.name: RDB_Native_store_test_002 + * @tc.desc: Normal testCase of store for Delete、ExecuteQuery. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_002, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_002, TestSize.Level1) { int errCode = 0; OH_VBucket* valueBucket = OH_Rdb_CreateValuesBucket(); @@ -230,11 +230,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_002, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_003 - * @tc.desc: Normal testCase of NDK store for Transaction、Commit. + * @tc.name: RDB_Native_store_test_003 + * @tc.desc: Normal testCase of store for Transaction、Commit. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_003, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_003, TestSize.Level1) { OH_Rdb_BeginTransaction(storeTestRdbStore_); @@ -274,11 +274,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_003, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_004 - * @tc.desc: Normal testCase of NDK store for Transaction、RollBack. + * @tc.name: RDB_Native_store_test_004 + * @tc.desc: Normal testCase of store for Transaction、RollBack. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_004, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_004, TestSize.Level1) { OH_Rdb_BeginTransaction(storeTestRdbStore_); @@ -318,11 +318,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_004, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_005 - * @tc.desc: Normal testCase of NDK store for Backup、Restore. + * @tc.name: RDB_Native_store_test_005 + * @tc.desc: Normal testCase of store for Backup、Restore. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_005, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_005, TestSize.Level1) { int errCode = 0; OH_VBucket* valueBucket = OH_Rdb_CreateValuesBucket(); @@ -399,11 +399,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_005, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_006 - * @tc.desc: Normal testCase of NDK store for Backup、Restore. + * @tc.name: RDB_Native_store_test_006 + * @tc.desc: Normal testCase of store for Backup、Restore. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_006, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_006, TestSize.Level1) { int errCode = 0; OH_VBucket* valueBucket = OH_Rdb_CreateValuesBucket(); @@ -471,11 +471,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_006, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_007 - * @tc.desc: Normal testCase of NDK store for GetVersion、SetVersion. + * @tc.name: RDB_Native_store_test_007 + * @tc.desc: Normal testCase of store for GetVersion、SetVersion. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_007, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_007, TestSize.Level1) { int errCode = 0; int version = 0; @@ -491,11 +491,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_007, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_008 - * @tc.desc: Normal testCase of NDK store for Insert with wrong table name or table is NULL. + * @tc.name: RDB_Native_store_test_008 + * @tc.desc: Normal testCase of store for Insert with wrong table name or table is NULL. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_008, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_008, TestSize.Level1) { int errCode = 0; OH_VBucket* valueBucket = OH_Rdb_CreateValuesBucket(); @@ -541,11 +541,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_008, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_009 - * @tc.desc: Normal testCase of NDK store for Update with wrong table or table is NULL. + * @tc.name: RDB_Native_store_test_009 + * @tc.desc: Normal testCase of store for Update with wrong table or table is NULL. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_009, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_009, TestSize.Level1) { int errCode = 0; OH_VBucket* valueBucket = OH_Rdb_CreateValuesBucket(); @@ -624,11 +624,11 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_009, TestSize.Level1) } /** - * @tc.name: RDB_NDK_store_test_010 - * @tc.desc: Normal testCase of NDK store for querysql is NULL. + * @tc.name: RDB_Native_store_test_010 + * @tc.desc: Normal testCase of store for querysql is NULL. * @tc.type: FUNC */ -HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_010, TestSize.Level1) +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_010, TestSize.Level1) { int errCode = 0; OH_VBucket *valueBucket = OH_Rdb_CreateValuesBucket(); @@ -648,4 +648,138 @@ HWTEST_F(RdbNdkStoreTest, RDB_NDK_store_test_010, TestSize.Level1) EXPECT_EQ(cursor, NULL); valueBucket->destroy(valueBucket); +} + +/** + * @tc.name: RDB_Native_store_test_011 + * @tc.desc: Normal testCase of RelationalValuesBucket for anomalous branch. + * @tc.type: FUNC + */ +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_011, TestSize.Level1) +{ + OH_VBucket *valueBucket = OH_Rdb_CreateValuesBucket(); + uint8_t arr[] = { 1, 2, 3, 4, 5 }; + uint32_t len = sizeof(arr) / sizeof(arr[0]); + int errCode = valueBucket->putBlob(nullptr, "data4", arr, len); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueBucket->putBlob(valueBucket, nullptr, arr, len); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueBucket->putBlob(valueBucket, "data4", nullptr, len); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_OK); + + errCode = valueBucket->clear(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = valueBucket->destroy(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + valueBucket->destroy(valueBucket); +} + +/** + * @tc.name: RDB_Native_store_test_012 + * @tc.desc: Normal testCase of store for anomalous branch. + * @tc.type: FUNC + */ +HWTEST_F(RdbNativeStoreTest, RDB_Native_store_test_012, TestSize.Level1) +{ + int errCode = 0; + OH_Rdb_Config config; + config.dataBaseDir = RDB_TEST_PATH; + config.storeName = "rdb_store_error.db"; + config.bundleName = nullptr; + config.moduleName = ""; + config.securityLevel = OH_Rdb_SecurityLevel::S1; + config.isEncrypt = false; + config.selfSize = 0; + + auto store = OH_Rdb_GetOrOpen(nullptr, &errCode); + EXPECT_EQ(store, nullptr); + store = OH_Rdb_GetOrOpen(&config, nullptr); + EXPECT_EQ(store, nullptr); + store = OH_Rdb_GetOrOpen(&config, &errCode); + EXPECT_EQ(store, nullptr); + + config.selfSize = sizeof(OH_Rdb_Config); + store = OH_Rdb_GetOrOpen(&config, &errCode); + EXPECT_NE(store, nullptr); + + char createTableSql[] = "CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 TEXT, data2 INTEGER, " + "data3 FLOAT, data4 BLOB, data5 TEXT);"; + errCode = OH_Rdb_Execute(nullptr, createTableSql); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Execute(store, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + OH_VBucket *valueBucket = OH_Rdb_CreateValuesBucket(); + errCode = OH_Rdb_Insert(nullptr, "test", valueBucket); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Insert(store, nullptr, valueBucket); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Insert(store, "test", nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + OH_Predicates *predicates = OH_Rdb_CreatePredicates("test"); + errCode = OH_Rdb_Update(nullptr, valueBucket, predicates); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Update(store, nullptr, predicates); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Update(store, valueBucket, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + errCode = OH_Rdb_Delete(nullptr, predicates); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Delete(store, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + auto cursor = OH_Rdb_Query(nullptr, predicates, NULL, 0); + EXPECT_EQ(cursor, nullptr); + cursor = OH_Rdb_Query(store, nullptr, NULL, 0); + EXPECT_EQ(cursor, nullptr); + + char querySql[] = "SELECT * FROM test"; + cursor = OH_Rdb_ExecuteQuery(nullptr, querySql); + EXPECT_EQ(cursor, nullptr); + cursor = OH_Rdb_ExecuteQuery(store, nullptr); + EXPECT_EQ(cursor, nullptr); + + errCode = OH_Rdb_BeginTransaction(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_RollBack(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Commit(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + char backupDir[] = "backup.db"; + errCode = OH_Rdb_Backup(nullptr, backupDir); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Backup(store, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + errCode = OH_Rdb_Restore(nullptr, backupDir); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_Restore(store, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + int version = 1; + errCode = OH_Rdb_SetVersion(nullptr, version); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_GetVersion(nullptr, &version); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_GetVersion(store, nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + errCode = OH_Rdb_CloseStore(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + errCode = OH_Rdb_DeleteStore(nullptr); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + config.dataBaseDir = nullptr; + errCode = OH_Rdb_DeleteStore(&config); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + config.dataBaseDir = RDB_TEST_PATH; + config.storeName = nullptr; + errCode = OH_Rdb_DeleteStore(&config); + EXPECT_EQ(errCode, OH_Rdb_ErrCode::RDB_E_INVALID_ARGS); + + config.storeName = "rdb_store_error.db"; + OH_Rdb_CloseStore(store); + OH_Rdb_DeleteStore(&config); } \ No newline at end of file diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 8be41434..4d73750a 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.11.2) project(LDBTest) set(CMAKE_CXX_STANDARD 17) @@ -36,7 +36,7 @@ aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/dis aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/service/test/data_share remoteTestSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../preferences/test/native/unittest localTestSrc) #aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/test/native/dataability/unittest localTestSrc) -#aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/test/native/rdb/unittest localTestSrc) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/test/native/rdb/unittest localTestSrc) #aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/test/native/rdb_data_share_adapter/unittest localTestSrc) #aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../udmf/framework/innerkitsimpl/test/unittest remoteTestSrc) diff --git a/test/include/CMakeLists.txt b/test/include/CMakeLists.txt index 37e1580c..491119af 100644 --- a/test/include/CMakeLists.txt +++ b/test/include/CMakeLists.txt @@ -10,6 +10,7 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkits include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/libs/distributeddb/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/libs/distributeddb/interfaces/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/libs/distributeddb/interfaces/include/relational) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/libs/distributeddb/interfaces/include/cloud) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/adapter/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/adapter/include/account) @@ -46,6 +47,7 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../preferences/frameworks/js/nap include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../preferences/interfaces/inner_api/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/cloud_data/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) diff --git a/udmf/BUILD.gn b/udmf/BUILD.gn index 8cc737b8..32d165c9 100644 --- a/udmf/BUILD.gn +++ b/udmf/BUILD.gn @@ -18,7 +18,8 @@ group("udmf_packages") { deps = [ "interfaces/innerkits:udmf_client", "interfaces/jskits:udmf_data_napi", - "interfaces/jskits:udmf_napi", + "interfaces/jskits:unifieddatachannel_napi", + "interfaces/jskits:uniformtypedescriptor_napi", ] } } diff --git a/udmf/CMakeLists.txt b/udmf/CMakeLists.txt index 8435f24f..1108af54 100644 --- a/udmf/CMakeLists.txt +++ b/udmf/CMakeLists.txt @@ -15,22 +15,16 @@ aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/common udmf_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/innerkitsimpl/client udmf_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/innerkitsimpl/common udmf_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/innerkitsimpl/data udmf_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/jskitsimpl/common udmf_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/jskitsimpl/data udmf_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/jskitsimpl/common udmf_channel_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/jskitsimpl/data udmf_channel_src) +list(REMOVE_ITEM udmf_channel_src "${CMAKE_CURRENT_SOURCE_DIR}/frameworks/jskitsimpl/data/uniform_type_descriptor_napi.cpp") aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/framework/service udmf_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/jskits/module udmf_src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/framework/common) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/framework/service) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/innerkits/client) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/innerkits/common) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/innerkits/data) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/jskits/common) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/jskits/data) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/common) -#include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/innerkitsimpl/distributeddatafwk/include) -#include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/innerkitsimpl/distributeddatafwk/src) -#include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/innerkits/distributeddata/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/safwk/native/include) @@ -39,4 +33,10 @@ include(${KV_STORE_DIR}/interfaces/CMakeLists.txt OPTIONAL) set(links secure mock distributeddb kvdb) add_library(udmf SHARED ${udmf_src}) -target_link_libraries(udmf ${links}) \ No newline at end of file +target_link_libraries(udmf ${links}) +target_include_directories(udmf PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/innerkits/client) +target_include_directories(udmf PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/innerkits/common) +target_include_directories(udmf PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/interfaces/innerkits/data) + +add_library(udmf_channel SHARED ${udmf_channel_src}) +target_link_libraries(udmf_channel mock udmf) \ No newline at end of file diff --git a/udmf/framework/innerkitsimpl/test/unittest/udmf_client_test.cpp b/udmf/framework/innerkitsimpl/test/unittest/udmf_client_test.cpp index e1d94e15..24d20d48 100644 --- a/udmf/framework/innerkitsimpl/test/unittest/udmf_client_test.cpp +++ b/udmf/framework/innerkitsimpl/test/unittest/udmf_client_test.cpp @@ -1222,12 +1222,12 @@ HWTEST_F(UdmfClientTest, GetSummary001, TestSize.Level1) ASSERT_EQ(status, E_OK); ASSERT_EQ(summary.totalSize, size); - ASSERT_EQ(summary.summary["Text"], record1->GetSize()); - ASSERT_EQ(summary.summary["Text.PlainText"], record2->GetSize()); - ASSERT_EQ(summary.summary["File"], record3->GetSize()); - ASSERT_EQ(summary.summary["File.Media.Image"], record4->GetSize()); + ASSERT_EQ(summary.summary["general.text"], record1->GetSize()); + ASSERT_EQ(summary.summary["general.plain-text"], record2->GetSize()); + ASSERT_EQ(summary.summary["general.file"], record3->GetSize()); + ASSERT_EQ(summary.summary["general.image"], record4->GetSize()); ASSERT_EQ(summary.summary["SystemDefinedType"], record5->GetSize()); - ASSERT_EQ(summary.summary["SystemDefinedType.Form"], record6->GetSize()); + ASSERT_EQ(summary.summary["openharmony.form"], record6->GetSize()); ASSERT_EQ(summary.summary["ApplicationDefinedType"], record7->GetSize()); LOG_INFO(UDMF_TEST, "GetSummary001 end."); diff --git a/udmf/framework/jskitsimpl/data/udmf_napi.cpp b/udmf/framework/jskitsimpl/data/unified_data_channel_napi.cpp similarity index 78% rename from udmf/framework/jskitsimpl/data/udmf_napi.cpp rename to udmf/framework/jskitsimpl/data/unified_data_channel_napi.cpp index d437acc3..f4b2f860 100644 --- a/udmf/framework/jskitsimpl/data/udmf_napi.cpp +++ b/udmf/framework/jskitsimpl/data/unified_data_channel_napi.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "udmf_napi.h" +#include "unified_data_channel_napi.h" #include "napi_data_utils.h" #include "napi_error_utils.h" @@ -23,13 +23,11 @@ namespace OHOS { namespace UDMF { -napi_value UDMFNapi::UDMFInit(napi_env env, napi_value exports) +napi_value UnifiedDataChannelNapi::UnifiedDataChannelInit(napi_env env, napi_value exports) { - LOG_DEBUG(UDMF_KITS_NAPI, "UDMFNapi"); - napi_value unifiedDataType = CreateUnifiedDataType(env); + LOG_DEBUG(UDMF_KITS_NAPI, "UnifiedDataChannelNapi"); napi_value intention = CreateIntention(env); napi_property_descriptor desc[] = { - DECLARE_NAPI_PROPERTY("UnifiedDataType", unifiedDataType), DECLARE_NAPI_PROPERTY("Intention", intention), DECLARE_NAPI_FUNCTION("insertData", InsertData), DECLARE_NAPI_FUNCTION("updateData", UpdateData), @@ -41,35 +39,7 @@ napi_value UDMFNapi::UDMFInit(napi_env env, napi_value exports) return exports; } -napi_value UDMFNapi::CreateUnifiedDataType(napi_env env) -{ - LOG_DEBUG(UDMF_KITS_NAPI, "UDMFNapi"); - napi_value unifiedDataType = nullptr; - napi_create_object(env, &unifiedDataType); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(TEXT), UD_TYPE_MAP.at(TEXT)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(PLAIN_TEXT), UD_TYPE_MAP.at(PLAIN_TEXT)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(HTML), UD_TYPE_MAP.at(HTML)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(HYPERLINK), UD_TYPE_MAP.at(HYPERLINK)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(FILE), UD_TYPE_MAP.at(FILE)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(IMAGE), UD_TYPE_MAP.at(IMAGE)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(VIDEO), UD_TYPE_MAP.at(VIDEO)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(AUDIO), UD_TYPE_MAP.at(AUDIO)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(FOLDER), UD_TYPE_MAP.at(FOLDER)); - SetNamedProperty( - env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_RECORD), UD_TYPE_MAP.at(SYSTEM_DEFINED_RECORD)); - SetNamedProperty( - env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_FORM), UD_TYPE_MAP.at(SYSTEM_DEFINED_FORM)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_APP_ITEM), - UD_TYPE_MAP.at(SYSTEM_DEFINED_APP_ITEM)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_PIXEL_MAP), - UD_TYPE_MAP.at(SYSTEM_DEFINED_PIXEL_MAP)); - SetNamedProperty(env, unifiedDataType, JS_UD_TYPE_NAME_MAP.at(APPLICATION_DEFINED_RECORD), - UD_TYPE_MAP.at(APPLICATION_DEFINED_RECORD)); - napi_object_freeze(env, unifiedDataType); - return unifiedDataType; -} - -napi_value UDMFNapi::CreateIntention(napi_env env) +napi_value UnifiedDataChannelNapi::CreateIntention(napi_env env) { napi_value intention = nullptr; napi_create_object(env, &intention); @@ -79,7 +49,8 @@ napi_value UDMFNapi::CreateIntention(napi_env env) return intention; } -napi_status UDMFNapi::SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, const std::string &value) +napi_status UnifiedDataChannelNapi::SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, + const std::string &value) { napi_value property = nullptr; napi_status status = NapiDataUtils::SetValue(env, value, property); @@ -89,7 +60,7 @@ napi_status UDMFNapi::SetNamedProperty(napi_env env, napi_value &obj, const std: return status; } -napi_value UDMFNapi::InsertData(napi_env env, napi_callback_info info) +napi_value UnifiedDataChannelNapi::InsertData(napi_env env, napi_callback_info info) { LOG_DEBUG(UDMF_KITS_NAPI, "InsertData is called!"); struct InsertContext : public ContextBase { @@ -107,8 +78,8 @@ napi_value UDMFNapi::InsertData(napi_env env, napi_callback_info info) ASSERT_BUSINESS_ERR(ctxt, ctxt->status == napi_ok && UnifiedDataUtils::IsPersist(intention), E_INVALID_PARAMETERS, "invalid arg[0], i.e. invalid intention!"); ctxt->status = napi_unwrap(env, argv[1], reinterpret_cast(&unifiedDataNapi)); - ASSERT_BUSINESS_ERR( - ctxt, ctxt->status == napi_ok, E_INVALID_PARAMETERS, "invalid arg[1], i.e. invalid unifiedData!"); + ASSERT_BUSINESS_ERR(ctxt, ctxt->status == napi_ok, E_INVALID_PARAMETERS, + "invalid arg[1], i.e. invalid unifiedData!"); }; ctxt->GetCbInfo(env, info, input); ASSERT_NULL(!ctxt->isThrowError, "Insert Exit"); @@ -127,7 +98,7 @@ napi_value UDMFNapi::InsertData(napi_env env, napi_callback_info info) return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } -napi_value UDMFNapi::UpdateData(napi_env env, napi_callback_info info) +napi_value UnifiedDataChannelNapi::UpdateData(napi_env env, napi_callback_info info) { LOG_DEBUG(UDMF_KITS_NAPI, "UpdateData is called!"); struct UpdateContext : public ContextBase { @@ -146,8 +117,8 @@ napi_value UDMFNapi::UpdateData(napi_env env, napi_callback_info info) ctxt->status == napi_ok && key.IsValid() && UnifiedDataUtils::IsPersist(key.intention), E_INVALID_PARAMETERS, "invalid arg[0], i.e. invalid key!"); ctxt->status = napi_unwrap(env, argv[1], reinterpret_cast(&unifiedDataNapi)); - ASSERT_BUSINESS_ERR( - ctxt, ctxt->status == napi_ok, E_INVALID_PARAMETERS, "invalid arg[1], i.e. invalid unifiedData!"); + ASSERT_BUSINESS_ERR(ctxt, ctxt->status == napi_ok, E_INVALID_PARAMETERS, + "invalid arg[1], i.e. invalid unifiedData!"); }; ctxt->GetCbInfo(env, info, input); ASSERT_NULL(!ctxt->isThrowError, "Update Exit"); @@ -160,7 +131,7 @@ napi_value UDMFNapi::UpdateData(napi_env env, napi_callback_info info) return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute); } -napi_value UDMFNapi::QueryData(napi_env env, napi_callback_info info) +napi_value UnifiedDataChannelNapi::QueryData(napi_env env, napi_callback_info info) { LOG_DEBUG(UDMF_KITS_NAPI, "QueryData is called!"); struct QueryContext : public ContextBase { @@ -179,8 +150,8 @@ napi_value UDMFNapi::QueryData(napi_env env, napi_callback_info info) keyStatus = GetNamedProperty(env, options, "key", ctxt->key); intentionStatus = GetNamedProperty(env, options, "intention", intention); ASSERT_BUSINESS_ERR(ctxt, - (keyStatus == napi_ok || intentionStatus == napi_ok) - && UnifiedDataUtils::IsValidOptions(ctxt->key, intention), + (keyStatus == napi_ok || intentionStatus == napi_ok) && + UnifiedDataUtils::IsValidOptions(ctxt->key, intention), E_INVALID_PARAMETERS, "invalid arg[0], i.e. invalid options!"); }; ctxt->GetCbInfo(env, info, input); @@ -213,7 +184,7 @@ napi_value UDMFNapi::QueryData(napi_env env, napi_callback_info info) return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } -napi_value UDMFNapi::DeleteData(napi_env env, napi_callback_info info) +napi_value UnifiedDataChannelNapi::DeleteData(napi_env env, napi_callback_info info) { LOG_DEBUG(UDMF_KITS_NAPI, "DeleteData is called!"); struct DeleteContext : public ContextBase { @@ -232,8 +203,8 @@ napi_value UDMFNapi::DeleteData(napi_env env, napi_callback_info info) keyStatus = GetNamedProperty(env, options, "key", ctxt->key); intentionStatus = GetNamedProperty(env, options, "intention", intention); ASSERT_BUSINESS_ERR(ctxt, - (keyStatus == napi_ok || intentionStatus == napi_ok) - && UnifiedDataUtils::IsValidOptions(ctxt->key, intention), + (keyStatus == napi_ok || intentionStatus == napi_ok) && + UnifiedDataUtils::IsValidOptions(ctxt->key, intention), E_INVALID_PARAMETERS, "invalid arg[0], i.e. invalid options!"); }; ctxt->GetCbInfo(env, info, input); @@ -266,7 +237,8 @@ napi_value UDMFNapi::DeleteData(napi_env env, napi_callback_info info) return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } -napi_status UDMFNapi::GetNamedProperty(napi_env env, napi_value &obj, const std::string &key, std::string &value) +napi_status UnifiedDataChannelNapi::GetNamedProperty(napi_env env, napi_value &obj, const std::string &key, + std::string &value) { bool hasKey = false; napi_status status = napi_has_named_property(env, obj, key.c_str(), &hasKey); diff --git a/udmf/framework/jskitsimpl/data/uniform_type_descriptor_napi.cpp b/udmf/framework/jskitsimpl/data/uniform_type_descriptor_napi.cpp new file mode 100644 index 00000000..df187627 --- /dev/null +++ b/udmf/framework/jskitsimpl/data/uniform_type_descriptor_napi.cpp @@ -0,0 +1,75 @@ +/* +* 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 "uniform_type_descriptor_napi.h" + +#include "napi_data_utils.h" +#include "napi_error_utils.h" +#include "napi_queue.h" +#include "unified_meta.h" + +namespace OHOS { +namespace UDMF { +napi_value UniformTypeDescriptorNapi::UniformTypeDescriptorInit(napi_env env, napi_value exports) +{ + LOG_DEBUG(UDMF_KITS_NAPI, "UniformTypeDescriptorNapi"); + napi_value uniformDataType = CreateUniformDataType(env); + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("UniformDataType", uniformDataType), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value UniformTypeDescriptorNapi::CreateUniformDataType(napi_env env) +{ + napi_value uniformDataType = nullptr; + napi_create_object(env, &uniformDataType); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(TEXT), UD_TYPE_MAP.at(TEXT)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(PLAIN_TEXT), UD_TYPE_MAP.at(PLAIN_TEXT)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(HTML), UD_TYPE_MAP.at(HTML)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(HYPERLINK), UD_TYPE_MAP.at(HYPERLINK)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(FILE), UD_TYPE_MAP.at(FILE)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(IMAGE), UD_TYPE_MAP.at(IMAGE)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(VIDEO), UD_TYPE_MAP.at(VIDEO)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(AUDIO), UD_TYPE_MAP.at(AUDIO)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(FOLDER), UD_TYPE_MAP.at(FOLDER)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_RECORD), + UD_TYPE_MAP.at(SYSTEM_DEFINED_RECORD)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_FORM), + UD_TYPE_MAP.at(SYSTEM_DEFINED_FORM)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_APP_ITEM), + UD_TYPE_MAP.at(SYSTEM_DEFINED_APP_ITEM)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(SYSTEM_DEFINED_PIXEL_MAP), + UD_TYPE_MAP.at(SYSTEM_DEFINED_PIXEL_MAP)); + SetNamedProperty(env, uniformDataType, JS_UD_TYPE_NAME_MAP.at(APPLICATION_DEFINED_RECORD), + UD_TYPE_MAP.at(APPLICATION_DEFINED_RECORD)); + napi_object_freeze(env, uniformDataType); + return uniformDataType; +} + +napi_status UniformTypeDescriptorNapi::SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, + const std::string &value) +{ + napi_value property = nullptr; + napi_status status = NapiDataUtils::SetValue(env, value, property); + ASSERT(status == napi_ok, "string to napi_value failed!", status); + status = napi_set_named_property(env, obj, name.c_str(), property); + ASSERT(status == napi_ok, "napi_set_named_property failed!", status); + return status; +} +} // namespace UDMF +} // namespace OHOS \ No newline at end of file diff --git a/udmf/framework/jskitsimpl/unittest/UdmfCallbackJsTest.js b/udmf/framework/jskitsimpl/unittest/UdmfCallbackJsTest.js index b8d9f764..24948fa5 100644 --- a/udmf/framework/jskitsimpl/unittest/UdmfCallbackJsTest.js +++ b/udmf/framework/jskitsimpl/unittest/UdmfCallbackJsTest.js @@ -14,7 +14,8 @@ */ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index'; -import UDMF from '@ohos.data.UDMF'; +import UDC from '@ohos.data.unifiedDataChannel'; +import UTD from '@ohos.data.uniformTypeDescriptor'; const TEXT_CONTEXT_01 = 'TextContent01'; const TEXT_CONTEXT_02 = 'TextContent02'; @@ -22,18 +23,18 @@ const ERROR_PARAMETER = '401'; describe('UdmfCallbackJSTest', function () { - let gPlainText1 = new UDMF.PlainText(); + let gPlainText1 = new UDC.PlainText(); gPlainText1.textContent = TEXT_CONTEXT_01; - let gPlainText2 = new UDMF.PlainText(); + let gPlainText2 = new UDC.PlainText(); gPlainText2.textContent = TEXT_CONTEXT_02; const optionsValid = { intention: 'DataHub', }; const optionsInValidIntention = { intention: 'Drag', }; const optionsInValidKey = { key: 'udmf://drag/com.test.demo/123456789', }; const optionsInValidAll = { intention: 'DataHub', key: 'udmf://drag/com.test.demo/123456789' }; - const unifiedData01 = new UDMF.UnifiedData(gPlainText1); - const unifiedData02 = new UDMF.UnifiedData(gPlainText2); - const unifiedDataInvalid = new UDMF.UnifiedData(); + const unifiedData01 = new UDC.UnifiedData(gPlainText1); + const unifiedData02 = new UDC.UnifiedData(gPlainText2); + const unifiedDataInvalid = new UDC.UnifiedData(); /** * @tc.name UdmfInsertCallbackInvalidOptionsTest @@ -45,7 +46,7 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfInsertCallbackInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsInValidIntention, unifiedData01, (err, data) => { + UDC.insertData(optionsInValidIntention, unifiedData01, (err, data) => { console.info(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -68,7 +69,7 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfInsertCallbackInvalidDataTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedDataInvalid, (err, data) => { + UDC.insertData(optionsValid, unifiedDataInvalid, (err, data) => { expect(data).assertUndefined(); console.error(TAG, `get fail. code is ${err.code},message is ${err.message} `); expect(err.code === ERROR_PARAMETER).assertTrue(); @@ -92,12 +93,12 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfInsertCallbackSucTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01, (err, data) => { + UDC.insertData(optionsValid, unifiedData01, (err, data) => { expect(err).assertUndefined(); console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `query start. The options: ${JSON.stringify(options)}`); - UDMF.queryData(options, (err, data) => { + UDC.queryData(options, (err, data) => { expect(err).assertUndefined(); console.info(TAG, 'query success.'); console.info(TAG, `data.length = ${data.length}.`); @@ -107,7 +108,7 @@ describe('UdmfCallbackJSTest', function () { console.info(TAG, `records[0].getType() = ${records[0].getType()}.`); console.info(TAG, `records[0].textContent = ${records[0].textContent}.`); expect(records.length).assertEqual(1); - expect(records[0].getType()).assertEqual(UDMF.UnifiedDataType.PLAIN_TEXT); + expect(records[0].getType()).assertEqual(UTD.UniformDataType.PLAIN_TEXT); expect(records[0].textContent).assertEqual(TEXT_CONTEXT_01); done(); }); @@ -130,7 +131,7 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfUpdateCallbackInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.updateData(optionsInValidKey, unifiedData01, (err) => { + UDC.updateData(optionsInValidKey, unifiedData01, (err) => { console.error(TAG, 'Unreachable code!'); expect(null).assertFail(); }); @@ -153,12 +154,12 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfUpdateCallbackInvalidDataTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01, (err, data) => { + UDC.insertData(optionsValid, unifiedData01, (err, data) => { expect(err).assertUndefined(); console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `update start. The options: ${JSON.stringify(options)}`); - UDMF.updateData(options, unifiedDataInvalid, (err) => { + UDC.updateData(options, unifiedDataInvalid, (err) => { console.error(TAG, `get fail. code is ${err.code},message is ${err.message} `); expect(err.code === ERROR_PARAMETER).assertTrue(); done(); @@ -182,21 +183,21 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfUpdateCallbackSucTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01, (err, data) => { + UDC.insertData(optionsValid, unifiedData01, (err, data) => { expect(err).assertUndefined(); console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `update start. The options: ${JSON.stringify(options)}`); - UDMF.updateData(options, unifiedData02, (err) => { + UDC.updateData(options, unifiedData02, (err) => { expect(err).assertUndefined(); console.info(TAG, 'update success.'); - UDMF.queryData(options, (err, data) => { + UDC.queryData(options, (err, data) => { expect(err).assertUndefined(); console.info(TAG, 'query success.'); expect(data.length).assertEqual(1); let records = data[0].getRecords(); expect(records.length).assertEqual(1); - expect(records[0].getType()).assertEqual(UDMF.UnifiedDataType.PLAIN_TEXT); + expect(records[0].getType()).assertEqual(UTD.UniformDataType.PLAIN_TEXT); expect(records[0].textContent).assertEqual(TEXT_CONTEXT_02); done(); }); @@ -222,7 +223,7 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfQueryCallbackInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.queryData(optionsInValidAll, (err, data) => { + UDC.queryData(optionsInValidAll, (err, data) => { console.error(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -245,19 +246,19 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfQueryCallbackSucTest:'; console.info(TAG, 'start'); try { - UDMF.deleteData(optionsValid, (err, data) => { + UDC.deleteData(optionsValid, (err, data) => { expect(err).assertUndefined(); console.info(TAG, 'delete success.'); - UDMF.queryData(optionsValid, (err, data) => { + UDC.queryData(optionsValid, (err, data) => { console.info(TAG, 'query has no data.'); expect(data).assertUndefined(); - UDMF.insertData(optionsValid, unifiedData01, (err, data) => { + UDC.insertData(optionsValid, unifiedData01, (err, data) => { expect(err).assertUndefined(); console.info(TAG, `insert success. The key: ${data}`); - UDMF.insertData(optionsValid, unifiedData02, (err, data) => { + UDC.insertData(optionsValid, unifiedData02, (err, data) => { expect(err).assertUndefined(); console.info(TAG, `insert success. The key: ${data}`); - UDMF.queryData(optionsValid, function (err, data) { + UDC.queryData(optionsValid, function (err, data) { expect(err).assertUndefined(); console.info(TAG, 'query success.'); expect(data.length).assertEqual(2); @@ -286,7 +287,7 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfDeleteCallbackInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.deleteData(optionsInValidAll, (err, data) => { + UDC.deleteData(optionsInValidAll, (err, data) => { console.error(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -309,24 +310,24 @@ describe('UdmfCallbackJSTest', function () { const TAG = 'UdmfDeleteCallbackSucTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01, (err, data) => { + UDC.insertData(optionsValid, unifiedData01, (err, data) => { expect(err).assertUndefined(); console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `query start. The options: ${JSON.stringify(options)}`); - UDMF.queryData(options, (err, data) => { + UDC.queryData(options, (err, data) => { expect(err).assertUndefined(); console.info(TAG, 'query success.'); expect(data.length).assertEqual(1); - UDMF.deleteData(options, (err, data) => { + UDC.deleteData(options, (err, data) => { expect(err).assertUndefined(); console.info(TAG, 'delete success.'); expect(data.length).assertEqual(1); let records = data[0].getRecords(); expect(records.length).assertEqual(1); - expect(records[0].getType()).assertEqual(UDMF.UnifiedDataType.PLAIN_TEXT); + expect(records[0].getType()).assertEqual(UTD.UniformDataType.PLAIN_TEXT); expect(records[0].textContent).assertEqual(TEXT_CONTEXT_01); - UDMF.queryData(options, (err, data) => { + UDC.queryData(options, (err, data) => { expect(data).assertUndefined(); console.info(TAG, 'query has no data.'); done(); diff --git a/udmf/framework/jskitsimpl/unittest/UdmfJsTest.js b/udmf/framework/jskitsimpl/unittest/UdmfJsTest.js index 2a88a7b6..c8044f28 100644 --- a/udmf/framework/jskitsimpl/unittest/UdmfJsTest.js +++ b/udmf/framework/jskitsimpl/unittest/UdmfJsTest.js @@ -14,7 +14,8 @@ */ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index'; -import UDMF from '@ohos.data.UDMF'; +import UDC from '@ohos.data.unifiedDataChannel'; +import UTD from '@ohos.data.uniformTypeDescriptor'; const TEST_BUNDLE_NAME = 'MyBundleName'; const KEY_TEST_ELEMENT = 'TestKey'; @@ -35,12 +36,12 @@ describe('UdmfJSTest', function () { */ it('UdmfTextTest', 0, function () { console.info('UdmfTextTest start'); - let text = new UDMF.Text(); + let text = new UDC.Text(); text.details = { Key: 'text' + KEY_TEST_ELEMENT, Value: 'text' + VALUE_TEST_ELEMENT, }; - let unifiedData = new UDMF.UnifiedData(text); + let unifiedData = new UDC.UnifiedData(text); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('text' + KEY_TEST_ELEMENT); @@ -56,14 +57,14 @@ describe('UdmfJSTest', function () { */ it('UdmfPlainTextTest', 0, function () { console.info('UdmfPlainTextTest start'); - let plainText = new UDMF.PlainText(); + let plainText = new UDC.PlainText(); plainText.details = { Key: 'text' + KEY_TEST_ELEMENT, Value: 'text' + VALUE_TEST_ELEMENT, }; plainText.textContent = 'textContent'; plainText.abstract = 'abstract'; - let unifiedData = new UDMF.UnifiedData(plainText); + let unifiedData = new UDC.UnifiedData(plainText); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('text' + KEY_TEST_ELEMENT); @@ -81,14 +82,14 @@ describe('UdmfJSTest', function () { */ it('UdmfHyperlinkTest', 0, function () { console.info('UdmfHyperlinkTest start'); - let link = new UDMF.Hyperlink(); + let link = new UDC.Hyperlink(); link.details = { Key: 'link' + KEY_TEST_ELEMENT, Value: 'link' + VALUE_TEST_ELEMENT, }; link.url = 'url'; link.description = 'description'; - let unifiedData = new UDMF.UnifiedData(link); + let unifiedData = new UDC.UnifiedData(link); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('link' + KEY_TEST_ELEMENT); @@ -106,14 +107,14 @@ describe('UdmfJSTest', function () { */ it('UdmfHtmlTest', 0, function () { console.info('UdmfHtmlTest start'); - let html = new UDMF.HTML(); + let html = new UDC.HTML(); html.details = { Key: 'html' + KEY_TEST_ELEMENT, Value: 'html' + VALUE_TEST_ELEMENT, }; html.htmlContent = 'htmlContent'; html.plainContent = 'plainContent'; - let unifiedData = new UDMF.UnifiedData(html); + let unifiedData = new UDC.UnifiedData(html); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('html' + KEY_TEST_ELEMENT); @@ -131,13 +132,13 @@ describe('UdmfJSTest', function () { */ it('UdmfFileTest', 0, function () { console.info('UdmfFileTest start'); - let file = new UDMF.File(); + let file = new UDC.File(); file.details = { Key: 'file' + KEY_TEST_ELEMENT, Value: 'file' + VALUE_TEST_ELEMENT, }; file.uri = 'uri'; - let unifiedData = new UDMF.UnifiedData(file); + let unifiedData = new UDC.UnifiedData(file); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('file' + KEY_TEST_ELEMENT); @@ -154,13 +155,13 @@ describe('UdmfJSTest', function () { */ it('UdmfFolderTest', 0, function () { console.info('UdmfFolderTest start'); - let folder = new UDMF.Folder(); + let folder = new UDC.Folder(); folder.details = { Key: 'folder' + KEY_TEST_ELEMENT, Value: 'folder' + VALUE_TEST_ELEMENT, }; folder.uri = 'folderUri'; - let unifiedData = new UDMF.UnifiedData(folder); + let unifiedData = new UDC.UnifiedData(folder); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('folder' + KEY_TEST_ELEMENT); @@ -177,13 +178,13 @@ describe('UdmfJSTest', function () { */ it('UdmfImageTest', 0, function () { console.info('UdmfImageTest start'); - let image = new UDMF.Image(); + let image = new UDC.Image(); image.details = { Key: 'image' + KEY_TEST_ELEMENT, Value: 'image' + VALUE_TEST_ELEMENT, }; image.imageUri = 'imageUri'; - let unifiedData = new UDMF.UnifiedData(image); + let unifiedData = new UDC.UnifiedData(image); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('image' + KEY_TEST_ELEMENT); @@ -200,13 +201,13 @@ describe('UdmfJSTest', function () { */ it('UdmfVideoTest', 0, function () { console.info('UdmfVideoTest start'); - let video = new UDMF.Video(); + let video = new UDC.Video(); video.details = { Key: 'video' + KEY_TEST_ELEMENT, Value: 'video' + VALUE_TEST_ELEMENT, }; video.videoUri = 'videoUri'; - let unifiedData = new UDMF.UnifiedData(video); + let unifiedData = new UDC.UnifiedData(video); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.Key).assertEqual('video' + KEY_TEST_ELEMENT); @@ -223,13 +224,13 @@ describe('UdmfJSTest', function () { */ it('UdmfSystemDefinedRecordTest', 0, function () { console.info('UdmfSystemDefinedRecordTest start'); - let systemDefinedRecord = new UDMF.SystemDefinedRecord(); + let systemDefinedRecord = new UDC.SystemDefinedRecord(); systemDefinedRecord.details = { recordKey1: 'systemDefinedRecord' + KEY_TEST_ELEMENT, recordKey2: 1, recordKey3: U8_ARRAY, }; - let unifiedData = new UDMF.UnifiedData(systemDefinedRecord); + let unifiedData = new UDC.UnifiedData(systemDefinedRecord); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.recordKey1).assertEqual('systemDefinedRecord' + KEY_TEST_ELEMENT); @@ -248,14 +249,14 @@ describe('UdmfJSTest', function () { */ it('UdmfSystemDefinedPixelMapTest', 0, function () { console.info('UdmfSystemDefinedPixelMapTest start'); - let systemDefinedPixelMap = new UDMF.SystemDefinedPixelMap(); + let systemDefinedPixelMap = new UDC.SystemDefinedPixelMap(); systemDefinedPixelMap.details = { recordKey1: 'systemDefinedPixelMap' + KEY_TEST_ELEMENT, recordKey2: 1, recordKey3: U8_ARRAY, }; systemDefinedPixelMap.rawData = U8_ARRAY; - let unifiedData = new UDMF.UnifiedData(systemDefinedPixelMap); + let unifiedData = new UDC.UnifiedData(systemDefinedPixelMap); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.recordKey1).assertEqual('systemDefinedPixelMap' + KEY_TEST_ELEMENT); @@ -277,7 +278,7 @@ describe('UdmfJSTest', function () { */ it('UdmfSystemDefinedFormTest', 0, function () { console.info('UdmfSystemDefinedFormTest start'); - let form = new UDMF.SystemDefinedForm(); + let form = new UDC.SystemDefinedForm(); form.formId = TEST_ID; form.formName = 'MyFormName'; form.bundleName = TEST_BUNDLE_NAME; @@ -288,7 +289,7 @@ describe('UdmfJSTest', function () { formKey2: 'form' + VALUE_TEST_ELEMENT, formKey3: U8_ARRAY, }; - let unifiedData = new UDMF.UnifiedData(form); + let unifiedData = new UDC.UnifiedData(form); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.formKey1).assertEqual(1); @@ -312,7 +313,7 @@ describe('UdmfJSTest', function () { */ it('UdmfSystemDefinedAppItemTest', 0, function () { console.info('UdmfSystemDefinedAppItemTest start'); - let appItem = new UDMF.SystemDefinedAppItem(); + let appItem = new UDC.SystemDefinedAppItem(); appItem.appId = 'MyAppId'; appItem.appName = 'MyAppName'; appItem.abilityName = TEST_ABILITY_NAME; @@ -324,7 +325,7 @@ describe('UdmfJSTest', function () { appItemKey2: 'appItem' + VALUE_TEST_ELEMENT, appItemKey3: U8_ARRAY, }; - let unifiedData = new UDMF.UnifiedData(appItem); + let unifiedData = new UDC.UnifiedData(appItem); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].details.appItemKey1).assertEqual(1); @@ -349,10 +350,10 @@ describe('UdmfJSTest', function () { */ it('UdmfApplicationDefinedRecord', 0, function () { console.info('UdmfApplicationDefinedRecord start'); - let applicationDefinedRecord = new UDMF.ApplicationDefinedRecord(); + let applicationDefinedRecord = new UDC.ApplicationDefinedRecord(); applicationDefinedRecord.applicationDefinedType = 'applicationDefinedType'; applicationDefinedRecord.rawData = U8_ARRAY; - let unifiedData = new UDMF.UnifiedData(applicationDefinedRecord); + let unifiedData = new UDC.UnifiedData(applicationDefinedRecord); let records = unifiedData.getRecords(); expect(records.length).assertEqual(1); expect(records[0].applicationDefinedType).assertEqual('applicationDefinedType'); @@ -370,47 +371,45 @@ describe('UdmfJSTest', function () { */ it('UdmfAllRecordsTest', 0, function () { console.info('UdmfAllRecordsTest start'); - let text = new UDMF.Text(); - let unifiedDatas = new UDMF.UnifiedData(text); - let plainText = new UDMF.PlainText(); + let text = new UDC.Text(); + let unifiedDatas = new UDC.UnifiedData(text); + let plainText = new UDC.PlainText(); unifiedDatas.addRecord(plainText); - let link = new UDMF.Hyperlink(); + let link = new UDC.Hyperlink(); unifiedDatas.addRecord(link); - let html = new UDMF.HTML(); + let html = new UDC.HTML(); unifiedDatas.addRecord(html); - let file = new UDMF.File(); + let file = new UDC.File(); unifiedDatas.addRecord(file); - let folder = new UDMF.Folder(); + let folder = new UDC.Folder(); unifiedDatas.addRecord(folder); - let image = new UDMF.Image(); + let image = new UDC.Image(); unifiedDatas.addRecord(image); - let video = new UDMF.Video(); + let video = new UDC.Video(); unifiedDatas.addRecord(video); - let systemDefinedRecord = new UDMF.SystemDefinedRecord(); + let systemDefinedRecord = new UDC.SystemDefinedRecord(); unifiedDatas.addRecord(systemDefinedRecord); - let systemDefinedPixelMap = new UDMF.SystemDefinedPixelMap(); + let systemDefinedPixelMap = new UDC.SystemDefinedPixelMap(); unifiedDatas.addRecord(systemDefinedPixelMap); - let form = new UDMF.SystemDefinedForm(); + let form = new UDC.SystemDefinedForm(); unifiedDatas.addRecord(form); - let appItem = new UDMF.SystemDefinedAppItem(); + let appItem = new UDC.SystemDefinedAppItem(); unifiedDatas.addRecord(appItem); - let applicationDefinedRecord = new UDMF.ApplicationDefinedRecord(); + let applicationDefinedRecord = new UDC.ApplicationDefinedRecord(); unifiedDatas.addRecord(applicationDefinedRecord); let records = unifiedDatas.getRecords(); expect(records.length).assertEqual(13); - expect(records[0].getType()).assertEqual(UDMF.UnifiedDataType.TEXT); - expect(records[1].getType()).assertEqual(UDMF.UnifiedDataType.PLAIN_TEXT); - expect(records[2].getType()).assertEqual(UDMF.UnifiedDataType.HYPERLINK); - expect(records[3].getType()).assertEqual(UDMF.UnifiedDataType.HTML); - expect(records[4].getType()).assertEqual(UDMF.UnifiedDataType.FILE); - expect(records[5].getType()).assertEqual(UDMF.UnifiedDataType.FOLDER); - expect(records[6].getType()).assertEqual(UDMF.UnifiedDataType.IMAGE); - expect(records[7].getType()).assertEqual(UDMF.UnifiedDataType.VIDEO); - expect(records[8].getType()).assertEqual(UDMF.UnifiedDataType.SYSTEM_DEFINED_RECORD); - expect(records[9].getType()).assertEqual(UDMF.UnifiedDataType.SYSTEM_DEFINED_PIXEL_MAP); - expect(records[10].getType()).assertEqual(UDMF.UnifiedDataType.SYSTEM_DEFINED_FORM); - expect(records[11].getType()).assertEqual(UDMF.UnifiedDataType.SYSTEM_DEFINED_APP_ITEM); - expect(records[12].getType()).assertEqual(UDMF.UnifiedDataType.APPLICATION_DEFINED_RECORD); + expect(records[0].getType()).assertEqual(UTD.UniformDataType.TEXT); + expect(records[1].getType()).assertEqual(UTD.UniformDataType.PLAIN_TEXT); + expect(records[2].getType()).assertEqual(UTD.UniformDataType.HYPERLINK); + expect(records[3].getType()).assertEqual(UTD.UniformDataType.HTML); + expect(records[4].getType()).assertEqual(UTD.UniformDataType.FILE); + expect(records[5].getType()).assertEqual(UTD.UniformDataType.FOLDER); + expect(records[6].getType()).assertEqual(UTD.UniformDataType.IMAGE); + expect(records[7].getType()).assertEqual(UTD.UniformDataType.VIDEO); + expect(records[9].getType()).assertEqual(UTD.UniformDataType.OPENHARMONY_PIXEL_MAP); + expect(records[10].getType()).assertEqual(UTD.UniformDataType.OPENHARMONY_FORM); + expect(records[11].getType()).assertEqual(UTD.UniformDataType.OPENHARMONY_APP_ITEM); console.info('UdmfAllRecordsTest end'); }); }); \ No newline at end of file diff --git a/udmf/framework/jskitsimpl/unittest/UdmfPromiseJsTest.js b/udmf/framework/jskitsimpl/unittest/UdmfPromiseJsTest.js index d53d47e1..833e5875 100644 --- a/udmf/framework/jskitsimpl/unittest/UdmfPromiseJsTest.js +++ b/udmf/framework/jskitsimpl/unittest/UdmfPromiseJsTest.js @@ -14,7 +14,8 @@ */ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index'; -import UDMF from '@ohos.data.UDMF'; +import UDC from '@ohos.data.unifiedDataChannel'; +import UTD from '@ohos.data.uniformTypeDescriptor'; const TEXT_CONTEXT_01 = 'TextContent01'; const TEXT_CONTEXT_02 = 'TextContent02'; @@ -22,18 +23,18 @@ const ERROR_PARAMETER = '401'; describe('UdmfPromiseJSTest', function () { - let gPlainText1 = new UDMF.PlainText(); + let gPlainText1 = new UDC.PlainText(); gPlainText1.textContent = TEXT_CONTEXT_01; - let gPlainText2 = new UDMF.PlainText(); + let gPlainText2 = new UDC.PlainText(); gPlainText2.textContent = TEXT_CONTEXT_02; const optionsValid = { intention: 'DataHub', }; const optionsInValidIntention = { intention: 'Drag', }; const optionsInValidKey = { key: 'udmf://drag/com.test.demo/123456789', }; const optionsInValidAll = { intention: 'DataHub', key: 'udmf://drag/com.test.demo/123456789' }; - const unifiedData01 = new UDMF.UnifiedData(gPlainText1); - const unifiedData02 = new UDMF.UnifiedData(gPlainText2); - const unifiedDataInvalid = new UDMF.UnifiedData(); + const unifiedData01 = new UDC.UnifiedData(gPlainText1); + const unifiedData02 = new UDC.UnifiedData(gPlainText2); + const unifiedDataInvalid = new UDC.UnifiedData(); /** * @tc.name UdmfInsertPromiseInvalidOptionsTest @@ -45,7 +46,7 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfInsertPromiseInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsInValidIntention, unifiedData01).then(() => { + UDC.insertData(optionsInValidIntention, unifiedData01).then(() => { console.info(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -72,7 +73,7 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfInsertPromiseInvalidDataTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedDataInvalid).then(() => { + UDC.insertData(optionsValid, unifiedDataInvalid).then(() => { console.info(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -99,11 +100,11 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfInsertPromiseSucTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01).then((data) => { + UDC.insertData(optionsValid, unifiedData01).then((data) => { console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `query start. The options: ${JSON.stringify(options)}`); - UDMF.queryData(options).then((data) => { + UDC.queryData(options).then((data) => { console.info(TAG, 'query success.'); console.info(TAG, `data.length = ${data.length}.`); expect(data.length).assertEqual(1); @@ -112,7 +113,7 @@ describe('UdmfPromiseJSTest', function () { console.info(TAG, `records[0].getType() = ${records[0].getType()}.`); console.info(TAG, `records[0].textContent = ${records[0].textContent}.`); expect(records.length).assertEqual(1); - expect(records[0].getType()).assertEqual(UDMF.UnifiedDataType.PLAIN_TEXT); + expect(records[0].getType()).assertEqual(UTD.UniformDataType.PLAIN_TEXT); expect(records[0].textContent).assertEqual(TEXT_CONTEXT_01); done(); }).catch(() => { @@ -143,7 +144,7 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfUpdatePromiseInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.updateData(optionsInValidKey, unifiedData01).then(() => { + UDC.updateData(optionsInValidKey, unifiedData01).then(() => { console.info(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -170,11 +171,11 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfUpdatePromiseInvalidDataTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01).then((data) => { + UDC.insertData(optionsValid, unifiedData01).then((data) => { console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `query start. The options: ${JSON.stringify(options)}`); - UDMF.updateData(options, unifiedDataInvalid).then(() => { + UDC.updateData(options, unifiedDataInvalid).then(() => { console.info(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -206,18 +207,18 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfUpdatePromiseSucTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01).then((data) => { + UDC.insertData(optionsValid, unifiedData01).then((data) => { console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `query start. The options: ${JSON.stringify(options)}`); - UDMF.updateData(options, unifiedData02).then((data) => { + UDC.updateData(options, unifiedData02).then((data) => { console.info(TAG, 'update success.'); - UDMF.queryData(options).then((data) => { + UDC.queryData(options).then((data) => { console.info(TAG, 'query success.'); expect(data.length).assertEqual(1); let records = data[0].getRecords(); expect(records.length).assertEqual(1); - expect(records[0].getType()).assertEqual(UDMF.UnifiedDataType.PLAIN_TEXT); + expect(records[0].getType()).assertEqual(UTD.UniformDataType.PLAIN_TEXT); expect(records[0].textContent).assertEqual(TEXT_CONTEXT_02); done(); }).catch(() => { @@ -254,7 +255,7 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfQueryPromiseInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.queryData(optionsInValidAll).then(() => { + UDC.queryData(optionsInValidAll).then(() => { console.error(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -281,19 +282,19 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfQueryPromiseSucTest:'; console.info(TAG, 'start'); try { - UDMF.deleteData(optionsValid).then(() => { + UDC.deleteData(optionsValid).then(() => { console.info(TAG, 'delete success.'); - UDMF.queryData(optionsValid).then(() => { + UDC.queryData(optionsValid).then(() => { console.error(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); }).catch((err) => { console.info(TAG, 'query has no data.'); - UDMF.insertData(optionsValid, unifiedData01).then((data) => { + UDC.insertData(optionsValid, unifiedData01).then((data) => { console.info(TAG, `insert success. The key: ${data}`); - UDMF.insertData(optionsValid, unifiedData01).then((data) => { + UDC.insertData(optionsValid, unifiedData01).then((data) => { console.info(TAG, `insert success. The key: ${data}`); - UDMF.queryData(optionsValid).then((data) => { + UDC.queryData(optionsValid).then((data) => { console.info(TAG, 'query success.'); expect(data.length).assertEqual(2); done(); @@ -337,7 +338,7 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfDeletePromiseInvalidOptionsTest:'; console.info(TAG, 'start'); try { - UDMF.deleteData(optionsInValidAll).then(() => { + UDC.deleteData(optionsInValidAll).then(() => { console.error(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); @@ -364,21 +365,21 @@ describe('UdmfPromiseJSTest', function () { const TAG = 'UdmfDeletePromiseSucTest:'; console.info(TAG, 'start'); try { - UDMF.insertData(optionsValid, unifiedData01).then((data) => { + UDC.insertData(optionsValid, unifiedData01).then((data) => { console.info(TAG, `insert success. The key: ${data}`); let options = { key: data }; console.info(TAG, `query start. The options: ${JSON.stringify(options)}`); - UDMF.queryData(options).then((data) => { + UDC.queryData(options).then((data) => { console.info(TAG, 'query success.'); expect(data.length).assertEqual(1); - UDMF.deleteData(options).then((data) => { + UDC.deleteData(options).then((data) => { console.info(TAG, 'delete success.'); expect(data.length).assertEqual(1); let records = data[0].getRecords(); expect(records.length).assertEqual(1); - expect(records[0].getType()).assertEqual(UDMF.UnifiedDataType.PLAIN_TEXT); + expect(records[0].getType()).assertEqual(UTD.UniformDataType.PLAIN_TEXT); expect(records[0].textContent).assertEqual(TEXT_CONTEXT_01); - UDMF.queryData(options).then(() => { + UDC.queryData(options).then(() => { console.error(TAG, 'Unreachable code!'); expect(null).assertFail(); done(); diff --git a/udmf/interfaces/innerkits/common/unified_meta.h b/udmf/interfaces/innerkits/common/unified_meta.h index 8ea052f5..776400f5 100644 --- a/udmf/interfaces/innerkits/common/unified_meta.h +++ b/udmf/interfaces/innerkits/common/unified_meta.h @@ -32,19 +32,13 @@ namespace UDMF { enum UDType : int32_t { TEXT = 0, PLAIN_TEXT, - STYLED_TEXT, HYPERLINK, HTML, FILE, FOLDER, - MEDIA, IMAGE, VIDEO, AUDIO, - OFFICE, - EBOOK, - COMPRESSION, - GENERAL, SYSTEM_DEFINED_FORM, SYSTEM_DEFINED_RECORD, SYSTEM_DEFINED_APP_ITEM, @@ -54,25 +48,19 @@ enum UDType : int32_t { }; static const std::unordered_map UD_TYPE_MAP { - { TEXT, "Text" }, - { PLAIN_TEXT, "Text.PlainText" }, - { STYLED_TEXT, "Text.StyledText" }, - { HYPERLINK, "Text.Hyperlink" }, - { HTML, "Text.HTML" }, - { FILE, "File" }, - { FOLDER, "File.Folder" }, - { MEDIA, "File.Media" }, - { OFFICE, "File.Office" }, - { EBOOK, "File.Ebook" }, - { COMPRESSION, "File.Compression" }, - { GENERAL, "File.General" }, - { IMAGE, "File.Media.Image" }, - { VIDEO, "File.Media.Video" }, - { AUDIO, "File.Media.Audio" }, + { TEXT, "general.text" }, + { PLAIN_TEXT, "general.plain-text" }, + { HYPERLINK, "general.hyperlink" }, + { HTML, "general.html" }, + { FILE, "general.file" }, + { FOLDER, "general.folder" }, + { IMAGE, "general.image" }, + { VIDEO, "general.video" }, + { AUDIO, "general.audio" }, { SYSTEM_DEFINED_RECORD, "SystemDefinedType" }, - { SYSTEM_DEFINED_FORM, "SystemDefinedType.Form" }, - { SYSTEM_DEFINED_APP_ITEM, "SystemDefinedType.AppItem" }, - { SYSTEM_DEFINED_PIXEL_MAP, "SystemDefinedType.PixelMap" }, + { SYSTEM_DEFINED_FORM, "openharmony.form" }, + { SYSTEM_DEFINED_APP_ITEM, "openharmony.app-item" }, + { SYSTEM_DEFINED_PIXEL_MAP, "openharmony.pixel-map" }, { APPLICATION_DEFINED_RECORD, "ApplicationDefinedType" }, { UD_BUTT, "INVALID" } }; @@ -88,9 +76,9 @@ static const std::unordered_map JS_UD_TYPE_NAME_MAP { { AUDIO, "AUDIO" }, { FOLDER, "FOLDER" }, { SYSTEM_DEFINED_RECORD, "SYSTEM_DEFINED_RECORD" }, - { SYSTEM_DEFINED_FORM, "SYSTEM_DEFINED_FORM" }, - { SYSTEM_DEFINED_APP_ITEM, "SYSTEM_DEFINED_APP_ITEM" }, - { SYSTEM_DEFINED_PIXEL_MAP, "SYSTEM_DEFINED_PIXEL_MAP" }, + { SYSTEM_DEFINED_FORM, "OPENHARMONY_FORM" }, + { SYSTEM_DEFINED_APP_ITEM, "OPENHARMONY_APP_ITEM" }, + { SYSTEM_DEFINED_PIXEL_MAP, "OPENHARMONY_PIXEL_MAP" }, { APPLICATION_DEFINED_RECORD, "APPLICATION_DEFINED_RECORD" }, }; diff --git a/udmf/interfaces/jskits/BUILD.gn b/udmf/interfaces/jskits/BUILD.gn index a139a9dc..bf0718dc 100644 --- a/udmf/interfaces/jskits/BUILD.gn +++ b/udmf/interfaces/jskits/BUILD.gn @@ -36,11 +36,8 @@ config("udmf_napi_config") { ] } -ohos_shared_library("udmf_napi") { +ohos_shared_library("unifieddatachannel_napi") { sources = [ - "${udmf_framework_path}/jskitsimpl/common/napi_data_utils.cpp", - "${udmf_framework_path}/jskitsimpl/common/napi_error_utils.cpp", - "${udmf_framework_path}/jskitsimpl/common/napi_queue.cpp", "${udmf_framework_path}/jskitsimpl/data/application_defined_record_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/audio_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/file_napi.cpp", @@ -55,24 +52,25 @@ ohos_shared_library("udmf_napi") { "${udmf_framework_path}/jskitsimpl/data/system_defined_pixelmap_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/system_defined_record_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/text_napi.cpp", - "${udmf_framework_path}/jskitsimpl/data/udmf_napi.cpp", + "${udmf_framework_path}/jskitsimpl/data/unified_data_channel_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/unified_data_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/unified_record_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/video_napi.cpp", - "${udmf_interfaces_path}/jskits/module/udmf_napi_module.cpp", + "${udmf_interfaces_path}/jskits/module/unified_data_channel_napi_module.cpp", ] + + ldflags = [ "-Wl,--exclude-libs=ALL" ] + public_configs = [ ":udmf_napi_config" ] deps = [ "${third_party_path}/bounds_checking_function:libsec_shared", "../innerkits:udmf_client", + "../jskits:udmf_js_common", ] external_deps = [ - "ability_base:base", - "ability_runtime:ability_manager", "ability_runtime:abilitykit_native", - "ability_runtime:napi_base_context", "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", @@ -85,11 +83,36 @@ ohos_shared_library("udmf_napi") { part_name = "udmf" } +ohos_shared_library("uniformtypedescriptor_napi") { + sources = [ + "${udmf_framework_path}/jskitsimpl/data/uniform_type_descriptor_napi.cpp", + "${udmf_interfaces_path}/jskits/module/uniform_type_descriptor_napi_module.cpp", + ] + + ldflags = [ "-Wl,--exclude-libs=ALL" ] + + public_configs = [ ":udmf_napi_config" ] + + deps = [ + "${third_party_path}/bounds_checking_function:libsec_shared", + "../innerkits:udmf_client", + "../jskits:udmf_js_common", + ] + + external_deps = [ + "ability_runtime:abilitykit_native", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] + + relative_install_dir = "module/data" + subsystem_name = "distributeddatamgr" + part_name = "udmf" +} + ohos_shared_library("udmf_data_napi") { sources = [ - "${udmf_framework_path}/jskitsimpl/common/napi_data_utils.cpp", - "${udmf_framework_path}/jskitsimpl/common/napi_error_utils.cpp", - "${udmf_framework_path}/jskitsimpl/common/napi_queue.cpp", "${udmf_framework_path}/jskitsimpl/data/application_defined_record_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/audio_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/file_napi.cpp", @@ -104,24 +127,25 @@ ohos_shared_library("udmf_data_napi") { "${udmf_framework_path}/jskitsimpl/data/system_defined_pixelmap_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/system_defined_record_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/text_napi.cpp", - "${udmf_framework_path}/jskitsimpl/data/udmf_napi.cpp", + "${udmf_framework_path}/jskitsimpl/data/unified_data_channel_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/unified_data_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/unified_record_napi.cpp", "${udmf_framework_path}/jskitsimpl/data/video_napi.cpp", - "${udmf_interfaces_path}/jskits/module/udmf_napi_module.cpp", + "${udmf_interfaces_path}/jskits/module/unified_data_channel_napi_module.cpp", ] + + ldflags = [ "-Wl,--exclude-libs=ALL" ] + public_configs = [ ":udmf_napi_config" ] deps = [ "${third_party_path}/bounds_checking_function:libsec_shared", "../innerkits:udmf_client", + "../jskits:udmf_js_common", ] external_deps = [ - "ability_base:base", - "ability_runtime:ability_manager", "ability_runtime:abilitykit_native", - "ability_runtime:napi_base_context", "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", @@ -132,3 +156,25 @@ ohos_shared_library("udmf_data_napi") { subsystem_name = "distributeddatamgr" part_name = "udmf" } + +ohos_static_library("udmf_js_common") { + sources = [ + "${udmf_framework_path}/jskitsimpl/common/napi_data_utils.cpp", + "${udmf_framework_path}/jskitsimpl/common/napi_error_utils.cpp", + "${udmf_framework_path}/jskitsimpl/common/napi_queue.cpp", + ] + + ldflags = [ "-Wl,--exclude-libs=ALL" ] + cflags = [ "-fvisibility=hidden" ] + + include_dirs = [ "${udmf_interfaces_path}/jskits/common" ] + + public_configs = [ ":udmf_napi_config" ] + external_deps = [ + "ability_runtime:abilitykit_native", + "hilog:libhilog", + "napi:ace_napi", + ] + subsystem_name = "distributeddatamgr" + part_name = "udmf" +} diff --git a/udmf/interfaces/jskits/data/udmf_napi.h b/udmf/interfaces/jskits/data/unified_data_channel_napi.h similarity index 82% rename from udmf/interfaces/jskits/data/udmf_napi.h rename to udmf/interfaces/jskits/data/unified_data_channel_napi.h index 775f270c..81534559 100644 --- a/udmf/interfaces/jskits/data/udmf_napi.h +++ b/udmf/interfaces/jskits/data/unified_data_channel_napi.h @@ -23,15 +23,14 @@ namespace OHOS { namespace UDMF { -class UDMFNapi { +class UnifiedDataChannelNapi { public: - static napi_value UDMFInit(napi_env env, napi_value exports); + static napi_value UnifiedDataChannelInit(napi_env env, napi_value exports); private: - static napi_value CreateUnifiedDataType(napi_env env); static napi_value CreateIntention(napi_env env); - static napi_status SetNamedProperty( - napi_env env, napi_value &obj, const std::string &name, const std::string &value); + static napi_status SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, + const std::string &value); static napi_value InsertData(napi_env env, napi_callback_info info); static napi_value UpdateData(napi_env env, napi_callback_info info); static napi_value QueryData(napi_env env, napi_callback_info info); diff --git a/preferences/frameworks/native/include/task_executor.h b/udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h similarity index 54% rename from preferences/frameworks/native/include/task_executor.h rename to udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h index 38b44a65..3553fcfb 100644 --- a/preferences/frameworks/native/include/task_executor.h +++ b/udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h @@ -12,24 +12,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef PREFERENCES_TASK_EXECUTOR_H -#define PREFERENCES_TASK_EXECUTOR_H -#include -#include "task_scheduler.h" +#ifndef UNIFORM_TYPE_DESCRIPTOR_NAPI_H +#define UNIFORM_TYPE_DESCRIPTOR_NAPI_H + +#include + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + namespace OHOS { -namespace NativePreferences { -class TaskExecutor { +namespace UDMF { +class UniformTypeDescriptorNapi { public: - API_LOCAL static TaskExecutor &GetInstance(); - API_LOCAL bool Execute(TaskScheduler::Task &&task); + static napi_value UniformTypeDescriptorInit(napi_env env, napi_value exports); private: - TaskExecutor(); - ~TaskExecutor(); - - std::shared_ptr pool_; + static napi_value CreateUniformDataType(napi_env env); + static napi_status SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, + const std::string &value); }; -} // namespace NativePreferences -} // namespace OHOS -#endif // PREFERENCES_TASK_EXECUTOR_H +} +} +#endif // UNIFORM_TYPE_DESCRIPTOR_NAPI_H diff --git a/udmf/interfaces/jskits/module/udmf_napi_module.cpp b/udmf/interfaces/jskits/module/unified_data_channel_napi_module.cpp similarity index 83% rename from udmf/interfaces/jskits/module/udmf_napi_module.cpp rename to udmf/interfaces/jskits/module/unified_data_channel_napi_module.cpp index fdc5c41d..9dc22484 100644 --- a/udmf/interfaces/jskits/module/udmf_napi_module.cpp +++ b/udmf/interfaces/jskits/module/unified_data_channel_napi_module.cpp @@ -1,17 +1,17 @@ /* - * 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. - */ +* 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 "application_defined_record_napi.h" #include "audio_napi.h" @@ -22,13 +22,13 @@ #include "link_napi.h" #include "logger.h" #include "plain_text_napi.h" +#include "unified_data_channel_napi.h" #include "summary_napi.h" #include "system_defined_appitem_napi.h" #include "system_defined_form_napi.h" #include "system_defined_pixelmap_napi.h" #include "system_defined_record_napi.h" #include "text_napi.h" -#include "udmf_napi.h" #include "unified_data_napi.h" #include "unified_record_napi.h" #include "video_napi.h" @@ -38,7 +38,7 @@ using namespace OHOS::UDMF; EXTERN_C_START static napi_value Init(napi_env env, napi_value exports) { - OHOS::UDMF::UDMFNapi::UDMFInit(env, exports); + OHOS::UDMF::UnifiedDataChannelNapi::UnifiedDataChannelInit(env, exports); napi_status status = napi_set_named_property(env, exports, "UnifiedData", OHOS::UDMF::UnifiedDataNapi::Constructor(env)); @@ -88,11 +88,12 @@ static napi_module _module = { .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, - .nm_modname = "data.UDMF", + .nm_modname = "data.unifiedDataChannel", .nm_priv = ((void *)0), .reserved = { 0 } }; extern "C" __attribute__((constructor)) void RegisterUDMFUnifiedDataModule(void) { napi_module_register(&_module); + LOG_INFO(UDMF_KITS_NAPI, "module register data.unifiedDataChannel"); } diff --git a/udmf/interfaces/jskits/module/uniform_type_descriptor_napi_module.cpp b/udmf/interfaces/jskits/module/uniform_type_descriptor_napi_module.cpp new file mode 100644 index 00000000..47a2ba3e --- /dev/null +++ b/udmf/interfaces/jskits/module/uniform_type_descriptor_napi_module.cpp @@ -0,0 +1,41 @@ +/* + * 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 "logger.h" +#include "uniform_type_descriptor_napi.h" + +using namespace OHOS::UDMF; + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) +{ + OHOS::UDMF::UniformTypeDescriptorNapi::UniformTypeDescriptorInit(env, exports); + return exports; +} +EXTERN_C_END + +static napi_module _module = { .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "data.uniformTypeDescriptor", + .nm_priv = ((void *)0), + .reserved = { 0 } }; + +extern "C" __attribute__((constructor)) void RegisterUDMFUnifiedDataModule(void) +{ + napi_module_register(&_module); + LOG_INFO(UDMF_KITS_NAPI, "module register data.uniformTypeDescriptor"); +} -- Gitee