From 58c353ba4fe7065a358f80414e79ee4bdf952374 Mon Sep 17 00:00:00 2001 From: PaDaBoo Date: Fri, 29 Jul 2022 12:23:38 +0800 Subject: [PATCH] =?UTF-8?q?appdatamgr=E5=88=86=E4=BB=93relational=5Fstore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: PaDaBoo --- OAT.xml | 66 - README.md | 110 -- README_zh.md | 55 +- appdatamgr.gni | 16 - relational_store/bundle.json => bundle.json | 0 data_share/README_zh.md | 52 - data_share/bundle.json | 113 -- data_share/datashare.gni | 38 - data_share/figures/zh-cn_dataShare.png | Bin 32504 -> 0 bytes data_share/frameworks/js/napi/BUILD.gn | 24 - .../napi/common/include/datashare_js_utils.h | 55 - .../include/datashare_predicates_proxy.h | 84 - .../include/datashare_result_set_proxy.h | 68 - .../include/napi_datashare_values_bucket.h | 31 - .../js/napi/common/src/datashare_js_utils.cpp | 259 --- .../common/src/datashare_predicates_proxy.cpp | 863 ---------- .../common/src/datashare_result_set_proxy.cpp | 492 ------ .../src/napi_datashare_values_bucket.cpp | 133 -- .../frameworks/js/napi/dataShare/BUILD.gn | 91 -- .../js/napi/dataShare/include/async_call.h | 105 -- .../dataShare/include/data_share_common.h | 52 - .../dataShare/include/napi_datashare_helper.h | 88 - .../include/napi_datashare_observer.h | 45 - .../js/napi/dataShare/src/async_call.cpp | 145 -- .../dataShare/src/napi_datashare_helper.cpp | 753 --------- .../dataShare/src/napi_datashare_observer.cpp | 85 - .../dataShare/src/native_datashare_module.cpp | 61 - .../native_datashare_predicates_module.cpp | 58 - .../js/napi/datashare_ext_ability/BUILD.gn | 50 - .../datashare_ext_ability.js | 66 - .../datashare_ext_ability_module.cpp | 57 - .../datashare_ext_ability_context/BUILD.gn | 51 - .../datashare_ext_ability_context.js | 24 - .../datashare_ext_ability_context_module.cpp | 57 - .../common/include/datashare_abs_result_set.h | 65 - .../include/datashare_block_writer_impl.h | 155 -- .../native/common/include/datashare_log.h | 46 - .../common/include/datashare_operation.h | 166 -- .../include/datashare_operation_builder.h | 99 -- .../native/common/include/datashare_result.h | 106 -- .../include/datashare_shared_result_set.h | 44 - .../common/include/datashare_string_utils.h | 42 - .../native/common/include/idatashare.h | 221 --- .../common/include/ishared_result_set.h | 67 - .../common/include/ishared_result_set_proxy.h | 38 - .../common/include/ishared_result_set_stub.h | 68 - .../native/common/include/result_set.h | 229 --- .../common/src/datashare_abs_result_set.cpp | 240 --- .../src/datashare_block_writer_impl.cpp | 211 --- .../native/common/src/datashare_operation.cpp | 482 ------ .../src/datashare_operation_builder.cpp | 154 -- .../common/src/datashare_predicates.cpp | 559 ------- .../src/datashare_predicates_object.cpp | 358 ----- .../native/common/src/datashare_result.cpp | 180 --- .../common/src/datashare_result_set.cpp | 426 ----- .../common/src/datashare_string_utils.cpp | 51 - .../common/src/datashare_value_object.cpp | 167 -- .../common/src/datashare_values_bucket.cpp | 123 -- .../native/common/src/ishared_result_set.cpp | 29 - .../common/src/ishared_result_set_proxy.cpp | 128 -- .../common/src/ishared_result_set_stub.cpp | 142 -- .../consumer/include/datashare_connection.h | 95 -- .../native/consumer/include/datashare_proxy.h | 69 - .../consumer/src/datashare_connection.cpp | 118 -- .../native/consumer/src/datashare_helper.cpp | 826 ---------- .../native/consumer/src/datashare_proxy.cpp | 580 ------- .../provider/include/datashare_ext_ability.h | 240 --- .../include/datashare_ext_ability_context.h | 44 - .../datashare_ext_ability_module_loader.h | 37 - .../native/provider/include/datashare_stub.h | 54 - .../provider/include/datashare_stub_impl.h | 81 - .../provider/include/datashare_uv_queue.h | 58 - .../include/js_datashare_ext_ability.h | 320 ---- .../js_datashare_ext_ability_context.h | 33 - .../provider/src/datashare_ext_ability.cpp | 177 --- .../src/datashare_ext_ability_context.cpp | 25 - .../datashare_ext_ability_module_loader.cpp | 38 - .../native/provider/src/datashare_stub.cpp | 418 ----- .../provider/src/datashare_stub_impl.cpp | 382 ----- .../provider/src/datashare_uv_queue.cpp | 116 -- .../provider/src/js_datashare_ext_ability.cpp | 831 ---------- .../src/js_datashare_ext_ability_context.cpp | 62 - data_share/interfaces/inner_api/BUILD.gn | 126 -- .../interfaces/inner_api/common/BUILD.gn | 73 - .../common/include/datashare_abs_predicates.h | 74 - .../common/include/datashare_errno.h | 70 - .../common/include/datashare_predicates.h | 88 - .../common/include/datashare_predicates_def.h | 90 -- .../include/datashare_predicates_object.h | 117 -- .../common/include/datashare_value_object.h | 107 -- .../common/include/datashare_values_bucket.h | 58 - .../consumer/include/datashare_helper.h | 269 ---- .../consumer/include/datashare_result_set.h | 81 - .../provider/include/result_set_bridge.h | 84 - .../en-us_How_RDB_works.png | Bin .../zh-cn_关系型数据库运作机制.png | Bin .../js/napi/common/include/js_ability.h | 0 .../js/napi/common/include/js_logger.h | 0 .../js/napi/common/include/js_utils.h | 0 .../js/napi/common/include/napi_async_proxy.h | 0 .../js/napi/common/src/js_ability.cpp | 0 .../js/napi/common/src/js_utils.cpp | 0 .../js/napi/dataability/BUILD.gn | 0 .../include/napi_data_ability_predicates.h | 0 .../include/napi_predicates_utils.h | 0 .../js/napi/dataability/src/entry_point.cpp | 0 .../src/napi_data_ability_predicates.cpp | 0 .../dataability/src/napi_predicates_utils.cpp | 0 .../js/napi/rdb/BUILD.gn | 0 .../rdb/include/napi_rdb_const_properties.h | 0 .../js/napi/rdb/include/napi_rdb_predicates.h | 0 .../js/napi/rdb/include/napi_rdb_store.h | 0 .../napi/rdb/include/napi_rdb_store_helper.h | 0 .../rdb/include/napi_rdb_store_observer.h | 0 .../js/napi/rdb/include/napi_result_set.h | 0 .../js/napi/rdb/include/napi_uv_queue.h | 0 .../js/napi/rdb/include/napi_values_bucket.h | 0 .../js/napi/rdb/src/entry_point.cpp | 0 .../rdb/src/napi_rdb_const_properties.cpp | 0 .../js/napi/rdb/src/napi_rdb_predicates.cpp | 0 .../js/napi/rdb/src/napi_rdb_store.cpp | 0 .../js/napi/rdb/src/napi_rdb_store_helper.cpp | 0 .../napi/rdb/src/napi_rdb_store_observer.cpp | 0 .../js/napi/rdb/src/napi_result_set.cpp | 0 .../js/napi/rdb/src/napi_uv_queue.cpp | 0 .../js/napi/rdb/src/napi_values_bucket.cpp | 0 .../native/appdatafwk/src/shared_block.cpp | 0 .../src/data_ability_predicates.cpp | 0 .../dataability/src/ishared_result_set.cpp | 0 .../src/ishared_result_set_proxy.cpp | 0 .../src/ishared_result_set_proxy.h | 0 .../src/ishared_result_set_stub.cpp | 0 .../dataability/src/ishared_result_set_stub.h | 0 .../native/dataability/src/logger.h | 0 .../dataability/src/predicates_utils.cpp | 0 .../native/rdb/include/base_transaction.h | 0 .../native/rdb/include/rdb_store_impl.h | 0 .../native/rdb/include/share_block.h | 0 .../include/shared_block_serializer_info.h | 0 .../native/rdb/include/sqlite_config.h | 0 .../native/rdb/include/sqlite_connection.h | 0 .../rdb/include/sqlite_connection_pool.h | 0 .../native/rdb/include/sqlite_errno.h | 0 .../native/rdb/include/sqlite_global_config.h | 0 .../rdb/include/sqlite_shared_result_set.h | 0 .../native/rdb/include/sqlite_sql_builder.h | 0 .../native/rdb/include/sqlite_statement.h | 0 .../native/rdb/include/sqlite_utils.h | 0 .../native/rdb/include/step_result_set.h | 0 .../native/rdb/include/store_session.h | 0 .../native/rdb/include/string_utils.h | 0 .../native/rdb/src/abs_predicates.cpp | 0 .../native/rdb/src/abs_rdb_predicates.cpp | 0 .../native/rdb/src/abs_result_set.cpp | 0 .../native/rdb/src/abs_shared_result_set.cpp | 0 .../native/rdb/src/base_transaction.cpp | 0 .../native/rdb/src/logger.h | 0 .../native/rdb/src/rdb_helper.cpp | 0 .../native/rdb/src/rdb_predicates.cpp | 0 .../native/rdb/src/rdb_store_config.cpp | 0 .../native/rdb/src/rdb_store_impl.cpp | 0 .../native/rdb/src/share_block.cpp | 0 .../rdb/src/shared_block_serializer_info.cpp | 0 .../native/rdb/src/sqlite_config.cpp | 0 .../native/rdb/src/sqlite_connection.cpp | 0 .../native/rdb/src/sqlite_connection_pool.cpp | 0 .../native/rdb/src/sqlite_database_utils.cpp | 0 .../native/rdb/src/sqlite_global_config.cpp | 0 .../rdb/src/sqlite_shared_result_set.cpp | 0 .../native/rdb/src/sqlite_sql_builder.cpp | 0 .../native/rdb/src/sqlite_statement.cpp | 0 .../native/rdb/src/sqlite_utils.cpp | 0 .../native/rdb/src/step_result_set.cpp | 0 .../native/rdb/src/store_session.cpp | 0 .../native/rdb/src/string_utils.cpp | 0 .../native/rdb/src/value_object.cpp | 0 .../native/rdb/src/values_bucket.cpp | 0 .../src/rdb_result_set_bridge.cpp | 0 .../rdb_data_share_adapter/src/rdb_utils.cpp | 0 .../inner_api/appdatafwk/BUILD.gn | 0 .../inner_api/appdatafwk/include/logger.h | 0 .../appdatafwk/include/shared_block.h | 0 .../inner_api/dataability/BUILD.gn | 0 .../include/data_ability_predicates.h | 0 .../dataability/include/ishared_result_set.h | 0 .../dataability/include/predicates_utils.h | 0 .../inner_api/rdb/BUILD.gn | 0 .../inner_api/rdb/include/abs_predicates.h | 0 .../rdb/include/abs_rdb_predicates.h | 0 .../inner_api/rdb/include/abs_result_set.h | 0 .../rdb/include/abs_shared_result_set.h | 0 .../inner_api/rdb/include/rdb_errno.h | 0 .../inner_api/rdb/include/rdb_helper.h | 0 .../inner_api/rdb/include/rdb_open_callback.h | 0 .../inner_api/rdb/include/rdb_predicates.h | 0 .../inner_api/rdb/include/rdb_store.h | 0 .../inner_api/rdb/include/rdb_store_config.h | 0 .../inner_api/rdb/include/result_set.h | 0 .../inner_api/rdb/include/shared_result_set.h | 0 .../rdb/include/sqlite_database_utils.h | 0 .../rdb/include/transaction_observer.h | 0 .../inner_api/rdb/include/value_object.h | 0 .../inner_api/rdb/include/values_bucket.h | 0 .../inner_api/rdb_data_share_adapter/BUILD.gn | 0 .../include/rdb_logger.h | 0 .../include/rdb_result_set_bridge.h | 0 .../include/rdb_utils.h | 0 kv_store/README_zh.md | 39 - kv_store/bundle.json | 36 - .../native/dbm_kv_store/inc/dbm_def.h | 74 - .../src/kv_store_impl_hal/dbm_kv_store.c | 1413 ----------------- .../src/kv_store_impl_posix/dbm_kv_store.c | 54 - .../src/kvstore_common/kvstore_common.c | 198 --- .../src/kvstore_common/kvstore_common.h | 43 - .../kv_store/src/kvstore_impl_hal/kv_store.c | 172 -- .../src/kvstore_impl_posix/kv_store.c | 320 ---- .../inner_api/dbm_kv_store/BUILD.gn | 39 - .../dbm_kv_store/include/dbm_config.h | 54 - .../dbm_kv_store/include/dbm_errno.h | 39 - .../dbm_kv_store/include/dbm_kv_store.h | 71 - .../dbm_kv_store/include/dbm_kv_store_env.h | 33 - .../interfaces/inner_api/kv_store/BUILD.gn | 60 - .../inner_api/kv_store/include/kvstore_env.h | 33 - kv_store/kv_store.gni | 18 - preferences/README_zh.md | 55 - preferences/bundle.json | 92 -- ...-us_How_the_preferences_database_works.png | Bin 42340 -> 0 bytes .../figures/zh-cn_首选项运行机制.png | Bin 13287 -> 0 bytes preferences/frameworks/js/napi/BUILD.gn | 108 -- .../js/napi/include/napi_preferences.h | 69 - .../js/napi/include/napi_preferences_helper.h | 27 - .../frameworks/js/napi/include/napi_storage.h | 74 - .../js/napi/include/napi_storage_helper.h | 27 - .../js/napi/include/napi_system_storage.h | 27 - .../frameworks/js/napi/src/entry_point.cpp | 51 - .../js/napi/src/entry_point_storage.cpp | 53 - .../napi/src/entry_point_system_storage.cpp | 46 - .../js/napi/src/napi_preferences.cpp | 625 -------- .../js/napi/src/napi_preferences_helper.cpp | 141 -- .../frameworks/js/napi/src/napi_storage.cpp | 589 ------- .../js/napi/src/napi_storage_helper.cpp | 201 --- .../js/napi/src/napi_system_storage.cpp | 283 ---- .../frameworks/native/include/logger.h | 33 - .../native/include/preferences_impl.h | 215 --- .../frameworks/native/include/task_pool.h | 89 -- .../frameworks/native/include/task_queue.h | 42 - .../native/src/preferences_helper.cpp | 154 -- .../native/src/preferences_impl.cpp | 571 ------- .../native/src/preferences_observer.cpp | 24 - .../native/src/preferences_value.cpp | 199 --- .../native/src/preferences_xml_utils.cpp | 390 ----- .../frameworks/native/src/task_pool.cpp | 310 ---- .../frameworks/native/src/task_queue.cpp | 78 - preferences/interfaces/inner_api/BUILD.gn | 52 - .../inner_api/include/preferences.h | 85 - .../inner_api/include/preferences_errno.h | 46 - .../inner_api/include/preferences_helper.h | 42 - .../inner_api/include/preferences_observer.h | 31 - .../inner_api/include/preferences_value.h | 76 - .../inner_api/include/preferences_xml_utils.h | 51 - preferences/preferences.gni | 20 - preferences/test/js/unittest/src/BUILD.gn | 29 - .../src/PreferencesCallBackJsunit.test.js | 416 ----- .../src/PreferencesHelperJsunit.test.js | 147 -- .../src/PreferencesPromiseJsunit.test.js | 452 ------ .../src/StorageCallBackJsunit.test.js | 306 ---- .../unittest/src/StorageHelperJsunit.test.js | 134 -- .../unittest/src/StoragePromiseJsunit.test.js | 326 ---- .../js/unittest/src/StorageSyncJsunit.test.js | 289 ---- .../unittest/src/SystemStorageJsunit.test.js | 514 ------ preferences/test/native/BUILD.gn | 53 - .../native/unittest/preferences_file_test.cpp | 301 ---- .../unittest/preferences_helper_test.cpp | 81 - .../test/native/unittest/preferences_test.cpp | 706 -------- ...lational_store.gni => relational_store.gni | 0 relational_store/README_zh.md | 54 - relational_store/test/js/rdb/BUILD.gn | 23 - .../test/js/rdb/unittest/src/config.json | 60 - .../test/js => test/js/dataability}/BUILD.gn | 0 .../js/dataability/unittest/src/BUILD.gn | 0 .../src/DataAbilityPredicatesJsunit.test.js | 0 .../js/dataability}/unittest/src/config.json | 0 .../js/dataability => test/js/rdb}/BUILD.gn | 0 .../js/rdb/unittest/src/BUILD.gn | 0 .../src/RdbStoreDataShareJsunit.test.js | 0 .../src/RdbStoreDistributedJsunit.test.js | 0 .../src/RdbStoreResultSetJsunit.test.js | 0 ...reBackupRestoreWithFAContextJsunit.test.js | 0 .../RdbstoreChangeEncryptKeyJsunit.test.js | 0 ...oreCreateDeleteWithFAContextJsunit.test.js | 0 .../unittest/src/RdbstoreDeleteJsunit.test.js | 0 .../unittest/src/RdbstoreInsertJsunit.test.js | 0 .../src/RdbstorePredicatesJoinJsunit.test.js | 0 .../src/RdbstorePredicatesJsunit.test.js | 0 .../src/RdbstoreRdbstoreJsunit.test.js | 0 .../src/RdbstoreStoreExcuteSqlJsunit.test.js | 0 .../src/RdbstoreTransactionJsunit.test.js | 0 .../unittest/src/RdbstoreUpdateJsunit.test.js | 0 .../js/rdb}/unittest/src/config.json | 0 .../test => test}/native/dataability/BUILD.gn | 0 .../unittest/data_ability_predicates_test.cpp | 0 .../test => test}/native/rdb/BUILD.gn | 0 .../rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn | 0 .../rdb/fuzztest/rdbimpl_fuzzer/corpus/init | 0 .../rdb/fuzztest/rdbimpl_fuzzer/project.xml | 0 .../rdbimpl_fuzzer/rdbimpl_fuzzer.cpp | 0 .../fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.h | 0 .../native/rdb/unittest/common.h | 0 .../native/rdb/unittest/logger.h | 0 .../native/rdb/unittest/rdb_attach_test.cpp | 0 .../native/rdb/unittest/rdb_delete_test.cpp | 0 .../rdb/unittest/rdb_distributed_test.cpp | 0 .../native/rdb/unittest/rdb_encrypt_test.cpp | 0 .../native/rdb/unittest/rdb_execute_test.cpp | 0 .../native/rdb/unittest/rdb_helper_test.cpp | 0 .../native/rdb/unittest/rdb_insert_test.cpp | 0 .../rdb/unittest/rdb_open_callback_test.cpp | 0 .../rdb/unittest/rdb_predicates_join_test.cpp | 0 .../rdb/unittest/rdb_predicates_test.cpp | 0 .../rdb_sqlite_shared_result_set_test.cpp | 0 .../rdb/unittest/rdb_step_result_set_test.cpp | 0 .../unittest/rdb_store_concurrent_test.cpp | 0 .../rdb/unittest/rdb_store_config_test.cpp | 0 .../rdb/unittest/rdb_store_interface_test.cpp | 0 .../rdb/unittest/rdb_transaction_test.cpp | 0 .../native/rdb/unittest/rdb_update_test.cpp | 0 .../native/rdb/unittest/rdb_upgrade_test.cpp | 0 .../rdb/unittest/rdb_value_bucket_test.cpp | 0 .../native/rdb_data_share_adapter/BUILD.gn | 0 .../unittest/rdb_data_share_adapter_test.cpp | 0 330 files changed, 40 insertions(+), 26207 deletions(-) delete mode 100644 OAT.xml delete mode 100644 README.md delete mode 100644 appdatamgr.gni rename relational_store/bundle.json => bundle.json (100%) delete mode 100644 data_share/README_zh.md delete mode 100644 data_share/bundle.json delete mode 100644 data_share/datashare.gni delete mode 100644 data_share/figures/zh-cn_dataShare.png delete mode 100644 data_share/frameworks/js/napi/BUILD.gn delete mode 100644 data_share/frameworks/js/napi/common/include/datashare_js_utils.h delete mode 100644 data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h delete mode 100644 data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h delete mode 100644 data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h delete mode 100644 data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp delete mode 100644 data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp delete mode 100644 data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp delete mode 100644 data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp delete mode 100644 data_share/frameworks/js/napi/dataShare/BUILD.gn delete mode 100644 data_share/frameworks/js/napi/dataShare/include/async_call.h delete mode 100644 data_share/frameworks/js/napi/dataShare/include/data_share_common.h delete mode 100644 data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h delete mode 100644 data_share/frameworks/js/napi/dataShare/include/napi_datashare_observer.h delete mode 100644 data_share/frameworks/js/napi/dataShare/src/async_call.cpp delete mode 100644 data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp delete mode 100644 data_share/frameworks/js/napi/dataShare/src/napi_datashare_observer.cpp delete mode 100644 data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp delete mode 100644 data_share/frameworks/js/napi/dataShare/src/native_datashare_predicates_module.cpp delete mode 100644 data_share/frameworks/js/napi/datashare_ext_ability/BUILD.gn delete mode 100644 data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability.js delete mode 100644 data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability_module.cpp delete mode 100644 data_share/frameworks/js/napi/datashare_ext_ability_context/BUILD.gn delete mode 100644 data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context.js delete mode 100644 data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp delete mode 100644 data_share/frameworks/native/common/include/datashare_abs_result_set.h delete mode 100644 data_share/frameworks/native/common/include/datashare_block_writer_impl.h delete mode 100644 data_share/frameworks/native/common/include/datashare_log.h delete mode 100644 data_share/frameworks/native/common/include/datashare_operation.h delete mode 100644 data_share/frameworks/native/common/include/datashare_operation_builder.h delete mode 100644 data_share/frameworks/native/common/include/datashare_result.h delete mode 100644 data_share/frameworks/native/common/include/datashare_shared_result_set.h delete mode 100644 data_share/frameworks/native/common/include/datashare_string_utils.h delete mode 100644 data_share/frameworks/native/common/include/idatashare.h delete mode 100644 data_share/frameworks/native/common/include/ishared_result_set.h delete mode 100644 data_share/frameworks/native/common/include/ishared_result_set_proxy.h delete mode 100644 data_share/frameworks/native/common/include/ishared_result_set_stub.h delete mode 100644 data_share/frameworks/native/common/include/result_set.h delete mode 100644 data_share/frameworks/native/common/src/datashare_abs_result_set.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_operation.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_operation_builder.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_predicates.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_predicates_object.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_result.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_result_set.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_string_utils.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_value_object.cpp delete mode 100644 data_share/frameworks/native/common/src/datashare_values_bucket.cpp delete mode 100644 data_share/frameworks/native/common/src/ishared_result_set.cpp delete mode 100644 data_share/frameworks/native/common/src/ishared_result_set_proxy.cpp delete mode 100644 data_share/frameworks/native/common/src/ishared_result_set_stub.cpp delete mode 100644 data_share/frameworks/native/consumer/include/datashare_connection.h delete mode 100644 data_share/frameworks/native/consumer/include/datashare_proxy.h delete mode 100644 data_share/frameworks/native/consumer/src/datashare_connection.cpp delete mode 100644 data_share/frameworks/native/consumer/src/datashare_helper.cpp delete mode 100644 data_share/frameworks/native/consumer/src/datashare_proxy.cpp delete mode 100644 data_share/frameworks/native/provider/include/datashare_ext_ability.h delete mode 100644 data_share/frameworks/native/provider/include/datashare_ext_ability_context.h delete mode 100644 data_share/frameworks/native/provider/include/datashare_ext_ability_module_loader.h delete mode 100644 data_share/frameworks/native/provider/include/datashare_stub.h delete mode 100644 data_share/frameworks/native/provider/include/datashare_stub_impl.h delete mode 100644 data_share/frameworks/native/provider/include/datashare_uv_queue.h delete mode 100644 data_share/frameworks/native/provider/include/js_datashare_ext_ability.h delete mode 100644 data_share/frameworks/native/provider/include/js_datashare_ext_ability_context.h delete mode 100644 data_share/frameworks/native/provider/src/datashare_ext_ability.cpp delete mode 100644 data_share/frameworks/native/provider/src/datashare_ext_ability_context.cpp delete mode 100644 data_share/frameworks/native/provider/src/datashare_ext_ability_module_loader.cpp delete mode 100644 data_share/frameworks/native/provider/src/datashare_stub.cpp delete mode 100644 data_share/frameworks/native/provider/src/datashare_stub_impl.cpp delete mode 100644 data_share/frameworks/native/provider/src/datashare_uv_queue.cpp delete mode 100644 data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp delete mode 100644 data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp delete mode 100644 data_share/interfaces/inner_api/BUILD.gn delete mode 100644 data_share/interfaces/inner_api/common/BUILD.gn delete mode 100644 data_share/interfaces/inner_api/common/include/datashare_abs_predicates.h delete mode 100644 data_share/interfaces/inner_api/common/include/datashare_errno.h delete mode 100644 data_share/interfaces/inner_api/common/include/datashare_predicates.h delete mode 100644 data_share/interfaces/inner_api/common/include/datashare_predicates_def.h delete mode 100644 data_share/interfaces/inner_api/common/include/datashare_predicates_object.h delete mode 100644 data_share/interfaces/inner_api/common/include/datashare_value_object.h delete mode 100644 data_share/interfaces/inner_api/common/include/datashare_values_bucket.h delete mode 100644 data_share/interfaces/inner_api/consumer/include/datashare_helper.h delete mode 100644 data_share/interfaces/inner_api/consumer/include/datashare_result_set.h delete mode 100644 data_share/interfaces/inner_api/provider/include/result_set_bridge.h rename {relational_store/figures => figures}/en-us_How_RDB_works.png (100%) rename {relational_store/figures => figures}/zh-cn_关系型数据库运作机制.png (100%) rename {relational_store/frameworks => frameworks}/js/napi/common/include/js_ability.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/common/include/js_logger.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/common/include/js_utils.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/common/include/napi_async_proxy.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/common/src/js_ability.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/common/src/js_utils.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/dataability/BUILD.gn (100%) rename {relational_store/frameworks => frameworks}/js/napi/dataability/include/napi_data_ability_predicates.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/dataability/include/napi_predicates_utils.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/dataability/src/entry_point.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/dataability/src/napi_data_ability_predicates.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/dataability/src/napi_predicates_utils.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/BUILD.gn (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_rdb_const_properties.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_rdb_predicates.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_rdb_store.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_rdb_store_helper.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_rdb_store_observer.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_result_set.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_uv_queue.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/include/napi_values_bucket.h (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/entry_point.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_rdb_const_properties.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_rdb_predicates.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_rdb_store.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_rdb_store_helper.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_rdb_store_observer.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_result_set.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_uv_queue.cpp (100%) rename {relational_store/frameworks => frameworks}/js/napi/rdb/src/napi_values_bucket.cpp (100%) rename {relational_store/frameworks => frameworks}/native/appdatafwk/src/shared_block.cpp (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/data_ability_predicates.cpp (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/ishared_result_set.cpp (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/ishared_result_set_proxy.cpp (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/ishared_result_set_proxy.h (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/ishared_result_set_stub.cpp (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/ishared_result_set_stub.h (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/logger.h (100%) rename {relational_store/frameworks => frameworks}/native/dataability/src/predicates_utils.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/base_transaction.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/rdb_store_impl.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/share_block.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/shared_block_serializer_info.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_config.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_connection.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_connection_pool.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_errno.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_global_config.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_shared_result_set.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_sql_builder.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_statement.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/sqlite_utils.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/step_result_set.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/store_session.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/include/string_utils.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/abs_predicates.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/abs_rdb_predicates.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/abs_result_set.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/abs_shared_result_set.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/base_transaction.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/logger.h (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/rdb_helper.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/rdb_predicates.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/rdb_store_config.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/rdb_store_impl.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/share_block.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/shared_block_serializer_info.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_config.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_connection.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_connection_pool.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_database_utils.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_global_config.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_shared_result_set.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_sql_builder.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_statement.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/sqlite_utils.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/step_result_set.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/store_session.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/string_utils.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/value_object.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb/src/values_bucket.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb_data_share_adapter/src/rdb_result_set_bridge.cpp (100%) rename {relational_store/frameworks => frameworks}/native/rdb_data_share_adapter/src/rdb_utils.cpp (100%) rename {relational_store/interfaces => interfaces}/inner_api/appdatafwk/BUILD.gn (100%) rename {relational_store/interfaces => interfaces}/inner_api/appdatafwk/include/logger.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/appdatafwk/include/shared_block.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/dataability/BUILD.gn (100%) rename {relational_store/interfaces => interfaces}/inner_api/dataability/include/data_ability_predicates.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/dataability/include/ishared_result_set.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/dataability/include/predicates_utils.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/BUILD.gn (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/abs_predicates.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/abs_rdb_predicates.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/abs_result_set.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/abs_shared_result_set.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/rdb_errno.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/rdb_helper.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/rdb_open_callback.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/rdb_predicates.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/rdb_store.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/rdb_store_config.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/result_set.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/shared_result_set.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/sqlite_database_utils.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/transaction_observer.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/value_object.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb/include/values_bucket.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb_data_share_adapter/BUILD.gn (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb_data_share_adapter/include/rdb_logger.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h (100%) rename {relational_store/interfaces => interfaces}/inner_api/rdb_data_share_adapter/include/rdb_utils.h (100%) delete mode 100644 kv_store/README_zh.md delete mode 100644 kv_store/bundle.json delete mode 100644 kv_store/frameworks/native/dbm_kv_store/inc/dbm_def.h delete mode 100644 kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_hal/dbm_kv_store.c delete mode 100644 kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_posix/dbm_kv_store.c delete mode 100644 kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.c delete mode 100644 kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.h delete mode 100644 kv_store/frameworks/native/kv_store/src/kvstore_impl_hal/kv_store.c delete mode 100644 kv_store/frameworks/native/kv_store/src/kvstore_impl_posix/kv_store.c delete mode 100644 kv_store/interfaces/inner_api/dbm_kv_store/BUILD.gn delete mode 100644 kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_config.h delete mode 100644 kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_errno.h delete mode 100644 kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store.h delete mode 100644 kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store_env.h delete mode 100644 kv_store/interfaces/inner_api/kv_store/BUILD.gn delete mode 100644 kv_store/interfaces/inner_api/kv_store/include/kvstore_env.h delete mode 100644 kv_store/kv_store.gni delete mode 100644 preferences/README_zh.md delete mode 100644 preferences/bundle.json delete mode 100644 preferences/figures/en-us_How_the_preferences_database_works.png delete mode 100644 preferences/figures/zh-cn_首选项运行机制.png delete mode 100644 preferences/frameworks/js/napi/BUILD.gn delete mode 100644 preferences/frameworks/js/napi/include/napi_preferences.h delete mode 100644 preferences/frameworks/js/napi/include/napi_preferences_helper.h delete mode 100644 preferences/frameworks/js/napi/include/napi_storage.h delete mode 100644 preferences/frameworks/js/napi/include/napi_storage_helper.h delete mode 100644 preferences/frameworks/js/napi/include/napi_system_storage.h delete mode 100644 preferences/frameworks/js/napi/src/entry_point.cpp delete mode 100644 preferences/frameworks/js/napi/src/entry_point_storage.cpp delete mode 100644 preferences/frameworks/js/napi/src/entry_point_system_storage.cpp delete mode 100644 preferences/frameworks/js/napi/src/napi_preferences.cpp delete mode 100644 preferences/frameworks/js/napi/src/napi_preferences_helper.cpp delete mode 100644 preferences/frameworks/js/napi/src/napi_storage.cpp delete mode 100644 preferences/frameworks/js/napi/src/napi_storage_helper.cpp delete mode 100644 preferences/frameworks/js/napi/src/napi_system_storage.cpp delete mode 100644 preferences/frameworks/native/include/logger.h delete mode 100644 preferences/frameworks/native/include/preferences_impl.h delete mode 100644 preferences/frameworks/native/include/task_pool.h delete mode 100644 preferences/frameworks/native/include/task_queue.h delete mode 100644 preferences/frameworks/native/src/preferences_helper.cpp delete mode 100644 preferences/frameworks/native/src/preferences_impl.cpp delete mode 100644 preferences/frameworks/native/src/preferences_observer.cpp delete mode 100644 preferences/frameworks/native/src/preferences_value.cpp delete mode 100644 preferences/frameworks/native/src/preferences_xml_utils.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/interfaces/inner_api/BUILD.gn delete mode 100644 preferences/interfaces/inner_api/include/preferences.h delete mode 100644 preferences/interfaces/inner_api/include/preferences_errno.h delete mode 100644 preferences/interfaces/inner_api/include/preferences_helper.h delete mode 100644 preferences/interfaces/inner_api/include/preferences_observer.h delete mode 100644 preferences/interfaces/inner_api/include/preferences_value.h delete mode 100644 preferences/interfaces/inner_api/include/preferences_xml_utils.h delete mode 100644 preferences/preferences.gni delete mode 100644 preferences/test/js/unittest/src/BUILD.gn 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/native/BUILD.gn delete mode 100644 preferences/test/native/unittest/preferences_file_test.cpp delete mode 100644 preferences/test/native/unittest/preferences_helper_test.cpp delete mode 100644 preferences/test/native/unittest/preferences_test.cpp rename relational_store/relational_store.gni => relational_store.gni (100%) delete mode 100644 relational_store/README_zh.md delete mode 100644 relational_store/test/js/rdb/BUILD.gn delete mode 100644 relational_store/test/js/rdb/unittest/src/config.json rename {preferences/test/js => test/js/dataability}/BUILD.gn (100%) rename {relational_store/test => test}/js/dataability/unittest/src/BUILD.gn (100%) rename {relational_store/test => test}/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js (100%) rename {preferences/test/js => test/js/dataability}/unittest/src/config.json (100%) rename {relational_store/test/js/dataability => test/js/rdb}/BUILD.gn (100%) rename {relational_store/test => test}/js/rdb/unittest/src/BUILD.gn (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreChangeEncryptKeyJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js (100%) rename {relational_store/test => test}/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js (100%) rename {relational_store/test/js/dataability => test/js/rdb}/unittest/src/config.json (100%) rename {relational_store/test => test}/native/dataability/BUILD.gn (100%) rename {relational_store/test => test}/native/dataability/unittest/data_ability_predicates_test.cpp (100%) rename {relational_store/test => test}/native/rdb/BUILD.gn (100%) rename {relational_store/test => test}/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn (100%) rename {relational_store/test => test}/native/rdb/fuzztest/rdbimpl_fuzzer/corpus/init (100%) rename {relational_store/test => test}/native/rdb/fuzztest/rdbimpl_fuzzer/project.xml (100%) rename {relational_store/test => test}/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp (100%) rename {relational_store/test => test}/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.h (100%) rename {relational_store/test => test}/native/rdb/unittest/common.h (100%) rename {relational_store/test => test}/native/rdb/unittest/logger.h (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_attach_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_delete_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_distributed_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_encrypt_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_execute_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_helper_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_insert_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_open_callback_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_predicates_join_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_predicates_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_step_result_set_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_store_concurrent_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_store_config_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_store_interface_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_transaction_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_update_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_upgrade_test.cpp (100%) rename {relational_store/test => test}/native/rdb/unittest/rdb_value_bucket_test.cpp (100%) rename {relational_store/test => test}/native/rdb_data_share_adapter/BUILD.gn (100%) rename {relational_store/test => test}/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp (100%) diff --git a/OAT.xml b/OAT.xml deleted file mode 100644 index 703bfd735..000000000 --- a/OAT.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - - diff --git a/README.md b/README.md deleted file mode 100644 index 0d55aa17a..000000000 --- a/README.md +++ /dev/null @@ -1,110 +0,0 @@ -# distributeddatamgr\_appdatamgr - -- [Introduction](#section11660541593) - - [RDB](#section1589234172717) - - [Preferences Database](#section1287582752719) - -- [Directory Structure](#section161941989596) -- [Relational Database](#section101010894114) - - [Constraints](#section18387142613414) - -- [Preferences Database](#section762641474720) - - [Constraints](#section1944481420489) - -- [Repositories Involved](#section1371113476307) - -## Introduction - -The **relational database \(RDB\)** manages data based on relational models. With the underlying SQLite database, the OpenHarmony RDB provides a complete mechanism for managing local databases. - -The **preferences database** provides lightweight key-value operations for local applications to store a small amount of data. As the stored data is already loaded in the memory, the faster data access speed achieves a higher work efficiency. The preferences database is non-relational, and therefore it is not suitable for storing a large amount of data. Instead, the preferences database is usually used to operate data in key-value pairs. - -### RDB - -With the SQLite database as the persistence engine, the OpenHarmony RDB supports all features of the SQLite database , including but not limited to transactions, indices, views, triggers, foreign keys, parameterized queries, and prepared SQL statements. - -**Figure 1** How RDB works - - -![](figures/en-us_How_RDB_works.png) - -### Preferences Database - -1. The preferences database provides operation classes for applications to operate the database. -2. With the **PreferencesHelper**, an app can load the content of a specified file to the **Preferences** instance. Each file has only one **Preferences** instance. The system stores the instance in the memory through a static container until the app removes the instance from the memory or deletes the file. -3. After obtaining the **Preferences** instance, the app can use the functions in **Preferences** to read data from or write data to the **Preferences** instance, and use **flush\(\)** or **flushSync\(\)** to save the modification to the file that stores the preference data. - -**Figure 2** How the preferences database works - - -![](figures/en-us_How_the_preferences_database_works.png) - -## Directory Structure - -``` -//foundation/distributeddatamgr/appdatamgr -├── frameworks # Framework code -│ └── js # JS API implementation -│ │ └── napi # napi implementation -│ └── native # Internal API implementation -└── interfaces # APIs - └── inner_api # Internal APIs - └── native # C/C++ APIs -``` - -## Relational Database - -Some basic concepts are as follows: - -- **Relational database \(RDB\)** - - A database created on the basis of relational models. The RDB stores data in rows and columns. - -- **Result set** - - A set of query results used to access the data. You can access the required data in a result set in flexible modes. - -- **SQLite database** - - A lightweight RDB in compliance with the atomicity, consistency, isolation, and durability \(ACID\) properties. It is an open-source database. - - -### Constraints - -The RDB can use a maximum of four connection pools to manage read and write operations. - -To ensure data accuracy, the RDB supports only one writ operation at a time. - -## Preferences Database - -Some basic concepts are as follows: - -- **Key-value database** - - A database that stores data in key-value pairs. The **key** indicates keyword, and **value** indicates the corresponding value. - -- **Non-relational database** - - A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. Instead, the data in a non-relational database is independent and scalable. - -- **Preference** **data** - - A type of data that is frequently accessed and used. - - -### Constraints - -A key should be a string with a maximum of 80 characters and cannot be an empty string. - -A value in the format of string can have a maximum of 8192 characters. A value can be an empty string. - -To avoid a high memory cost, it is recommended that the preferences database store no more than ten thousand data entries. - -## Repositories Involved - -- [Distributed Data Management subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/distributed-data-management.md) - -- **distributeddatamgr\_appdatamgr** - -- [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite) - diff --git a/README_zh.md b/README_zh.md index dcd3b2cdd..8cdceeb02 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,29 +1,54 @@ -# 本地数据管理组件 +# 关系型数据库(Relational Database,RDB) + ## 简介 -### [关系型数据库(Relational Database,RDB)](relational_store/README_zh.md) -是一种基于关系模型来管理数据的数据库。OpenHarmony关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制。 -### [首选项(Preferences)](preferences/README_zh.md) +**关系型数据库(Relational Database,RDB)** 是一种基于关系模型来管理数据的数据库。OpenHarmony关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制。 + +OpenHarmony关系型数据库底层使用SQLite作为持久化存储引擎,支持SQLite具有的所有数据库特性,包括但不限于事务、索引、视图、触发器、外键、参数化查询和预编译SQL语句。 -主要提供轻量级Key-Value操作,支持本地应用存储少量数据,数据存储在本地文件中,同时也加载在内存中,所以访问速度更快,效率更高。首选项提供非关系型数据存储,不宜存储大量数据,经常用于操作键值对形式数据的场景。 -### [数据共享(DataShare)](data_share/README_zh.md) +以下是几个基本概念: +- **关系型数据库** -主要用于应用管理其自身数据,同时支持同个设备上不同应用间的数据共享。 -### [轻量系统KV数据库(Lightweight KV store)](kv_store/README_zh.md) + 创建在关系模型基础上的数据库,以行和列的形式存储数据。 + +- **结果集** + + 指用户查询之后的结果集合,可以对数据进行访问。结果集提供了灵活的数据访问方式,可以更方便的拿到用户想要的数据。 + +- **SQLite数据库** + + 一款轻量级的数据库,是遵守ACID的关系型数据库组件。它是一个开源的项目。 + +**图 1** 关系型数据库运作机制 + + +![](figures/zh-cn_关系型数据库运作机制.png) -依托当前公共基础库提供的KV存储能力开发,为轻量系统设备应用提供键值对数据管理能力。在有进程的平台上,KV存储提供的参数管理,供单进程访问不能被其他进程使用。在此类平台上,KV存储作为基础库加载在应用进程,以保障不被其他进程访问。 ## 目录 ``` -//foundation/distributeddatamgr/appdatamgr -├── data_share # 数据共享(DataShare) -├── kv_store # 轻量系统KV数据库(Lightweight KV store) -├── preferences # 首选项(Preferences) -└── relational_store # 关系型数据库(RDB) +//foundation/distributeddatamgr/relational_store/ +├── frameworks # 框架层代码 +│ └── js # JS API的实现 +│ │ └── napi # napi代码实现 +│ └── native # 内部接口实现 +├── interfaces # 接口代码 +│ └── inner_api # 内部接口声明 +└── test # 测试用例 + ├── js # js用例 + └── native # C++用例 ``` + +## 约束 + +数据库中连接池的最大数量是4个,用以管理用户的读写操作。 + +为保证数据的准确性,数据库同一时间只能支持一个写操作。 + ## 相关仓 + - [分布式数据管理子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%88%86%E5%B8%83%E5%BC%8F%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md) -- [**distributeddatamgr\_appdatamgr**](https://gitee.com/openharmony/distributeddatamgr_appdatamgr/blob/master/README_zh.md) +- [**distributeddatamgr\_relational_store**](https://gitee.com/openharmony/distributeddatamgr_relational_store/blob/master/README_zh.md) - [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite) \ No newline at end of file diff --git a/appdatamgr.gni b/appdatamgr.gni deleted file mode 100644 index ecacc068a..000000000 --- a/appdatamgr.gni +++ /dev/null @@ -1,16 +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. - -declare_args() { - relational_store_rdb_support_icu = true -} diff --git a/relational_store/bundle.json b/bundle.json similarity index 100% rename from relational_store/bundle.json rename to bundle.json diff --git a/data_share/README_zh.md b/data_share/README_zh.md deleted file mode 100644 index 7da848c9c..000000000 --- a/data_share/README_zh.md +++ /dev/null @@ -1,52 +0,0 @@ -# 数据共享 - -## 简介 - -**数据共享(Data Share)** 提供了向其他应用共享以及管理其数据的方法,支持同个设备上不同应用之间的数据共享。 - -**图 1** 逻辑架构图 - -![](figures/zh-cn_dataShare.png) - -- DataShareExtAbility模块为数据提供方,实现跨应用数据共享的相关业务。 -- DataShareHelper模块为数据访问方,提供各种访问数据的接口,包括增删改查等。 -- 数据访问方与提供方通过IPC进行通信,数据提供方可以通过数据库实现,也可以通过其他数据存储方式实现。 -- ResultSet模块通过共享内存实现,用于存储查询数据得到的结果集,并提供了遍历结果集的方法。 - -## 目录 - -``` -/foundation/distributeddatamgr/data_share -├── frameworks # 框架代码 -│   ├── js -│   │   └── napi # NAPI代码存放目录 -│   │   ├── common # 公用NAPI代码存放目录 -│   │   ├── dataShare # 客户端NAPI代码存放目录 -│   │   ├── datashare_ext_ability # DataShareExtentionAbility模块JS代码存放目录 -│   │   └── datashare_ext_ability_context # DataShareExtentionAbilityContext模块JS代码存放目录 -│   └── native -│   ├── common -│   ├── consumer -│   └── provider -└── interfaces # 对外接口存放目录 - └── inner_api # 对内部子系统暴露的头文件存放目录 - ├── common # 公用对内部子系统暴露的头文件存放目录 - ├── consumer # 客户端对内部子系统暴露的头文件存放目录 - └── provider # 服务端对内部子系统暴露的头文件存放目录 -``` - - - - -## 约束 - -- DataShare受到数据提供方所使用数据库的一些限制。例如支持的数据模型、Key的长度、Value的长度、每个应用程序支持同时打开数据库的最大数量等,都会受到使用的数据库的限制。 -- 因DataShare内部实现依赖于IPC通信,所以数据集、谓词、结果集等的载荷受到IPC通信的约束与限制。 - -## 相关仓 - -[分布式数据管理子系统](https://gitee.com/openharmony/distributeddatamgr_data_share/blob/master/README_zh.md) - -[distributeddatamgr_datamgr](https://gitee.com/openharmony/distributeddatamgr_datamgr/blob/master/README_zh.md) - -[**distributeddatamgr_data_share**](https://gitee.com/openharmony/distributeddatamgr_data_share/blob/master/README_zh.md) \ No newline at end of file diff --git a/data_share/bundle.json b/data_share/bundle.json deleted file mode 100644 index 7b567c16e..000000000 --- a/data_share/bundle.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "name": "@ohos/distributeddatamgr_data_share", - "version": "3.1.0", - "description": "Local Data Management", - "homePage": "https://gitee.com/openharmony", - "license": "Apache V2", - "repository": "https://gitee.com/openharmony/distributeddatamgr_data_share", - "domain": "os", - "language": "", - "publishAs": "code-segment", - "private": false, - "scripts": {}, - "tags": [ - "foundation" - ], - "keywords": [ - "distributeddatamgr", - "data_share" - ], - "envs": [], - "dirs": {}, - "author": { - "name": "", - "email": "", - "url": "" - }, - "contributors": [ - { - "name": "", - "email": "", - "url": "" - } - ], - "segment": { - "destPath": "foundation/distributeddatamgr/data_share" - }, - "component": { - "name": "data_share", - "subsystem": "distributeddatamgr", - "syscap": [ - "SystemCapability.DistributedDataManager.DataShare.Core", - "SystemCapability.DistributedDataManager.DataShare.Consumer", - "SystemCapability.DistributedDataManager.DataShare.Provider" - ], - "features": [], - "adapted_system_type": [ - "standard" - ], - "rom": "", - "ram": "", - "deps": { - "components": [ - "relational_store", - "access_token", - "ability_runtime", - "ipc_js", - "napi", - "hiviewdfx_hilog_native", - "libuv", - "ipc", - "bundle_framework", - "utils_base", - "ability_base", - "eventhandler" - ], - "third_party": [] - }, - "build": { - "sub_component": [ - "//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_abilitykit", - "//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_ext_ability_module", - "//foundation/distributeddatamgr/data_share/frameworks/js/napi:datashare_napi_packages", - "//foundation/distributeddatamgr/data_share/interfaces/inner_api/common:datashare_common" - ], - "inner_kits": [ - { - "name": "//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_abilitykit", - "header": { - "header_files": [ - "datashare_helper.h", - "datashare_result_set.h" - ], - "header_base": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/consumer/include" - } - }, - { - "name": "//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_abilitykit", - "header": { - "header_files": [ - "result_set_bridge.h" - ], - "header_base": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/provider/include" - } - }, - { - "name": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/common:datashare_common", - "header": { - "header_files": [ - "datashare_errno.h", - "datashare_abs_predicates.h", - "datashare_predicates_def.h", - "datashare_predicates_object.h", - "datashare_predicates.h", - "datashare_value_object.h", - "datashare_values_bucket.h" - ], - "header_base": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/common/include" - } - } - ] - } - } -} diff --git a/data_share/datashare.gni b/data_share/datashare.gni deleted file mode 100644 index 6513a3307..000000000 --- a/data_share/datashare.gni +++ /dev/null @@ -1,38 +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. - -ability_runtime_path = "//foundation/ability/ability_runtime" - -ability_runtime_inner_api_path = "${ability_runtime_path}/interfaces/inner_api" - -ability_runtime_kits_path = "${ability_runtime_path}/frameworks/kits" - -ability_runtime_services_path = "${ability_runtime_path}/services" - -ability_runtime_napi_path = "${ability_runtime_path}/frameworks/js/napi" - -datashare_base_path = "//foundation/distributeddatamgr/data_share" - -datashare_common_native_path = "${datashare_base_path}/frameworks/native/common" - -datashare_common_napi_path = "${datashare_base_path}/frameworks/js/napi/common" - -datashare_napi_path = "${datashare_base_path}/frameworks/js/napi" - -datashare_innerapi_path = "${datashare_base_path}/interfaces/inner_api" - -datashare_native_provider_path = - "${datashare_base_path}/frameworks/native/provider" - -datashare_native_consumer_path = - "${datashare_base_path}/frameworks/native/consumer" diff --git a/data_share/figures/zh-cn_dataShare.png b/data_share/figures/zh-cn_dataShare.png deleted file mode 100644 index cbeee3191dc614ec21dbef2866dc3a1412628eee..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 32504 zcmc$GcUY6z)-TQs#}NxtKt&N|bQCF4M*(TaHcAl`jG={~H0dQ$LW_eV%%FmFkTw=N z1O+J}Ktx6YBoY-NVh9mK5duVr5JEz7cM?FHqjSIW-9IkR zl|P%_?d*blqYPcAz3Hp3)@)dtx#laY8@be%0l!WEi?MahZ!Zr?xSVe>eZAlLsLKtB zmfxff9d~tyPo20p-?^)KUCmb*nO}dze}n(7I{TaNFZg%mjT()rk{w1VQI`3oQ#P1=W{OA6AjPg#=U-i)znQw)ENp`oL<9`?awX2=hJSKY2 zHGOZU_%&^F84J;C-)8NWDipo;JMlY7o2B9Y`2RDUg?grdmoH%DI)#rFToueK3g{dC zaf>0?NF<}8?iIIbrc-rtrT|OAE28?<9h^{$vvbjjiY9&;8j6wc4n^Qb^CHkNW2dme zD|5!oX09JLvctB4+cfvedva#@xXHq^>s(j+I-ib%c=jKZyhOv;sc0mTI+HY7inYq4 z_;IQjoOW83L-SD0Q);C{?a+QQRjKlsA19d{7K)qro+_OCxMI``b%*A~N&h-F;XQaZ z8^UI!@0%O*=qt*1%Wp2hCPppTfsag={AMK1ukU<*bh`MP$yY_*e8;Q;=a4UfbUF9Q zSO6JwzvcXegoNhR$Ff9ST4eQ(z2G}SZGBAN#_uE~E)Cmgu91+)yb`lcLgJy?4DKj$ zW~d_=o2?-EJs6>Nkfnpq9w@Z%-SX0KZQ6?*g3U9KN8t^l2}UdWr1^JcRRI zx*onbOV$_&qhDu)=o(4w0ptEsKzi(WS~$@GvzD*GxSNGvOH|uBw(#cZiIiUff%kl_ zs%BDu0Polu3+KLMCmNNw6OQD)@3yL>P~U$v&Bkn6 z2ra0XEbG+^-3--)BZt#M{sd&GQQk><->D8eCZ^q|Yng&QTZnZ7 z;bl910zW6{dVr6S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l^2TL zOQ={8@e|N3p>}Q_!iPXn+{R@$t)M0^p;)5|$48JXay4 zq8z^S7_!*mJ9VF;r=I+sC?A8k>a?Vp7x$9>CNJ}Ef%Uu+*{4qtuyAwW{hQMHN9^?dkp)q2Kcz zuI$j6zKp^Ao~ye%9>JgQ4<5VYTn5Y16#pcg8y_4SMbK8g32(%Z4VaF(e?A!MTXRCE z(Y9X7PyIs!Jhr*Dr?7Wx)NLzu|DsTSaeqv2p<~&=1(UI&fdswa9q0QJc5oKF;u$lo zFEUcEF8`0lrd}Zi{It}zKHgqj2>t&_G4-AN*RO?2B|Q_j!Vb~+usY=|%x(V2`t;;q F{sG8hqO1S_ diff --git a/data_share/frameworks/js/napi/BUILD.gn b/data_share/frameworks/js/napi/BUILD.gn deleted file mode 100644 index 0a8dca071..000000000 --- a/data_share/frameworks/js/napi/BUILD.gn +++ /dev/null @@ -1,24 +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("//build/ohos.gni") -import("//foundation/distributeddatamgr/data_share/datashare.gni") - -group("datashare_napi_packages") { - deps = [ - "${datashare_napi_path}/dataShare:datashare", - "${datashare_napi_path}/dataShare:datasharepredicates", - "${datashare_napi_path}/datashare_ext_ability:datashareextensionability_napi", - "${datashare_napi_path}/datashare_ext_ability_context:datashareextensionabilitycontext_napi", - ] -} diff --git a/data_share/frameworks/js/napi/common/include/datashare_js_utils.h b/data_share/frameworks/js/napi/common/include/datashare_js_utils.h deleted file mode 100644 index 539e3bdd8..000000000 --- a/data_share/frameworks/js/napi/common/include/datashare_js_utils.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_JSUTILS_H -#define DATASHARE_JSUTILS_H - -#include -#include -#include -#include - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace DataShare { -class DataShareJSUtils final { -public: - static constexpr int32_t DEFAULT_BUF_SIZE = 1024; - static constexpr int32_t ASYNC_RST_SIZE = 2; - static constexpr int32_t SYNC_RESULT_ELEMNT_NUM = 2; - - static std::string Convert2String(napi_env env, napi_value jsStr, size_t max = DEFAULT_BUF_SIZE); - static std::vector Convert2StrVector(napi_env env, napi_value value, size_t strMax); - static std::vector Convert2U8Vector(napi_env env, napi_value jsValue); - static std::string ConvertAny2String(napi_env env, const napi_value jsValue); - static std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue = ""); - - static napi_value Convert2JSValue(napi_env env, const std::vector &value); - static napi_value Convert2JSValue(napi_env env, const std::string &value); - static napi_value Convert2JSValue(napi_env env, const std::vector &value); - static napi_value Convert2JSValue(napi_env env, int32_t value); - static napi_value Convert2JSValue(napi_env env, int64_t value); - static napi_value Convert2JSValue(napi_env env, double value); - static napi_value Convert2JSValue(napi_env env, bool value); - static napi_value Convert2JSValue(napi_env env, const std::map& value); - static std::vector ConvertU8Vector(napi_env env, napi_value jsValue); -}; -} // namespace DataShare -} // namespace OHOS - -#endif // DATASHARE_JSUTILS_H diff --git a/data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h b/data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h deleted file mode 100644 index ab367aefd..000000000 --- a/data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_PREDICATES_PROXY_H -#define DATASHARE_PREDICATES_PROXY_H - -#include -#include "datashare_predicates.h" -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace DataShare { -class DataSharePredicatesProxy { -public: - static void Init(napi_env env, napi_value exports); - static napi_value NewInstance(napi_env env, std::shared_ptr value); - static std::shared_ptr GetNativePredicates( - const napi_env &env, const napi_value &arg); - static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); - - DataSharePredicatesProxy(); - std::shared_ptr GetPredicates() const; - static napi_value GetConstructor(napi_env env); - -private: - ~DataSharePredicatesProxy(); - - static napi_value New(napi_env env, napi_callback_info info); - static std::shared_ptr GetNativePredicates(napi_env env, napi_callback_info info); - static napi_value EqualTo(napi_env env, napi_callback_info info); - static napi_value NotEqualTo(napi_env env, napi_callback_info info); - static napi_value BeginWrap(napi_env env, napi_callback_info info); - static napi_value EndWrap(napi_env env, napi_callback_info info); - static napi_value Or(napi_env env, napi_callback_info info); - static napi_value And(napi_env env, napi_callback_info info); - static napi_value Contains(napi_env env, napi_callback_info info); - static napi_value BeginsWith(napi_env env, napi_callback_info info); - static napi_value EndsWith(napi_env env, napi_callback_info info); - static napi_value IsNull(napi_env env, napi_callback_info info); - static napi_value IsNotNull(napi_env env, napi_callback_info info); - static napi_value Like(napi_env env, napi_callback_info info); - static napi_value Unlike(napi_env env, napi_callback_info info); - static napi_value Glob(napi_env env, napi_callback_info info); - static napi_value Between(napi_env env, napi_callback_info info); - static napi_value NotBetween(napi_env env, napi_callback_info info); - static napi_value GreaterThan(napi_env env, napi_callback_info info); - static napi_value LessThan(napi_env env, napi_callback_info info); - static napi_value GreaterThanOrEqualTo(napi_env env, napi_callback_info info); - static napi_value LessThanOrEqualTo(napi_env env, napi_callback_info info); - static napi_value OrderByAsc(napi_env env, napi_callback_info info); - static napi_value OrderByDesc(napi_env env, napi_callback_info info); - static napi_value Distinct(napi_env env, napi_callback_info info); - static napi_value Limit(napi_env env, napi_callback_info info); - static napi_value GroupBy(napi_env env, napi_callback_info info); - static napi_value IndexedBy(napi_env env, napi_callback_info info); - static napi_value In(napi_env env, napi_callback_info info); - static napi_value NotIn(napi_env env, napi_callback_info info); - static napi_value PrefixKey(napi_env env, napi_callback_info info); - static napi_value InKeys(napi_env env, napi_callback_info info); - - std::shared_ptr predicates_; - napi_env env_; - napi_ref wrapper_; -}; - -napi_value GetNapiObject(napi_env env, std::shared_ptr predicates); -DataSharePredicates *GetNativePredicatesObject(const napi_env &env, const napi_value &arg); -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_PREDICATES_PROXY_H diff --git a/data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h b/data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h deleted file mode 100644 index 6f48e90a4..000000000 --- a/data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_RESULT_SET_PROXY -#define DATASHARE_RESULT_SET_PROXY - -#include -#include "datashare_result_set.h" -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace DataShare { -class DataShareResultSetProxy final { -public: - DataShareResultSetProxy() = default; - ~DataShareResultSetProxy(); - explicit DataShareResultSetProxy(std::shared_ptr resultSet); - DataShareResultSetProxy &operator=(std::shared_ptr resultSet); - static napi_value NewInstance(napi_env env, std::shared_ptr resultSet); - static std::shared_ptr GetNativeObject( - const napi_env &env, const napi_value &arg); - static napi_value GetConstructor(napi_env env); - -private: - static std::shared_ptr &GetInnerResultSet(napi_env env, napi_callback_info info); - static napi_value Initialize(napi_env env, napi_callback_info info); - - static napi_value GoToFirstRow(napi_env env, napi_callback_info info); - static napi_value GoToLastRow(napi_env env, napi_callback_info info); - static napi_value GoToNextRow(napi_env env, napi_callback_info info); - static napi_value GoToPreviousRow(napi_env env, napi_callback_info info); - static napi_value GoTo(napi_env env, napi_callback_info info); - static napi_value GoToRow(napi_env env, napi_callback_info info); - static napi_value GetBlob(napi_env env, napi_callback_info info); - static napi_value GetString(napi_env env, napi_callback_info info); - static napi_value GetLong(napi_env env, napi_callback_info info); - static napi_value GetDouble(napi_env env, napi_callback_info info); - static napi_value Close(napi_env env, napi_callback_info info); - static napi_value GetColumnIndex(napi_env env, napi_callback_info info); - static napi_value GetColumnName(napi_env env, napi_callback_info info); - static napi_value GetDataType(napi_env env, napi_callback_info info); - - static napi_value GetAllColumnNames(napi_env env, napi_callback_info info); - static napi_value GetColumnCount(napi_env env, napi_callback_info info); - static napi_value GetRowCount(napi_env env, napi_callback_info info); - static napi_value IsClosed(napi_env env, napi_callback_info info); - - std::shared_ptr resultSet_; -}; -napi_value GetNapiResultSetObject(napi_env env, DataShareResultSet *resultSet); -DataShareResultSet *GetResultSetProxyObject(const napi_env &env, const napi_value &arg); -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_RESULT_SET_PROXY diff --git a/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h b/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h deleted file mode 100644 index 4b2e3a8ac..000000000 --- a/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h +++ /dev/null @@ -1,31 +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 NAPI_DATASHARE_VALUES_BUCKET_H -#define NAPI_DATASHARE_VALUES_BUCKET_H - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "datashare_values_bucket.h" -#include "datashare_js_utils.h" - -namespace OHOS { -namespace DataShare { -napi_value DataShareValueBucketNewInstance(napi_env env, DataShareValuesBucket &valuesBucket); -void GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg); -} // namespace DataShare -} // namespace OHOS -#endif // NAPI_DATASHARE_VALUES_BUCKET_H diff --git a/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp b/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp deleted file mode 100644 index 8a3e83377..000000000 --- a/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp +++ /dev/null @@ -1,259 +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 "datashare_js_utils.h" -#include "datashare_log.h" - -#include "securec.h" - -namespace OHOS { -namespace DataShare { -std::string DataShareJSUtils::Convert2String(napi_env env, napi_value jsStr, const size_t max) -{ - NAPI_ASSERT_BASE(env, max > 0, "failed on max > 0", std::string()); - char *buf = new char[max + 1]; - size_t len = 0; - napi_get_value_string_utf8(env, jsStr, buf, max, &len); - buf[len] = 0; - std::string value(buf); - delete[] buf; - return value; -} - -std::vector DataShareJSUtils::Convert2StrVector(napi_env env, napi_value value, const size_t strMax) -{ - NAPI_ASSERT_BASE(env, strMax > 0, "failed on strMax > 0", std::vector()); - 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 DataShareJSUtils::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::vector DataShareJSUtils::ConvertU8Vector(napi_env env, napi_value jsValue) -{ - bool isTypedArray = false; - if (napi_is_typedarray(env, jsValue, &isTypedArray) != napi_ok || !isTypedArray) { - return {}; - } - - napi_typedarray_type type; - size_t length = 0; - napi_value buffer = nullptr; - size_t offset = 0; - NAPI_CALL_BASE(env, napi_get_typedarray_info(env, jsValue, &type, &length, nullptr, &buffer, &offset), {}); - if (type != napi_uint8_array) { - return {}; - } - uint8_t *data = nullptr; - size_t total = 0; - NAPI_CALL_BASE(env, napi_get_arraybuffer_info(env, buffer, reinterpret_cast(&data), &total), {}); - length = std::min(length, total - offset); - std::vector result(sizeof(uint8_t) + length); - int retCode = memcpy_s(result.data(), result.size(), &data[offset], length); - if (retCode != 0) { - return {}; - } - return result; -} - -std::string DataShareJSUtils::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 DataShareJSUtils::Convert2String(env, jsValue, DataShareJSUtils::DEFAULT_BUF_SIZE); - } 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 "null"; - } else if (valueType == napi_object) { - std::vector bytes = DataShareJSUtils::Convert2U8Vector(env, jsValue); - std::string ret(bytes.begin(), bytes.end()); - return ret; - } - - return "invalid type"; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector &value) -{ - napi_value jsValue; - napi_status status = napi_create_array_with_length(env, value.size(), &jsValue); - if (status != napi_ok) { - return nullptr; - } - - for (size_t i = 0; i < value.size(); ++i) { - napi_set_element(env, jsValue, i, Convert2JSValue(env, value[i])); - } - return jsValue; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::string &value) -{ - napi_value jsValue; - napi_status status = napi_create_string_utf8(env, value.c_str(), value.size(), &jsValue); - if (status != napi_ok) { - return nullptr; - } - return jsValue; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector &value) -{ - napi_value jsValue; - void *native = nullptr; - napi_value buffer = nullptr; - napi_status status = napi_create_arraybuffer(env, value.size(), &native, &buffer); - if (status != napi_ok) { - return nullptr; - } - if (memcpy_s(native, value.size(), value.data(), value.size()) != EOK && value.size() > 0) { - return nullptr; - } - status = napi_create_typedarray(env, napi_uint8_array, value.size(), buffer, 0, &jsValue); - if (status != napi_ok) { - return nullptr; - } - return jsValue; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, int32_t value) -{ - napi_value jsValue; - napi_status status = napi_create_int32(env, value, &jsValue); - if (status != napi_ok) { - return nullptr; - } - return jsValue; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, int64_t value) -{ - napi_value jsValue; - napi_status status = napi_create_int64(env, value, &jsValue); - if (status != napi_ok) { - return nullptr; - } - return jsValue; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, double value) -{ - napi_value jsValue; - napi_status status = napi_create_double(env, value, &jsValue); - if (status != napi_ok) { - return nullptr; - } - return jsValue; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, bool value) -{ - napi_value jsValue; - napi_status status = napi_get_boolean(env, value, &jsValue); - if (status != napi_ok) { - return nullptr; - } - return jsValue; -} - -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::map &value) -{ - napi_value jsValue; - napi_status status = napi_create_array_with_length(env, value.size(), &jsValue); - if (status != napi_ok) { - return nullptr; - } - - int index = 0; - for (const auto& [device, result] : value) { - napi_value jsElement; - status = napi_create_array_with_length(env, SYNC_RESULT_ELEMNT_NUM, &jsElement); - if (status != napi_ok) { - return nullptr; - } - napi_set_element(env, jsElement, 0, Convert2JSValue(env, device)); - napi_set_element(env, jsElement, 1, Convert2JSValue(env, result)); - napi_set_element(env, jsValue, index++, jsElement); - } - - return jsValue; -} -std::string DataShareJSUtils::UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue) -{ - size_t size = 0; - if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) { - return defaultValue; - } - - std::string value(""); - if (size == 0) { - return defaultValue; - } - - char *buf = new (std::nothrow) char[size + 1]; - if (buf == nullptr) { - return value; - } - (void)memset_s(buf, size + 1, 0, size + 1); - - bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok; - if (rev) { - value = buf; - } else { - value = defaultValue; - } - - delete[] buf; - buf = nullptr; - return value; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp b/data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp deleted file mode 100644 index 6c30a3f6d..000000000 --- a/data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp +++ /dev/null @@ -1,863 +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 "datashare_predicates_proxy.h" - -#include "datashare_log.h" -#include "datashare_js_utils.h" - -namespace OHOS { -namespace DataShare { -static napi_ref __thread constructor_ = nullptr; -static constexpr int ARGC_ZERO = 0; -static constexpr int ARGC_ONE = 1; -static constexpr int ARGC_TWO = 2; - -napi_value DataSharePredicatesProxy::GetConstructor(napi_env env) -{ - napi_value cons; - if (constructor_ != nullptr) { - NAPI_CALL(env, napi_get_reference_value(env, constructor_, &cons)); - return cons; - } - LOG_INFO("GetConstructor DataSharePredicates constructor"); - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_FUNCTION("equalTo", EqualTo), - DECLARE_NAPI_FUNCTION("notEqualTo", NotEqualTo), - DECLARE_NAPI_FUNCTION("beginWrap", BeginWrap), - DECLARE_NAPI_FUNCTION("endWrap", EndWrap), - DECLARE_NAPI_FUNCTION("or", Or), - DECLARE_NAPI_FUNCTION("and", And), - DECLARE_NAPI_FUNCTION("contains", Contains), - DECLARE_NAPI_FUNCTION("beginsWith", BeginsWith), - DECLARE_NAPI_FUNCTION("endsWith", EndsWith), - DECLARE_NAPI_FUNCTION("isNull", IsNull), - DECLARE_NAPI_FUNCTION("isNotNull", IsNotNull), - DECLARE_NAPI_FUNCTION("like", Like), - DECLARE_NAPI_FUNCTION("unlike", Unlike), - DECLARE_NAPI_FUNCTION("glob", Glob), - DECLARE_NAPI_FUNCTION("between", Between), - DECLARE_NAPI_FUNCTION("notBetween", NotBetween), - DECLARE_NAPI_FUNCTION("greaterThan", GreaterThan), - DECLARE_NAPI_FUNCTION("lessThan", LessThan), - DECLARE_NAPI_FUNCTION("greaterThanOrEqualTo", GreaterThanOrEqualTo), - DECLARE_NAPI_FUNCTION("lessThanOrEqualTo", LessThanOrEqualTo), - DECLARE_NAPI_FUNCTION("orderByAsc", OrderByAsc), - DECLARE_NAPI_FUNCTION("orderByDesc", OrderByDesc), - DECLARE_NAPI_FUNCTION("distinct", Distinct), - DECLARE_NAPI_FUNCTION("limit", Limit), - DECLARE_NAPI_FUNCTION("groupBy", GroupBy), - DECLARE_NAPI_FUNCTION("indexedBy", IndexedBy), - DECLARE_NAPI_FUNCTION("in", In), - DECLARE_NAPI_FUNCTION("notIn", NotIn), - DECLARE_NAPI_FUNCTION("prefixKey", PrefixKey), - DECLARE_NAPI_FUNCTION("inKeys", InKeys), - }; - NAPI_CALL(env, napi_define_class(env, "DataSharePredicates", NAPI_AUTO_LENGTH, New, nullptr, - sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons)); - NAPI_CALL(env, napi_create_reference(env, cons, 1, &constructor_)); - return cons; -} - -void DataSharePredicatesProxy::Init(napi_env env, napi_value exports) -{ - LOG_INFO("Init DataSharePredicatesProxy in."); - napi_value cons = GetConstructor(env); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, exports, "DataSharePredicates", cons)); - LOG_DEBUG("Init DataSharePredicatesProxy out."); -} - -napi_value DataSharePredicatesProxy::New(napi_env env, napi_callback_info info) -{ - napi_value new_target; - NAPI_CALL(env, napi_get_new_target(env, info, &new_target)); - bool is_constructor = (new_target != nullptr); - - napi_value thiz; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr)); - - if (is_constructor) { - auto *proxy = new DataSharePredicatesProxy(); - proxy->env_ = env; - NAPI_CALL(env, napi_wrap(env, thiz, proxy, DataSharePredicatesProxy::Destructor, nullptr, &proxy->wrapper_)); - LOG_INFO("DataSharePredicatesProxy::New constructor ref:%{public}p", proxy->wrapper_); - return thiz; - } - - napi_value cons; - NAPI_CALL(env, napi_get_reference_value(env, constructor_, &cons)); - - napi_value output; - NAPI_CALL(env, napi_new_instance(env, cons, 0, nullptr, &output)); - - return output; -} - -napi_value DataSharePredicatesProxy::NewInstance( - napi_env env, std::shared_ptr value) -{ - napi_value cons = GetConstructor(env); - if (cons == nullptr) { - LOG_ERROR("DataSharePredicatesProxy GetConstructor failed."); - return nullptr; - } - - napi_value instance = nullptr; - napi_status status = napi_new_instance(env, cons, 0, nullptr, &instance); - if (status != napi_ok) { - LOG_ERROR("DataSharePredicatesProxy napi_new_instance failed! napi_status:%{public}d!", status); - return nullptr; - } - - DataSharePredicatesProxy *proxy = nullptr; - status = napi_unwrap(env, instance, reinterpret_cast(&proxy)); - if (status != napi_ok) { - LOG_ERROR("DataSharePredicatesProxy native instance is nullptr! napi_status:%{public}d!", status); - return instance; - } - proxy->predicates_ = std::move(value); - return instance; -} - -std::shared_ptr DataSharePredicatesProxy::GetNativePredicates( - const napi_env &env, const napi_value &arg) -{ - LOG_DEBUG("GetNativePredicates on called."); - if (arg == nullptr) { - LOG_ERROR("DataSharePredicatesProxy arg is null."); - return nullptr; - } - DataSharePredicatesProxy *proxy = nullptr; - napi_unwrap(env, arg, reinterpret_cast(&proxy)); - return proxy->predicates_; -} - -void DataSharePredicatesProxy::Destructor(napi_env env, void *nativeObject, void *) -{ - DataSharePredicatesProxy *proxy = static_cast(nativeObject); - delete proxy; -} - -DataSharePredicatesProxy::~DataSharePredicatesProxy() -{ - napi_delete_reference(env_, wrapper_); -} - -DataSharePredicatesProxy::DataSharePredicatesProxy() - : predicates_(new DataSharePredicates()), env_(nullptr), wrapper_(nullptr) -{ -} - -std::shared_ptr DataSharePredicatesProxy::GetNativePredicates( - napi_env env, napi_callback_info info) -{ - DataSharePredicatesProxy *predicatesProxy = nullptr; - napi_value thiz; - napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); - napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); - return predicatesProxy->predicates_; -} - -napi_value DataSharePredicatesProxy::EqualTo(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::EqualTo on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::EqualTo Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - napi_valuetype valueType = napi_undefined; - napi_status status = napi_typeof(env, args[1], &valueType); - if (status != napi_ok) { - LOG_ERROR("napi_typeof status : %{public}d", status); - return thiz; - } - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - switch (valueType) { - case napi_number: { - double value; - napi_get_value_double(env, args[1], &value); - nativePredicates->EqualTo(field, value); - break; - } - case napi_boolean: { - bool value = false; - napi_get_value_bool(env, args[1], &value); - nativePredicates->EqualTo(field, value); - break; - } - case napi_string: { - std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - nativePredicates->EqualTo(field, value); - break; - } - default: - break; - } - return thiz; -} - -napi_value DataSharePredicatesProxy::NotEqualTo(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::NotEqualTo on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::NotEqualTo Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - napi_valuetype valueType = napi_undefined; - napi_status status = napi_typeof(env, args[1], &valueType); - if (status != napi_ok) { - LOG_ERROR("napi_typeof status : %{public}d", status); - return thiz; - } - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - switch (valueType) { - case napi_number: { - double value; - napi_get_value_double(env, args[1], &value); - nativePredicates->NotEqualTo(field, value); - break; - } - case napi_boolean: { - bool value = false; - napi_get_value_bool(env, args[1], &value); - nativePredicates->NotEqualTo(field, value); - break; - } - case napi_string: { - std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - nativePredicates->NotEqualTo(field, value); - break; - } - default: - break; - } - return thiz; -} - -napi_value DataSharePredicatesProxy::BeginWrap(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::BeginWrap on called."); - napi_value thiz; - napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->BeginWrap(); - return thiz; -} - -napi_value DataSharePredicatesProxy::EndWrap(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::EndWrap on called."); - napi_value thiz; - napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->EndWrap(); - return thiz; -} - -napi_value DataSharePredicatesProxy::Or(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Or on called."); - napi_value thiz; - napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Or(); - return thiz; -} - -napi_value DataSharePredicatesProxy::And(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::And on called."); - napi_value thiz; - napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->And(); - return thiz; -} - -napi_value DataSharePredicatesProxy::Contains(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Contains on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Contains Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]); - - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Contains(field, value); - return thiz; -} - -napi_value DataSharePredicatesProxy::BeginsWith(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::BeginsWith on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::BeginsWith Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->BeginsWith(field, value); - return thiz; -} - -napi_value DataSharePredicatesProxy::EndsWith(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::EndsWith on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::EndsWith Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->EndsWith(field, value); - return thiz; -} - -napi_value DataSharePredicatesProxy::IsNull(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::IsNull on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::IsNull Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->IsNull(field); - return thiz; -} - -napi_value DataSharePredicatesProxy::IsNotNull(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::IsNotNull on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::IsNotNull Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->IsNotNull(field); - return thiz; -} - -napi_value DataSharePredicatesProxy::Like(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Like on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Like Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Like(field, value); - return thiz; -} - -napi_value DataSharePredicatesProxy::Unlike(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Unlike on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Unlike Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Unlike(field, value); - return thiz; -} - -napi_value DataSharePredicatesProxy::Glob(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Glob on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Glob Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Glob(field, value); - return thiz; -} - -napi_value DataSharePredicatesProxy::Between(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Between on called."); - napi_value thiz; - size_t argc = 3; - napi_value args[3] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_TWO, "DataSharePredicatesProxy::Between Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string low = DataShareJSUtils::ConvertAny2String(env, args[1]); - std::string high = DataShareJSUtils::ConvertAny2String(env, args[2]); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Between(field, low, high); - return thiz; -} - -napi_value DataSharePredicatesProxy::NotBetween(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::NotBetween on called."); - napi_value thiz; - size_t argc = 3; - napi_value args[3] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_TWO, "DataSharePredicatesProxy::NotBetween Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::string low = DataShareJSUtils::ConvertAny2String(env, args[1]); - std::string high = DataShareJSUtils::ConvertAny2String(env, args[2]); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->NotBetween(field, low, high); - return thiz; -} - -napi_value DataSharePredicatesProxy::GreaterThan(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::GreaterThan on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::GreaterThan Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - napi_valuetype valueType = napi_undefined; - napi_status status = napi_typeof(env, args[1], &valueType); - if (status != napi_ok) { - LOG_ERROR("napi_typeof status : %{public}d", status); - return thiz; - } - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - switch (valueType) { - case napi_number: { - double value; - napi_get_value_double(env, args[1], &value); - nativePredicates->GreaterThan(field, value); - break; - } - case napi_string: { - std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - nativePredicates->GreaterThan(field, value); - break; - } - default: - break; - } - return thiz; -} - -napi_value DataSharePredicatesProxy::LessThan(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::LessThan on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::LessThan Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - napi_valuetype valueType = napi_undefined; - napi_status status = napi_typeof(env, args[1], &valueType); - if (status != napi_ok) { - LOG_ERROR("napi_typeof status : %{public}d", status); - return thiz; - } - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - switch (valueType) { - case napi_number: { - double value; - napi_get_value_double(env, args[1], &value); - nativePredicates->LessThan(field, value); - break; - } - case napi_string: { - std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - nativePredicates->LessThan(field, value); - break; - } - default: - break; - } - return thiz; -} - -napi_value DataSharePredicatesProxy::GreaterThanOrEqualTo(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::GreaterThanOrEqualTo on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::GreaterThanOrEqualTo Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - napi_valuetype valueType = napi_undefined; - napi_status status = napi_typeof(env, args[1], &valueType); - if (status != napi_ok) { - LOG_ERROR("napi_typeof status : %{public}d", status); - return thiz; - } - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - switch (valueType) { - case napi_number: { - double value; - napi_get_value_double(env, args[1], &value); - nativePredicates->GreaterThanOrEqualTo(field, value); - break; - } - case napi_string: { - std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - nativePredicates->GreaterThanOrEqualTo(field, value); - break; - } - default: - break; - } - return thiz; -} - -napi_value DataSharePredicatesProxy::LessThanOrEqualTo(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::LessThanOrEqualTo on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::LessThanOrEqualTo Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - napi_valuetype valueType = napi_undefined; - napi_status status = napi_typeof(env, args[1], &valueType); - if (status != napi_ok) { - LOG_ERROR("napi_typeof status : %{public}d", status); - return thiz; - } - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - switch (valueType) { - case napi_number: { - double value; - napi_get_value_double(env, args[1], &value); - nativePredicates->LessThanOrEqualTo(field, value); - break; - } - case napi_string: { - std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - nativePredicates->LessThanOrEqualTo(field, value); - break; - } - default: - break; - } - return thiz; -} - -napi_value DataSharePredicatesProxy::OrderByAsc(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::OrderByAsc on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::OrderByAsc Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->OrderByAsc(field); - return thiz; -} - -napi_value DataSharePredicatesProxy::OrderByDesc(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::OrderByDesc on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::OrderByDesc Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->OrderByDesc(field); - return thiz; -} - -napi_value DataSharePredicatesProxy::Distinct(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Distinct on called."); - napi_value thiz; - napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Distinct(); - return thiz; -} - -napi_value DataSharePredicatesProxy::Limit(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::Limit on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Limit Invalid argvs!"); - int number = 0; - napi_status status = napi_get_value_int32(env, args[0], &number); - LOG_INFO("number, napi_get_value_int32 : %{public}d", status); - int offset = 0; - status = napi_get_value_int32(env, args[1], &offset); - LOG_INFO("offset, napi_get_value_int32 : %{public}d", status); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->Limit(number, offset); - return thiz; -} - -napi_value DataSharePredicatesProxy::GroupBy(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::GroupBy on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::GroupBy Invalid argvs!"); - std::vector fields = DataShareJSUtils::Convert2StrVector(env, - args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->GroupBy(fields); - return thiz; -} - -napi_value DataSharePredicatesProxy::IndexedBy(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::IndexedBy on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::IndexedBy Invalid argvs!"); - std::string indexName = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->IndexedBy(indexName); - return thiz; -} - -napi_value DataSharePredicatesProxy::In(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::In on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::In Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::vector values = DataShareJSUtils::Convert2StrVector(env, - args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->In(field, values); - return thiz; -} - -napi_value DataSharePredicatesProxy::NotIn(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::NotIn on called."); - napi_value thiz; - size_t argc = 2; - napi_value args[2] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::NotIn Invalid argvs!"); - std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::vector values = DataShareJSUtils::Convert2StrVector(env, - args[1], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->NotIn(field, values); - return thiz; -} - -std::shared_ptr DataSharePredicatesProxy::GetPredicates() const -{ - return this->predicates_; -} - -napi_value DataSharePredicatesProxy::PrefixKey(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::PrefixKey on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::PrefixKey Invalid argvs!"); - std::string prefix = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->KeyPrefix(prefix); - return thiz; -} - -napi_value DataSharePredicatesProxy::InKeys(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("DataSharePredicatesProxy::InKeys on called."); - napi_value thiz; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::InKeys Invalid argvs!"); - std::vector keys = DataShareJSUtils::Convert2StrVector(env, - args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativePredicates = GetNativePredicates(env, info); - if (nativePredicates == nullptr) { - LOG_ERROR("GetNativePredicates failed."); - return thiz; - } - nativePredicates->InKeys(keys); - return thiz; -} - -napi_value GetNapiObject(napi_env env, std::shared_ptr predicates) -{ - return DataSharePredicatesProxy::NewInstance(env, predicates); -} - -DataSharePredicates *GetNativePredicatesObject(const napi_env &env, const napi_value &arg) -{ - auto predicates = DataSharePredicatesProxy::GetNativePredicates(env, arg); - return predicates.get(); -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp b/data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp deleted file mode 100644 index e212ae84a..000000000 --- a/data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp +++ /dev/null @@ -1,492 +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 "datashare_result_set_proxy.h" - -#include - -#include "datashare_result_set.h" -#include "datashare_js_utils.h" -#include "string_ex.h" -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -constexpr int MAX_INPUT_COUNT = 10; -static napi_ref __thread ctorRef_ = nullptr; -napi_value DataShareResultSetProxy::NewInstance(napi_env env, std::shared_ptr resultSet) -{ - napi_value cons = GetConstructor(env); - if (cons == nullptr) { - LOG_ERROR("NewInstance GetConstructor is nullptr!"); - return nullptr; - } - napi_value instance; - napi_status status = napi_new_instance(env, cons, 0, nullptr, &instance); - if (status != napi_ok) { - LOG_ERROR("NewInstance napi_new_instance failed! code:%{public}d!", status); - return nullptr; - } - - DataShareResultSetProxy *proxy = nullptr; - status = napi_unwrap(env, instance, reinterpret_cast(&proxy)); - if (proxy == nullptr) { - LOG_ERROR("NewInstance native instance is nullptr! code:%{public}d!", status); - return instance; - } - - *proxy = std::move(resultSet); - return instance; -} - -std::shared_ptr DataShareResultSetProxy::GetNativeObject( - napi_env const &env, napi_value const &arg) -{ - if (arg == nullptr) { - LOG_ERROR("DataShareResultSetProxy GetNativeObject arg is null."); - return nullptr; - } - DataShareResultSetProxy *proxy = nullptr; - napi_unwrap(env, arg, reinterpret_cast(&proxy)); - if (proxy == nullptr) { - LOG_ERROR("DataShareResultSetProxy GetNativeObject proxy is null."); - return nullptr; - } - return proxy->resultSet_; -} - -napi_value DataShareResultSetProxy::GetConstructor(napi_env env) -{ - napi_value cons; - if (ctorRef_ != nullptr) { - NAPI_CALL(env, napi_get_reference_value(env, ctorRef_, &cons)); - return cons; - } - LOG_INFO("GetConstructor result set constructor"); - napi_property_descriptor clzDes[] = { - DECLARE_NAPI_FUNCTION("goToFirstRow", GoToFirstRow), - DECLARE_NAPI_FUNCTION("goToLastRow", GoToLastRow), - DECLARE_NAPI_FUNCTION("goToNextRow", GoToNextRow), - DECLARE_NAPI_FUNCTION("goToPreviousRow", GoToPreviousRow), - DECLARE_NAPI_FUNCTION("goTo", GoTo), - DECLARE_NAPI_FUNCTION("goToRow", GoToRow), - DECLARE_NAPI_FUNCTION("getBlob", GetBlob), - DECLARE_NAPI_FUNCTION("getString", GetString), - DECLARE_NAPI_FUNCTION("getLong", GetLong), - DECLARE_NAPI_FUNCTION("getDouble", GetDouble), - DECLARE_NAPI_FUNCTION("close", Close), - DECLARE_NAPI_FUNCTION("getColumnIndex", GetColumnIndex), - DECLARE_NAPI_FUNCTION("getColumnName", GetColumnName), - DECLARE_NAPI_FUNCTION("getDataType", GetDataType), - - DECLARE_NAPI_GETTER("columnNames", GetAllColumnNames), - DECLARE_NAPI_GETTER("columnCount", GetColumnCount), - DECLARE_NAPI_GETTER("rowCount", GetRowCount), - DECLARE_NAPI_GETTER("isClosed", IsClosed), - }; - NAPI_CALL(env, napi_define_class(env, "DataShareResultSet", NAPI_AUTO_LENGTH, Initialize, nullptr, - sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons)); - NAPI_CALL(env, napi_create_reference(env, cons, 1, &ctorRef_)); - return cons; -} - -napi_value DataShareResultSetProxy::Initialize(napi_env env, napi_callback_info info) -{ - napi_value self = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr)); - auto *proxy = new DataShareResultSetProxy(); - auto finalize = [](napi_env env, void *data, void *hint) { - DataShareResultSetProxy *proxy = reinterpret_cast(data); - delete proxy; - }; - napi_status status = napi_wrap(env, self, proxy, finalize, nullptr, nullptr); - if (status != napi_ok) { - LOG_ERROR("DataShareResultSetProxy napi_wrap failed! code:%{public}d!", status); - finalize(env, proxy, nullptr); - return nullptr; - } - return self; -} - -DataShareResultSetProxy::~DataShareResultSetProxy() -{ - LOG_INFO("DataShareResultSetProxy destructor!"); - if (resultSet_ != nullptr && !resultSet_->IsClosed()) { - resultSet_->Close(); - } -} - -DataShareResultSetProxy::DataShareResultSetProxy(std::shared_ptr resultSet) -{ - if (resultSet_ == resultSet) { - return; - } - resultSet_ = std::move(resultSet); -} - -DataShareResultSetProxy &DataShareResultSetProxy::operator=(std::shared_ptr resultSet) -{ - if (resultSet_ == resultSet) { - return *this; - } - resultSet_ = std::move(resultSet); - return *this; -} - -std::shared_ptr &DataShareResultSetProxy::GetInnerResultSet(napi_env env, - napi_callback_info info) -{ - DataShareResultSetProxy *resultSet = nullptr; - napi_value self = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr); - napi_unwrap(env, self, reinterpret_cast(&resultSet)); - return resultSet->resultSet_; -} - -napi_value DataShareResultSetProxy::GoToFirstRow(napi_env env, napi_callback_info info) -{ - int errCode = E_ERROR; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - errCode = nativeResultSet->GoToFirstRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToFirstRow failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK)); -} - -napi_value DataShareResultSetProxy::GoToLastRow(napi_env env, napi_callback_info info) -{ - int errCode = E_ERROR; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - errCode = nativeResultSet->GoToLastRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToLastRow failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK)); -} - -napi_value DataShareResultSetProxy::GoToNextRow(napi_env env, napi_callback_info info) -{ - int errCode = E_ERROR; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - errCode = nativeResultSet->GoToNextRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToNextRow failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK)); -} - -napi_value DataShareResultSetProxy::GoToPreviousRow(napi_env env, napi_callback_info info) -{ - int errCode = E_ERROR; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - errCode = nativeResultSet->GoToPreviousRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToPreviousRow failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK)); -} - -napi_value DataShareResultSetProxy::GoTo(napi_env env, napi_callback_info info) -{ - int32_t offset = -1; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &offset)); - int errCode = E_ERROR; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - errCode = nativeResultSet->GoTo(offset); - if (errCode != E_OK) { - LOG_ERROR("GoTo failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK)); -} - -napi_value DataShareResultSetProxy::GoToRow(napi_env env, napi_callback_info info) -{ - int32_t position = -1; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &position)); - int errCode = E_ERROR; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - errCode = nativeResultSet->GoToRow(position); - if (errCode != E_OK) { - LOG_ERROR("GoToRow failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK)); -} - -napi_value DataShareResultSetProxy::GetBlob(napi_env env, napi_callback_info info) -{ - int32_t columnIndex = -1; - std::vector blob; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex)); - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetBlob(columnIndex, blob); - if (errCode != E_OK) { - LOG_ERROR("GetBlob failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, blob); -} - -napi_value DataShareResultSetProxy::GetString(napi_env env, napi_callback_info info) -{ - int32_t columnIndex = -1; - std::string value; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex)); - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetString(columnIndex, value); - if (errCode != E_OK) { - LOG_ERROR("GetString failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, value); -} - -napi_value DataShareResultSetProxy::GetLong(napi_env env, napi_callback_info info) -{ - int32_t columnIndex = -1; - int64_t value = -1; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex)); - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetLong(columnIndex, value); - if (errCode != E_OK) { - LOG_ERROR("GetLong failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, value); -} - -napi_value DataShareResultSetProxy::GetDouble(napi_env env, napi_callback_info info) -{ - int32_t columnIndex = -1; - double value = 0.0; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex)); - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetDouble(columnIndex, value); - if (errCode != E_OK) { - LOG_ERROR("GetDouble failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, value); -} - -napi_value DataShareResultSetProxy::Close(napi_env env, napi_callback_info info) -{ - int errCode = E_ERROR; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - errCode = nativeResultSet->Close(); - if (errCode != E_OK) { - LOG_ERROR("Close failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK)); -} - -napi_value DataShareResultSetProxy::GetColumnIndex(napi_env env, napi_callback_info info) -{ - int32_t columnIndex = -1; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - std::string columnName = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE); - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetColumnIndex(columnName, columnIndex); - if (errCode != E_OK) { - LOG_ERROR("GetColumnIndex failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, columnIndex); -} - -napi_value DataShareResultSetProxy::GetColumnName(napi_env env, napi_callback_info info) -{ - int32_t columnIndex = -1; - std::string columnName; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex)); - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetColumnName(columnIndex, columnName); - if (errCode != E_OK) { - LOG_ERROR("GetColumnName failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, columnName); -} - -napi_value DataShareResultSetProxy::GetDataType(napi_env env, napi_callback_info info) -{ - int32_t columnIndex = -1; - DataType dataType = DataType::TYPE_NULL; - size_t argc = MAX_INPUT_COUNT; - napi_value args[MAX_INPUT_COUNT] = { 0 }; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - NAPI_ASSERT(env, argc > 0, "Invalid argvs!"); - NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex)); - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetDataType(columnIndex, dataType); - if (errCode != E_OK) { - LOG_ERROR("GetDataType failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, int32_t(dataType)); -} - -napi_value DataShareResultSetProxy::GetAllColumnNames(napi_env env, napi_callback_info info) -{ - std::vector columnNames; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetAllColumnNames(columnNames); - if (errCode != E_OK) { - LOG_ERROR("GetAllColumnNames failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, columnNames); -} - -napi_value DataShareResultSetProxy::GetColumnCount(napi_env env, napi_callback_info info) -{ - int32_t count = -1; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetColumnCount(count); - if (errCode != E_OK) { - LOG_ERROR("GetColumnCount failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, count); -} - -napi_value DataShareResultSetProxy::GetRowCount(napi_env env, napi_callback_info info) -{ - int32_t count = -1; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - int errCode = nativeResultSet->GetRowCount(count); - if (errCode != E_OK) { - LOG_ERROR("GetRowCount failed code:%{public}d", errCode); - } - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - return DataShareJSUtils::Convert2JSValue(env, count); -} - -napi_value DataShareResultSetProxy::IsClosed(napi_env env, napi_callback_info info) -{ - bool result = false; - std::shared_ptr nativeResultSet = GetInnerResultSet(env, info); - if (nativeResultSet != nullptr) { - result = nativeResultSet->IsClosed(); - } else { - LOG_ERROR("GetInnerResultSet failed."); - } - napi_value output; - napi_get_boolean(env, result, &output); - return output; -} - -napi_value GetNapiResultSetObject(napi_env env, DataShareResultSet *resultSet) -{ - return DataShareResultSetProxy::NewInstance(env, std::shared_ptr(resultSet)); -} - -DataShareResultSet *GetResultSetProxyObject(const napi_env &env, const napi_value &arg) -{ - // the resultSet maybe release. - auto resultSet = DataShareResultSetProxy::GetNativeObject(env, arg); - return resultSet.get(); -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp b/data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp deleted file mode 100644 index 21722b4a1..000000000 --- a/data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp +++ /dev/null @@ -1,133 +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 "napi_datashare_values_bucket.h" - -#include "datashare_log.h" -#include "datashare_js_utils.h" -#include "datashare_value_object.h" - -#include "securec.h" - -namespace OHOS { -namespace DataShare { -napi_value DataShareValueBucketNewInstance(napi_env env, DataShareValuesBucket &valuesBucket) -{ - napi_value ret; - NAPI_CALL(env, napi_create_object(env, &ret)); - std::map valuesMap; - valuesBucket.GetAll(valuesMap); - std::map::iterator it; - for (it = valuesMap.begin(); it != valuesMap.end(); ++it) { - std::string key = it->first; - auto valueObject = it->second; - napi_value value = nullptr; - switch (valueObject.GetType()) { - case DataShareValueObjectType::TYPE_NULL: { - value = nullptr; - } break; - case DataShareValueObjectType::TYPE_INT: { - int64_t intVal = 0; - valueObject.GetLong(intVal); - value = DataShareJSUtils::Convert2JSValue(env, intVal); - } break; - case DataShareValueObjectType::TYPE_DOUBLE: { - double doubleVal = 0L; - valueObject.GetDouble(doubleVal); - value = DataShareJSUtils::Convert2JSValue(env, doubleVal); - } break; - case DataShareValueObjectType::TYPE_BLOB: { - std::vector blobVal; - valueObject.GetBlob(blobVal); - value = DataShareJSUtils::Convert2JSValue(env, blobVal); - } break; - case DataShareValueObjectType::TYPE_BOOL: { - bool boolVal = false; - valueObject.GetBool(boolVal); - value = DataShareJSUtils::Convert2JSValue(env, boolVal); - } break; - default: { - std::string strVal = ""; - valueObject.GetString(strVal); - value = DataShareJSUtils::Convert2JSValue(env, strVal); - } break; - } - NAPI_CALL(env, napi_set_named_property(env, ret, key.c_str(), value)); - } - - return ret; -} - -void SetValuesBucketObject( - DataShareValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value) -{ - napi_valuetype valueType = napi_undefined; - napi_typeof(env, value, &valueType); - if (valueType == napi_string) { - std::string valueString = DataShareJSUtils::UnwrapStringFromJS(env, value); - LOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:%{public}s", - valueType, keyStr.c_str(), valueString.c_str()); - valuesBucket.PutString(keyStr, valueString); - } else if (valueType == napi_number) { - double valueNumber = 0; - napi_get_value_double(env, value, &valueNumber); - valuesBucket.PutDouble(keyStr, valueNumber); - LOG_INFO( - "ValueObject type:%{public}d, key:%{public}s, value:%{public}lf", valueType, keyStr.c_str(), valueNumber); - } else if (valueType == napi_boolean) { - bool valueBool = false; - napi_get_value_bool(env, value, &valueBool); - LOG_INFO( - "ValueObject type:%{public}d, key:%{public}s, value:%{public}d", valueType, keyStr.c_str(), valueBool); - valuesBucket.PutBool(keyStr, valueBool); - } else if (valueType == napi_null) { - valuesBucket.PutNull(keyStr); - LOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:null", valueType, keyStr.c_str()); - } else if (valueType == napi_object) { - LOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:Uint8Array", valueType, keyStr.c_str()); - valuesBucket.PutBlob(keyStr, DataShareJSUtils::Convert2U8Vector(env, value)); - } else { - LOG_ERROR("valuesBucket error"); - } -} - -void AnalysisValuesBucket(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) -{ - napi_value keys = 0; - napi_get_property_names(env, arg, &keys); - uint32_t arrLen = 0; - napi_status status = napi_get_array_length(env, keys, &arrLen); - if (status != napi_ok) { - LOG_ERROR("ValuesBucket errr"); - return; - } - LOG_INFO("ValuesBucket num : %{public}u", arrLen); - for (size_t i = 0; i < arrLen; ++i) { - napi_value key = 0; - status = napi_get_element(env, keys, i, &key); - std::string keyStr = DataShareJSUtils::UnwrapStringFromJS(env, key); - napi_value value = 0; - napi_get_property(env, arg, key, &value); - - SetValuesBucketObject(valuesBucket, env, keyStr, value); - } -} - -void GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) -{ - AnalysisValuesBucket(valuesBucket, env, arg); -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/js/napi/dataShare/BUILD.gn b/data_share/frameworks/js/napi/dataShare/BUILD.gn deleted file mode 100644 index d70822eb9..000000000 --- a/data_share/frameworks/js/napi/dataShare/BUILD.gn +++ /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. - -import("//build/ohos.gni") -import("//foundation/distributeddatamgr/data_share/datashare.gni") - -ohos_shared_library("datashare") { - include_dirs = [ - "${datashare_napi_path}/dataShare/include", - "${datashare_common_napi_path}/include", - "${datashare_common_native_path}/include", - ] - - sources = [ - "${datashare_napi_path}/dataShare/src/async_call.cpp", - "${datashare_napi_path}/dataShare/src/napi_datashare_helper.cpp", - "${datashare_napi_path}/dataShare/src/napi_datashare_observer.cpp", - "${datashare_napi_path}/dataShare/src/native_datashare_module.cpp", - ] - - deps = [ - "${ability_runtime_inner_api_path}/dataobs_manager:dataobs_manager", - "${ability_runtime_napi_path}/inner/napi_common:napi_common", - "${datashare_innerapi_path}/common:datashare_common", - "//third_party/libuv:uv", - ] - - external_deps = [ - "ability_base:base", - "ability_base:want", - "ability_base:zuri", - "ability_runtime:abilitykit_native", - "ability_runtime:napi_base_context", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "data_share:datashare_abilitykit", - "data_share:datashare_common", - "eventhandler:libeventhandler", - "eventhandler:libeventhandler", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "napi:ace_napi", - "relational_store:native_appdatafwk", - "relational_store:native_dataability", - "relational_store:native_rdb", - ] - - relative_install_dir = "module/data" - - subsystem_name = "distributeddatamgr" - part_name = "data_share" -} - -ohos_shared_library("datasharepredicates") { - include_dirs = [ - "${datashare_common_napi_path}/include", - "${datashare_common_native_path}/include", - ] - - sources = [ - "${datashare_common_napi_path}/src/datashare_predicates_proxy.cpp", - "${datashare_napi_path}/dataShare/src/native_datashare_predicates_module.cpp", - ] - - deps = [ "${datashare_innerapi_path}/common:datashare_common" ] - - external_deps = [ - "c_utils:utils", - "data_share:datashare_abilitykit", - "data_share:datashare_common", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "napi:ace_napi", - ] - - relative_install_dir = "module/data" - - subsystem_name = "distributeddatamgr" - part_name = "data_share" -} diff --git a/data_share/frameworks/js/napi/dataShare/include/async_call.h b/data_share/frameworks/js/napi/dataShare/include/async_call.h deleted file mode 100644 index 2419863aa..000000000 --- a/data_share/frameworks/js/napi/dataShare/include/async_call.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef DATASHARE_ASYNC_CALL_H -#define DATASHARE_ASYNC_CALL_H - -#include -#include -#include "datashare_js_utils.h" -#include "napi/native_common.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -namespace OHOS::DataShare { -class AsyncCall final { -public: - class Context { - public: - using InputAction = std::function; - using OutputAction = std::function; - using ExecAction = std::function; - Context(InputAction input, OutputAction output): input_(std::move(input)), output_(std::move(output)) {}; - virtual ~Context() {}; - void SetAction(InputAction input, OutputAction output = nullptr) - { - input_ = input; - output_ = output; - } - - void SetAction(OutputAction output) - { - SetAction(nullptr, std::move(output)); - } - - virtual napi_status operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) - { - if (input_ == nullptr) { - return napi_ok; - } - return input_(env, argc, argv, self); - } - - virtual napi_status operator()(napi_env env, napi_value *result) - { - if (output_ == nullptr) { - *result = nullptr; - return napi_ok; - } - return output_(env, result); - } - - virtual void Exec() - { - if (exec_ == nullptr) { - return; - } - exec_(this); - }; - protected: - friend class AsyncCall; - InputAction input_ = nullptr; - OutputAction output_ = nullptr; - ExecAction exec_ = nullptr; - }; - - // The default AsyncCallback in the parameters is at the end position. - static constexpr size_t ASYNC_DEFAULT_POS = -1; - AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr context); - ~AsyncCall(); - napi_value Call(napi_env env, Context::ExecAction exec = nullptr); - napi_value SyncCall(napi_env env, Context::ExecAction exec = nullptr); -private: - enum { - ARG_ERROR, - ARG_DATA, - ARG_BUTT - }; - static void OnExecute(napi_env env, void *data); - static void OnComplete(napi_env env, napi_status status, void *data); - struct AsyncContext { - std::shared_ptr ctx = nullptr; - napi_ref callback = nullptr; - napi_ref self = nullptr; - napi_deferred defer = nullptr; - napi_async_work work = nullptr; - }; - static void DeleteContext(napi_env env, AsyncContext *context); - - AsyncContext *context_ = nullptr; - napi_env env_ = nullptr; -}; -} - -#endif // DATASHARE_ASYNC_CALL_H diff --git a/data_share/frameworks/js/napi/dataShare/include/data_share_common.h b/data_share/frameworks/js/napi/dataShare/include/data_share_common.h deleted file mode 100644 index 8fa9c22ab..000000000 --- a/data_share/frameworks/js/napi/dataShare/include/data_share_common.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_COMMON_H -#define DATASHARE_COMMON_H -#include "ability.h" -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "napi_common.h" -#include "datashare_helper.h" - -using Ability = OHOS::AppExecFwk::Ability; - -namespace OHOS { -namespace DataShare { -using namespace AppExecFwk; - -struct CBBase { - CallbackInfo cbInfo; - napi_async_work asyncWork; - napi_deferred deferred; - Ability *ability = nullptr; - AbilityType abilityType = AbilityType::UNKNOWN; - int errCode = 0; -}; - -class NAPIDataShareObserver; -struct DSHelperOnOffCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - sptr observer; - std::string uri; - int result = 0; - std::vector NotifyList; - std::vector DestoryList; -}; -} // namespace DataShare -} // namespace OHOS -#endif /* DATASHARE_COMMON_H */ diff --git a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h deleted file mode 100644 index 4f9c39565..000000000 --- a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h +++ /dev/null @@ -1,88 +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 NAPI_DATASHARE_HELPER_H -#define NAPI_DATASHARE_HELPER_H - -#include "async_call.h" -#include "datashare_helper.h" -#include "data_share_common.h" -#include "napi_datashare_observer.h" - -namespace OHOS { -namespace DataShare { -class NapiDataShareHelper { -public: - static napi_value Napi_CreateDataShareHelper(napi_env env, napi_callback_info info); - - static napi_value Napi_OpenFile(napi_env env, napi_callback_info info); - static napi_value Napi_On(napi_env env, napi_callback_info info); - static napi_value Napi_Off(napi_env env, napi_callback_info info); - static napi_value Napi_Insert(napi_env env, napi_callback_info info); - static napi_value Napi_Delete(napi_env env, napi_callback_info info); - static napi_value Napi_Query(napi_env env, napi_callback_info info); - static napi_value Napi_Update(napi_env env, napi_callback_info info); - static napi_value Napi_BatchInsert(napi_env env, napi_callback_info info); - static napi_value Napi_GetType(napi_env env, napi_callback_info info); - static napi_value Napi_GetFileTypes(napi_env env, napi_callback_info info); - static napi_value Napi_NormalizeUri(napi_env env, napi_callback_info info); - static napi_value Napi_DenormalizeUri(napi_env env, napi_callback_info info); - static napi_value Napi_NotifyChange(napi_env env, napi_callback_info info); -private: - static napi_value GetConstructor(napi_env env); - static napi_value Initialize(napi_env env, napi_callback_info info); - - std::shared_ptr datashareHelper_ = nullptr; - std::map> observerMap_; - - struct ContextInfo : public AsyncCall::Context { - NapiDataShareHelper *proxy = nullptr; - napi_status status = napi_generic_failure; - int resultNumber = 0; - std::shared_ptr resultObject = nullptr; - std::string resultString = ""; - std::vector resultStrArr; - - std::string uri; - std::string mode; - DataShareValuesBucket valueBucket; - DataSharePredicates predicates; - std::vector columns; - std::vector values; - std::string mimeTypeFilter; - - ContextInfo() : Context(nullptr, nullptr) {}; - ContextInfo(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {}; - virtual ~ContextInfo() {}; - - napi_status operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) override - { - NAPI_ASSERT_BASE(env, self != nullptr, "self is nullptr", napi_invalid_arg); - NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), napi_invalid_arg); - NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no native upload task", napi_invalid_arg); - return Context::operator()(env, argc, argv, self); - } - napi_status operator()(napi_env env, napi_value *result) override - { - if (status != napi_ok) { - return status; - } - return Context::operator()(env, result); - } - }; -}; -} // namespace DataShare -} // namespace OHOS -#endif /* NAPI_DATASHARE_HELPER_H */ diff --git a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_observer.h b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_observer.h deleted file mode 100644 index f10b49909..000000000 --- a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_observer.h +++ /dev/null @@ -1,45 +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 NAPI_DATASHARE_OBSERVER_H -#define NAPI_DATASHARE_OBSERVER_H - -#include -#include "data_ability_observer_stub.h" -#include "napi/native_common.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace DataShare { -class NAPIDataShareObserver : public AAFwk::DataAbilityObserverStub { -public: - NAPIDataShareObserver(napi_env env, napi_value callback); - virtual ~NAPIDataShareObserver(); - void OnChange() override; - void DeleteReference(); -private: - struct ObserverWorker { - const NAPIDataShareObserver *observer_ = nullptr; - ObserverWorker(const NAPIDataShareObserver *observerIn) : observer_(observerIn) {} - }; - - napi_env env_ = nullptr; - napi_ref ref_ = nullptr; - uv_loop_s *loop_ = nullptr; -}; -} // namespace DataShare -} // namespace OHOS -#endif /* DATASHARE_COMMON_H */ diff --git a/data_share/frameworks/js/napi/dataShare/src/async_call.cpp b/data_share/frameworks/js/napi/dataShare/src/async_call.cpp deleted file mode 100644 index 394aa833f..000000000 --- a/data_share/frameworks/js/napi/dataShare/src/async_call.cpp +++ /dev/null @@ -1,145 +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 "async_call.h" - -#include "datashare_log.h" -#include "napi_common_data.h" - -namespace OHOS::DataShare { -AsyncCall::AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr context) - : env_(env) -{ - context_ = new AsyncContext(); - size_t argc = ARGS_MAX_COUNT; - napi_value self = nullptr; - napi_value argv[ARGS_MAX_COUNT] = {nullptr}; - NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[argc - 1], &valueType); - if (valueType == napi_function) { - napi_create_reference(env, argv[argc - 1], 1, &context_->callback); - argc = argc - 1; - } - NAPI_CALL_RETURN_VOID(env, (*context)(env, argc, argv, self)); - context_->ctx = std::move(context); - napi_create_reference(env, self, 1, &context_->self); -} - -AsyncCall::~AsyncCall() -{ - if (context_ == nullptr) { - return; - } - - DeleteContext(env_, context_); -} - -napi_value AsyncCall::Call(napi_env env, Context::ExecAction exec) -{ - if ((context_ == nullptr) || (context_->ctx == nullptr)) { - LOG_DEBUG("context_ or context_->ctx is null"); - return nullptr; - } - LOG_DEBUG("async call exec"); - context_->ctx->exec_ = std::move(exec); - napi_value promise = nullptr; - if (context_->callback == nullptr) { - napi_create_promise(env, &context_->defer, &promise); - } else { - napi_get_undefined(env, &promise); - } - napi_async_work work = context_->work; - napi_value resource = nullptr; - napi_create_string_utf8(env, "AsyncCall", NAPI_AUTO_LENGTH, &resource); - napi_create_async_work(env, nullptr, resource, AsyncCall::OnExecute, AsyncCall::OnComplete, context_, &work); - context_->work = work; - context_ = nullptr; - napi_queue_async_work(env, work); - LOG_DEBUG("async call exec"); - return promise; -} - -napi_value AsyncCall::SyncCall(napi_env env, AsyncCall::Context::ExecAction exec) -{ - if ((context_ == nullptr) || (context_->ctx == nullptr)) { - LOG_DEBUG("context_ or context_->ctx is null"); - return nullptr; - } - context_->ctx->exec_ = std::move(exec); - napi_value promise = nullptr; - if (context_->callback == nullptr) { - napi_create_promise(env, &context_->defer, &promise); - } else { - napi_get_undefined(env, &promise); - } - AsyncCall::OnExecute(env, context_); - AsyncCall::OnComplete(env, napi_ok, context_); - return promise; -} - -void AsyncCall::OnExecute(napi_env env, void *data) -{ - LOG_DEBUG("run the async runnable"); - AsyncContext *context = reinterpret_cast(data); - context->ctx->Exec(); -} - -void AsyncCall::OnComplete(napi_env env, napi_status status, void *data) -{ - LOG_DEBUG("run the js callback function"); - AsyncContext *context = reinterpret_cast(data); - napi_value output = nullptr; - napi_status runStatus = (*context->ctx)(env, &output); - napi_value result[ARG_BUTT] = { 0 }; - if (status == napi_ok && runStatus == napi_ok) { - napi_get_undefined(env, &result[ARG_ERROR]); - if (output != nullptr) { - result[ARG_DATA] = output; - } else { - napi_get_undefined(env, &result[ARG_DATA]); - } - } else { - napi_value message = nullptr; - napi_create_string_utf8(env, "async call failed", NAPI_AUTO_LENGTH, &message); - napi_create_error(env, nullptr, message, &result[ARG_ERROR]); - napi_get_undefined(env, &result[ARG_DATA]); - } - if (context->defer != nullptr) { - // promise - if (status == napi_ok && runStatus == napi_ok) { - napi_resolve_deferred(env, context->defer, result[ARG_DATA]); - } else { - napi_reject_deferred(env, context->defer, result[ARG_ERROR]); - } - } else { - // callback - napi_value callback = nullptr; - napi_get_reference_value(env, context->callback, &callback); - napi_value returnValue; - napi_call_function(env, nullptr, callback, ARG_BUTT, result, &returnValue); - } - DeleteContext(env, context); -} -void AsyncCall::DeleteContext(napi_env env, AsyncContext *context) -{ - if (env != nullptr) { - napi_delete_reference(env, context->callback); - napi_delete_reference(env, context->self); - napi_delete_async_work(env, context->work); - } - delete context; -} -} \ No newline at end of file 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 deleted file mode 100644 index 45e185b68..000000000 --- a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp +++ /dev/null @@ -1,753 +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 "napi_datashare_helper.h" - -#include "napi_common_util.h" -#include "datashare_helper.h" -#include "datashare_log.h" -#include "napi_base_context.h" -#include "napi_datashare_values_bucket.h" -#include "datashare_predicates_proxy.h" -#include "datashare_result_set_proxy.h" - -using namespace OHOS::AAFwk; -using namespace OHOS::AppExecFwk; - -namespace OHOS { -namespace DataShare { -constexpr int MAX_ARGC = 6; - -std::list> g_dataShareHelperList; - -void UnwrapDataSharePredicates(DataSharePredicates &predicates, napi_env env, napi_value value) -{ - auto tempPredicates = DataSharePredicatesProxy::GetNativePredicates(env, value); - if (tempPredicates == nullptr) { - LOG_ERROR("UnwrapDataSharePredicates GetNativePredicates retval Marshalling failed."); - return; - } - predicates = *tempPredicates; -} - -bool UnwrapValuesBucketArrayFromJS(napi_env env, napi_value param, std::vector &value) -{ - LOG_INFO("UnwrapValuesBucketArrayFromJS in"); - uint32_t arraySize = 0; - napi_value jsValue = nullptr; - std::string strValue = ""; - - if (!IsArrayForNapiValue(env, param, arraySize)) { - LOG_INFO("IsArrayForNapiValue is false"); - return false; - } - - value.clear(); - for (uint32_t i = 0; i < arraySize; i++) { - jsValue = nullptr; - if (napi_get_element(env, param, i, &jsValue) != napi_ok) { - LOG_INFO("napi_get_element is false"); - return false; - } - - DataShareValuesBucket valueBucket; - valueBucket.Clear(); - GetValueBucketObject(valueBucket, env, jsValue); - - value.push_back(valueBucket); - } - LOG_INFO("UnwrapValuesBucketArrayFromJS out"); - return true; -} - -std::vector GetValuesBucketArray(napi_env env, napi_value param) -{ - LOG_INFO("NapiValueObject in"); - std::vector result; - UnwrapValuesBucketArrayFromJS(env, param, result); - return result; -} - -napi_value NapiDataShareHelper::Napi_CreateDataShareHelper(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_CreateDataShareHelper in"); - struct CreateContextInfo { - napi_ref ref = nullptr; - }; - auto ctxInfo = std::make_shared(); - auto input = [ctxInfo](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - LOG_DEBUG("CreateDataShareHelper parser to native params %{public}d", static_cast(argc)); - NAPI_ASSERT_BASE(env, (argc > 1) && (argc < 4), " need 2 or 3 parameters!", napi_invalid_arg); - napi_value helperProxy = nullptr; - napi_status status = napi_new_instance(env, GetConstructor(env), argc, argv, &helperProxy); - if ((helperProxy == nullptr) || (status != napi_ok)) { - return napi_generic_failure; - } - napi_create_reference(env, helperProxy, 1, &(ctxInfo->ref)); - return napi_ok; - }; - auto output = [ctxInfo](napi_env env, napi_value *result) -> napi_status { - napi_status status = napi_get_reference_value(env, ctxInfo->ref, result); - napi_delete_reference(env, ctxInfo->ref); - return status; - }; - auto context = std::make_shared(input, output); - AsyncCall asyncCall(env, info, context); - return asyncCall.Call(env); -} - -napi_value NapiDataShareHelper::GetConstructor(napi_env env) -{ - napi_value cons = nullptr; - napi_property_descriptor clzDes[] = { - DECLARE_NAPI_FUNCTION("openFile", Napi_OpenFile), - DECLARE_NAPI_FUNCTION("on", Napi_On), - DECLARE_NAPI_FUNCTION("off", Napi_Off), - DECLARE_NAPI_FUNCTION("insert", Napi_Insert), - DECLARE_NAPI_FUNCTION("delete", Napi_Delete), - DECLARE_NAPI_FUNCTION("query", Napi_Query), - DECLARE_NAPI_FUNCTION("update", Napi_Update), - DECLARE_NAPI_FUNCTION("batchInsert", Napi_BatchInsert), - DECLARE_NAPI_FUNCTION("getType", Napi_GetType), - DECLARE_NAPI_FUNCTION("getFileTypes", Napi_GetFileTypes), - DECLARE_NAPI_FUNCTION("normalizeUri", Napi_NormalizeUri), - DECLARE_NAPI_FUNCTION("denormalizeUri", Napi_DenormalizeUri), - DECLARE_NAPI_FUNCTION("notifyChange", Napi_NotifyChange), - }; - NAPI_CALL(env, napi_define_class(env, "DataShareHelper", NAPI_AUTO_LENGTH, Initialize, nullptr, - sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons)); - g_dataShareHelperList.clear(); - return cons; -} - -napi_value NapiDataShareHelper::Initialize(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Initialize in"); - napi_value self = nullptr; - size_t argc = ARGS_MAX_COUNT; - napi_value argv[ARGS_MAX_COUNT] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - NAPI_ASSERT(env, argc > 1, "Wrong number of arguments"); - - auto *proxy = new NapiDataShareHelper(); - std::string strUri; - bool isStageMode = false; - napi_status status = AbilityRuntime::IsStageContext(env, argv[PARAM0], isStageMode); - if (status != napi_ok || !isStageMode) { - auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); - strUri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - NAPI_ASSERT(env, ability != nullptr, "DataShareHelperConstructor: failed to get native ability"); - LOG_INFO("FA Model: strUri = %{public}s", strUri.c_str()); - proxy->datashareHelper_ = DataShareHelper::Creator(ability->GetContext(), strUri); - } else { - auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); - strUri = DataShareJSUtils::Convert2String(env, argv[PARAM1]); - NAPI_ASSERT(env, context != nullptr, "DataShareHelperConstructor: failed to get native context"); - LOG_INFO("Stage Model: strUri = %{public}s", strUri.c_str()); - proxy->datashareHelper_ = DataShareHelper::Creator(context, strUri); - } - NAPI_ASSERT(env, proxy->datashareHelper_ != nullptr, "proxy->datashareHelper_ is nullptr"); - g_dataShareHelperList.emplace_back(proxy->datashareHelper_); - auto finalize = [](napi_env env, void * data, void * hint) { - NapiDataShareHelper *proxy = reinterpret_cast(data); - if (proxy != nullptr) { - auto it = proxy->observerMap_.begin(); - while (it != proxy->observerMap_.end()) { - if (proxy->datashareHelper_ != nullptr) { - proxy->datashareHelper_->UnregisterObserver(Uri(it->first), it->second); - } - it->second->DeleteReference(); - } - proxy->observerMap_.clear(); - delete proxy; - } - }; - if (napi_wrap(env, self, proxy, finalize, nullptr, nullptr) != napi_ok) { - finalize(env, proxy, nullptr); - return nullptr; - } - return self; -} - -napi_value NapiDataShareHelper::Napi_OpenFile(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_OpenFile in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - - napi_typeof(env, argv[PARAM1], &valuetype); - if (valuetype == napi_string) { - context->mode = DataShareJSUtils::Convert2String(env, argv[PARAM1]); - LOG_INFO("mode : %{public}s", context->mode.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_int32(env, context->resultNumber, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultNumber = context->proxy->datashareHelper_->OpenFile(uri, context->mode); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_Insert(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_Insert in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - - context->valueBucket.Clear(); - GetValueBucketObject(context->valueBucket, env, argv[PARAM1]); - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_int32(env, context->resultNumber, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultNumber = context->proxy->datashareHelper_->Insert(uri, context->valueBucket); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_Delete(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_Delete in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - - UnwrapDataSharePredicates(context->predicates, env, argv[PARAM1]); - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_int32(env, context->resultNumber, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultNumber = context->proxy->datashareHelper_->Delete(uri, context->predicates); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_Query(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_Query in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 3 || argc == 4, " should 3 or 4 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - - UnwrapDataSharePredicates(context->predicates, env, argv[PARAM1]); - - context->columns = DataShareJSUtils::Convert2StrVector(env, argv[PARAM2], DataShareJSUtils::DEFAULT_BUF_SIZE); - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - *result = DataShareResultSetProxy::NewInstance(env, context->resultObject); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultObject = - context->proxy->datashareHelper_->Query(uri, context->predicates, context->columns); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_Update(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_Update in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 3 || argc == 4, " should 3 or 4 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - - UnwrapDataSharePredicates(context->predicates, env, argv[PARAM1]); - - context->valueBucket.Clear(); - GetValueBucketObject(context->valueBucket, env, argv[PARAM2]); - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_int32(env, context->resultNumber, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultNumber = - context->proxy->datashareHelper_->Update(uri, context->predicates, context->valueBucket); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_BatchInsert(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_BatchInsert in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - - context->values = GetValuesBucketArray(env, argv[PARAM1]); - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_int32(env, context->resultNumber, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultNumber = context->proxy->datashareHelper_->BatchInsert(uri, context->values); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_GetType(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_GetType in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_string_utf8(env, context->resultString.c_str(), NAPI_AUTO_LENGTH, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultString = context->proxy->datashareHelper_->GetType(uri); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_GetFileTypes(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_GetFileTypes in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - - napi_typeof(env, argv[PARAM1], &valuetype); - if (valuetype == napi_string) { - context->mimeTypeFilter = DataShareJSUtils::Convert2String(env, argv[PARAM1]); - LOG_INFO("mimeTypeFilter : %{public}s", context->mimeTypeFilter.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - *result = DataShareJSUtils::Convert2JSValue(env, context->resultStrArr); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->resultStrArr = context->proxy->datashareHelper_->GetFileTypes(uri, context->mimeTypeFilter); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_NormalizeUri(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_NormalizeUri in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_string_utf8(env, context->resultString.c_str(), NAPI_AUTO_LENGTH, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - Uri uriValue = context->proxy->datashareHelper_->NormalizeUri(uri); - context->resultString = uriValue.ToString(); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_DenormalizeUri(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_DenormalizeUri in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_create_string_utf8(env, context->resultString.c_str(), NAPI_AUTO_LENGTH, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - Uri uriValue = context->proxy->datashareHelper_->DenormalizeUri(uri); - context->resultString = uriValue.ToString(); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_NotifyChange(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("Napi_NotifyChange in"); - auto context = std::make_shared(); - auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg); - LOG_DEBUG("argc : %{public}d", static_cast(argc)); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); - if (valuetype == napi_string) { - context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - LOG_INFO("uri : %{public}s", context->uri.c_str()); - } else { - LOG_INFO("wrong type, should be napi_string"); - } - return napi_ok; - }; - auto output = [context](napi_env env, napi_value *result) -> napi_status { - napi_get_null(env, result); - return napi_ok; - }; - auto exec = [context](AsyncCall::Context *ctx) { - if (context->proxy->datashareHelper_ != nullptr) { - if (!context->uri.empty()) { - OHOS::Uri uri(context->uri); - context->proxy->datashareHelper_->NotifyChange(uri); - context->status = napi_ok; - } else { - LOG_ERROR("context->uri is empty"); - } - } else { - LOG_ERROR("dataShareHelper_ == nullptr"); - } - }; - context->SetAction(std::move(input), std::move(output)); - AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); - return asyncCall.Call(env, exec); -} - -napi_value NapiDataShareHelper::Napi_On(napi_env env, napi_callback_info info) -{ - LOG_INFO("Napi_On in"); - napi_value self = nullptr; - size_t argc = MAX_ARGC; - napi_value argv[MAX_ARGC] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - NAPI_ASSERT(env, argc == ARGS_THREE, "wrong count of args"); - - NapiDataShareHelper *proxy = nullptr; - NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), nullptr); - NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr); - NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr); - - napi_valuetype valueType; - NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valueType)); - if (valueType != napi_string) { - LOG_ERROR("type is not string"); - return nullptr; - } - std::string type = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - if (type != "dataChange") { - LOG_ERROR("wrong register type : %{public}s", type.c_str()); - return nullptr; - } - - NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valueType)); - NAPI_ASSERT_BASE(env, valueType == napi_string, "uri is not string", nullptr); - std::string uri = DataShareJSUtils::Convert2String(env, argv[PARAM1]); - - NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); - NAPI_ASSERT_BASE(env, valueType == napi_function, "callback is not a function", nullptr); - sptr observer(new (std::nothrow) NAPIDataShareObserver(env, argv[PARAM2])); - - auto obs = proxy->observerMap_.find(uri); - if (obs != proxy->observerMap_.end()) { - proxy->datashareHelper_->UnregisterObserver(Uri(uri), obs->second); - obs->second->DeleteReference(); - proxy->observerMap_.erase(uri); - } - proxy->datashareHelper_->RegisterObserver(Uri(uri), observer); - proxy->observerMap_.emplace(uri, observer); - - return nullptr; -} - -napi_value NapiDataShareHelper::Napi_Off(napi_env env, napi_callback_info info) -{ - LOG_INFO("Napi_Off in"); - napi_value self = nullptr; - size_t argc = MAX_ARGC; - napi_value argv[MAX_ARGC] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - NAPI_ASSERT(env, argc == ARGS_TWO || argc == ARGS_THREE, "wrong count of args"); - - NapiDataShareHelper *proxy = nullptr; - NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), nullptr); - NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr); - NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr); - - napi_valuetype valueType; - NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valueType)); - if (valueType != napi_string) { - LOG_ERROR("type is not string"); - return nullptr; - } - std::string type = DataShareJSUtils::Convert2String(env, argv[PARAM0]); - if (type != "dataChange") { - LOG_ERROR("wrong register type : %{public}s", type.c_str()); - return nullptr; - } - - NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valueType)); - NAPI_ASSERT_BASE(env, valueType == napi_string, "uri is not string", nullptr); - std::string uri = DataShareJSUtils::Convert2String(env, argv[PARAM1]); - - if (argc == ARGS_THREE) { - NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); - NAPI_ASSERT_BASE(env, valueType == napi_function, "callback is not a function", nullptr); - } - - auto obs = proxy->observerMap_.find(uri); - if (obs != proxy->observerMap_.end()) { - proxy->datashareHelper_->UnregisterObserver(Uri(uri), obs->second); - obs->second->DeleteReference(); - proxy->observerMap_.erase(uri); - } else { - LOG_DEBUG("this uri hasn't been registered"); - } - - return nullptr; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_observer.cpp b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_observer.cpp deleted file mode 100644 index 5c15fcc3a..000000000 --- a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_observer.cpp +++ /dev/null @@ -1,85 +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 "napi_datashare_observer.h" - -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -NAPIDataShareObserver::NAPIDataShareObserver(napi_env env, napi_value callback) - : env_(env) -{ - napi_create_reference(env, callback, 1, &ref_); - napi_get_uv_event_loop(env, &loop_); -} - -NAPIDataShareObserver::~NAPIDataShareObserver() {} - -void NAPIDataShareObserver::OnChange() -{ - LOG_DEBUG("OnChange called"); - if (ref_ == nullptr) { - LOG_ERROR("ref_ == nullptr"); - return; - } - ObserverWorker *observerWorker = new (std::nothrow)ObserverWorker(this); - if (observerWorker == nullptr) { - LOG_ERROR("Failed to create observerWorker"); - return; - } - uv_work_t *work = new (std::nothrow)uv_work_t(); - if (work == nullptr) { - LOG_ERROR("Failed to create uv work"); - return; - } - work->data = observerWorker; - int ret = uv_queue_work(loop_, work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - LOG_DEBUG("uv_queue_work start"); - std::shared_ptr innerWorker(reinterpret_cast(work->data)); - if (innerWorker->observer_->ref_ == nullptr) { - LOG_ERROR("innerWorker->observer_->ref_ is nullptr"); - return; - } - napi_value callback = nullptr; - napi_value args[2] = {0}; - napi_value global = nullptr; - napi_value result; - napi_get_reference_value(innerWorker->observer_->env_, - innerWorker->observer_->ref_, &callback); - napi_get_global(innerWorker->observer_->env_, &global); - napi_status callStatus = - napi_call_function(innerWorker->observer_->env_, global, callback, 2, args, &result); - if (callStatus != napi_ok) { - LOG_ERROR("napi_call_function failed status : %{public}d", callStatus); - } - }); - if (ret != 0) { - LOG_ERROR("uv_queue_work failed"); - delete observerWorker; - delete work; - } -} - -void NAPIDataShareObserver::DeleteReference() -{ - if (ref_ != nullptr) { - napi_delete_reference(env_, ref_); - ref_ = nullptr; - } -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp b/data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp deleted file mode 100644 index a4cb3a7b6..000000000 --- a/data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp +++ /dev/null @@ -1,61 +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 "napi/native_api.h" -#include "napi/native_node_api.h" - -#include "datashare_log.h" -#include "napi_datashare_helper.h" - -namespace OHOS { -namespace DataShare { -EXTERN_C_START -/* - * The module initialization. - */ -static napi_value Init(napi_env env, napi_value exports) -{ - LOG_DEBUG("Init in"); - napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("createDataShareHelper", NapiDataShareHelper::Napi_CreateDataShareHelper), - }; - napi_status status = napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc); - LOG_DEBUG("Init napi_define_properties status : %{public}d", status); - return exports; -} -EXTERN_C_END - -/* - * The module definition. - */ -static napi_module _module = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "data.dataShare", - .nm_priv = ((void *)0), - .reserved = {0} -}; - -/* - * The module registration. - */ -extern "C" __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&_module); -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/js/napi/dataShare/src/native_datashare_predicates_module.cpp b/data_share/frameworks/js/napi/dataShare/src/native_datashare_predicates_module.cpp deleted file mode 100644 index a26a45c43..000000000 --- a/data_share/frameworks/js/napi/dataShare/src/native_datashare_predicates_module.cpp +++ /dev/null @@ -1,58 +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 "napi/native_api.h" -#include "napi/native_node_api.h" - -#include "datashare_log.h" -#include "datashare_predicates_proxy.h" - -namespace OHOS { -namespace DataShare { -EXTERN_C_START -/* - * The module initialization. - */ -static napi_value Init(napi_env env, napi_value exports) -{ - LOG_INFO("DataSharePredicatesProxy module Init in"); - DataSharePredicatesProxy::Init(env, exports); - LOG_INFO("DataSharePredicatesProxy module Init out"); - return exports; -} -EXTERN_C_END - -/* - * The module definition. - */ -static napi_module _module = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "data.dataSharePredicates", - .nm_priv = ((void *)0), - .reserved = {0} -}; - -/* - * The module registration. - */ -extern "C" __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&_module); -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/js/napi/datashare_ext_ability/BUILD.gn b/data_share/frameworks/js/napi/datashare_ext_ability/BUILD.gn deleted file mode 100644 index 651ee9ff1..000000000 --- a/data_share/frameworks/js/napi/datashare_ext_ability/BUILD.gn +++ /dev/null @@ -1,50 +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("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni") -import("//build/ohos.gni") - -ts2abc_gen_abc("gen_datashare_ext_ability_abc") { - src_js = rebase_path("datashare_ext_ability.js") - dst_file = rebase_path(target_out_dir + "/datashare_ext_ability.abc") - in_puts = [ "datashare_ext_ability.js" ] - out_puts = [ target_out_dir + "/datashare_ext_ability.abc" ] - extra_args = [ "--module" ] -} - -gen_js_obj("datashare_ext_ability_js") { - input = "datashare_ext_ability.js" - output = target_out_dir + "/datashare_ext_ability.o" -} - -gen_js_obj("datashare_ext_ability_abc") { - input = get_label_info(":gen_datashare_ext_ability_abc", "target_out_dir") + - "/datashare_ext_ability.abc" - output = target_out_dir + "/datashare_ext_ability_abc.o" - dep = ":gen_datashare_ext_ability_abc" -} - -ohos_shared_library("datashareextensionability_napi") { - sources = [ "datashare_ext_ability_module.cpp" ] - - deps = [ - ":datashare_ext_ability_abc", - ":datashare_ext_ability_js", - ] - - external_deps = [ "napi:ace_napi" ] - - relative_install_dir = "module/application" - subsystem_name = "distributeddatamgr" - part_name = "data_share" -} diff --git a/data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability.js b/data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability.js deleted file mode 100644 index f8204f453..000000000 --- a/data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability.js +++ /dev/null @@ -1,66 +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. - */ - -class DataShareExtensionAbility { - onCreate(want, callback) { - console.log('onCreate, want:' + want.abilityName); - } - - getFileTypes(uri, mimeTypeFilter, callback) { - console.log('getFileTypes, uri:' + uri); - } - - openFile(uri, mode, callback) { - console.log('openFile, uri:' + uri); - } - - openRawFile(uri, mode, callback) { - console.log('openRawFile, uri:' + uri); - } - - insert(uri, value, callback) { - console.log('insert, uri:' + uri); - } - - update(uri, predicates, value, callback) { - console.log('update, uri:' + uri); - } - - delete(uri, predicates, callback) { - console.log('delete, uri:' + uri); - } - - query(uri, predicates, columns, callback) { - console.log('query, uri:' + uri); - } - - getType(uri, callback) { - console.log('getType, uri:' + uri); - } - - batchInsert(uri, values, callback) { - console.log('batchInsert, uri:' + uri); - } - - normalizeUri(uri, callback) { - console.log('normalizeUri, uri:' + uri); - } - - denormalizeUri(uri, callback) { - console.log('denormalizeUri, uri:' + uri); - } -} - -export default DataShareExtensionAbility \ No newline at end of file diff --git a/data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability_module.cpp b/data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability_module.cpp deleted file mode 100644 index 9e0d46b7a..000000000 --- a/data_share/frameworks/js/napi/datashare_ext_ability/datashare_ext_ability_module.cpp +++ /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. - */ - -#include "native_engine/native_engine.h" - -extern const char _binary_datashare_ext_ability_js_start[]; -extern const char _binary_datashare_ext_ability_js_end[]; -extern const char _binary_datashare_ext_ability_abc_start[]; -extern const char _binary_datashare_ext_ability_abc_end[]; - -extern "C" __attribute__((constructor)) -void NAPI_application_DataShareExtensionAbility_AutoRegister() -{ - auto moduleManager = NativeModuleManager::GetInstance(); - NativeModule newModuleInfo = { - .name = "application.DataShareExtensionAbility", - .fileName = "application/libdatashareextensionability_napi.so/DataShareExtensionAbility.js", - }; - - moduleManager->Register(&newModuleInfo); -} - -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbility_GetJSCode(const char **buf, int *bufLen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_js_start; - } - - if (bufLen != nullptr) { - *bufLen = _binary_datashare_ext_ability_js_end - _binary_datashare_ext_ability_js_start; - } -} - -// datashare extension ability JS register -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbility_GetABCCode(const char **buf, int *buflen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_abc_start; - } - if (buflen != nullptr) { - *buflen = _binary_datashare_ext_ability_abc_end - _binary_datashare_ext_ability_abc_start; - } -} \ No newline at end of file diff --git a/data_share/frameworks/js/napi/datashare_ext_ability_context/BUILD.gn b/data_share/frameworks/js/napi/datashare_ext_ability_context/BUILD.gn deleted file mode 100644 index b5ef94527..000000000 --- a/data_share/frameworks/js/napi/datashare_ext_ability_context/BUILD.gn +++ /dev/null @@ -1,51 +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("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni") -import("//build/ohos.gni") - -ts2abc_gen_abc("gen_datashare_ext_ability_context_abc") { - src_js = rebase_path("datashare_ext_ability_context.js") - dst_file = rebase_path(target_out_dir + "/datashare_ext_ability_context.abc") - in_puts = [ "datashare_ext_ability_context.js" ] - out_puts = [ target_out_dir + "/datashare_ext_ability_context.abc" ] - extra_args = [ "--module" ] -} - -gen_js_obj("datashare_ext_ability_context_js") { - input = "datashare_ext_ability_context.js" - output = target_out_dir + "/datashare_ext_ability_context.o" -} - -gen_js_obj("datashare_ext_ability_context_abc") { - input = - get_label_info(":gen_datashare_ext_ability_context_abc", - "target_out_dir") + "/datashare_ext_ability_context.abc" - output = target_out_dir + "/datashare_ext_ability_context_abc.o" - dep = ":gen_datashare_ext_ability_context_abc" -} - -ohos_shared_library("datashareextensionabilitycontext_napi") { - sources = [ "datashare_ext_ability_context_module.cpp" ] - - deps = [ - ":datashare_ext_ability_context_abc", - ":datashare_ext_ability_context_js", - ] - - external_deps = [ "napi:ace_napi" ] - - relative_install_dir = "module/application" - subsystem_name = "distributeddatamgr" - part_name = "data_share" -} diff --git a/data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context.js b/data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context.js deleted file mode 100644 index 68ddf9c89..000000000 --- a/data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context.js +++ /dev/null @@ -1,24 +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. - */ - -var ExtensionContext = requireNapi("application.ExtensionContext") - -class DataShareExtensionAbilityContext extends ExtensionContext { - constructor(obj) { - super(obj); - } -} - -export default DataShareExtensionAbilityContext \ No newline at end of file diff --git a/data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp b/data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp deleted file mode 100644 index 145456c2d..000000000 --- a/data_share/frameworks/js/napi/datashare_ext_ability_context/datashare_ext_ability_context_module.cpp +++ /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. - */ - -#include "native_engine/native_engine.h" - -extern const char _binary_datashare_ext_ability_context_js_start[]; -extern const char _binary_datashare_ext_ability_context_js_end[]; -extern const char _binary_datashare_ext_ability_context_abc_start[]; -extern const char _binary_datashare_ext_ability_context_abc_end[]; - -extern "C" __attribute__((constructor)) -void NAPI_application_DataShareExtensionAbilityContext_AutoRegister() -{ - auto moduleManager = NativeModuleManager::GetInstance(); - NativeModule newModuleInfo = { - .name = "application.DataShareExtensionAbilityContext", - .fileName = "application/libdatashareextensionabilitycontext_napi.so/DataShareExtensionAbilityContext.js", - }; - - moduleManager->Register(&newModuleInfo); -} - -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbilityContext_GetJSCode(const char **buf, int *bufLen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_context_js_start; - } - - if (bufLen != nullptr) { - *bufLen = _binary_datashare_ext_ability_context_js_end - _binary_datashare_ext_ability_context_js_start; - } -} - -// datashare extension ability context JS register -extern "C" __attribute__((visibility("default"))) -void NAPI_application_DataShareExtensionAbilityContext_GetABCCode(const char **buf, int *buflen) -{ - if (buf != nullptr) { - *buf = _binary_datashare_ext_ability_context_abc_start; - } - if (buflen != nullptr) { - *buflen = _binary_datashare_ext_ability_context_abc_end - _binary_datashare_ext_ability_context_abc_start; - } -} diff --git a/data_share/frameworks/native/common/include/datashare_abs_result_set.h b/data_share/frameworks/native/common/include/datashare_abs_result_set.h deleted file mode 100644 index 8824116df..000000000 --- a/data_share/frameworks/native/common/include/datashare_abs_result_set.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_ABS_RESULT_SET_H -#define DATASHARE_ABS_RESULT_SET_H - -#include -#include "result_set.h" - -namespace OHOS { -namespace DataShare { -class DataShareAbsResultSet : public ResultSet { -public: - DataShareAbsResultSet(); - virtual ~DataShareAbsResultSet(); - virtual int GetRowCount(int &count) override; - virtual int GetAllColumnNames(std::vector &columnNames) override; - virtual int GetBlob(int columnIndex, std::vector &blob) override; - virtual int GetString(int columnIndex, std::string &value) override; - virtual int GetInt(int columnIndex, int &value) override; - virtual int GetLong(int columnIndex, int64_t &value) override; - virtual int GetDouble(int columnIndex, double &value) override; - virtual int IsColumnNull(int columnIndex, bool &isNull) override; - virtual int GoToRow(int position) override; - virtual int GetDataType(int columnIndex, DataType &dataType) override; - int GetRowIndex(int &position) const override; - int GoTo(int offset) override; - int GoToFirstRow() override; - int GoToLastRow() override; - int GoToNextRow() override; - int GoToPreviousRow() override; - int IsAtFirstRow(bool &result) const override; - int IsAtLastRow(bool &result) override; - int IsStarted(bool &result) const override; - int IsEnded(bool &result) override; - int GetColumnCount(int &count) override; - int GetColumnIndex(const std::string &columnName, int &columnIndex) override; - int GetColumnName(int columnIndex, std::string &columnName) override; - bool IsClosed() const override; - int Close() override; - -protected: - // The default position of the result set - static const int INIT_POS = -1; - // Current row position - int rowPos_; - // Indicates whether the result set is closed - bool isClosed_; -}; -} // namespace DataShare -} // namespace OHOS - -#endif \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/datashare_block_writer_impl.h b/data_share/frameworks/native/common/include/datashare_block_writer_impl.h deleted file mode 100644 index c64ef9604..000000000 --- a/data_share/frameworks/native/common/include/datashare_block_writer_impl.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_BLOCK_WRITER_IMPL_H -#define DATASHARE_BLOCK_WRITER_IMPL_H - -#include "shared_block.h" -#include "result_set_bridge.h" -#include "datashare_errno.h" - -namespace OHOS { -namespace DataShare { -/** - * This class stores a set of rows from a database in a buffer, - * which is used as the set of query result. - */ -class DataShareBlockWriterImpl : public virtual ResultSetBridge::Writer { -public: - /** - * SharedBlock constructor. - */ - DataShareBlockWriterImpl(); - - /** - * SharedBlock constructor. - */ - DataShareBlockWriterImpl(const std::string &name, size_t size); - - /** - * SharedBlock Deconstruction. - */ - virtual ~DataShareBlockWriterImpl(); - - /** - * Clear current shared block. - */ - int Clear(); - - /** - * Set a shared block column. - */ - int SetColumnNum(uint32_t numColumns); - - /** - * Allocate a row unit and its directory. - */ - int AllocRow() override; - - /** - * Release the value of the last row. - */ - int FreeLastRow(); - - /** - * Write Null data to the shared block. - */ - virtual int Write(uint32_t column) override; - - /** - * Write long data to the shared block. - */ - virtual int Write(uint32_t column, int64_t value) override; - - /** - * Write Double data to the shared block. - */ - virtual int Write(uint32_t column, double value) override; - - /** - * Write blob data to the shared block. - */ - virtual int Write(uint32_t column, const uint8_t *value, size_t Size) override; - - /** - * Write string data to the shared block. - */ - virtual int Write(uint32_t column, const char *value, size_t sizeIncludingNull) override; - - /** - * The mHeader of the current result set. - */ - const void *GetHeader(); - - /** - * Size of the used byte in the block. - */ - size_t GetUsedBytes(); - - /** - * The name of the current result set. - */ - std::string Name(); - - /** - * The size of the current result set. - */ - size_t Size(); - - /** - * The row number of the current result set. - */ - uint32_t GetRowNum(); - - /** - * The column number of the current result set. - */ - uint32_t GetColumnNum(); - - /** - * Write raw data in block. - */ - size_t SetRawData(const void *rawData, size_t size); - - /** - * The fd of shared memory - */ - int GetFd(); - - /** - * Get Block - */ - AppDataFwk::SharedBlock *GetBlock() const; - -private: - /** - * The fd of shared memory - */ - bool GetCurrentRowIndex(uint32_t &rowIndex); - - /** - * Convert ShareBlock error code to DataShare format - */ - int ConvertErrorCode(int shareBlockErr) - { - return shareBlockErr == AppDataFwk::SharedBlock::SHARED_BLOCK_OK ? E_OK : E_ERROR; - } - -private: - AppDataFwk::SharedBlock *shareBlock_; -}; -} // namespace DataShare -} // namespace OHOS -#endif diff --git a/data_share/frameworks/native/common/include/datashare_log.h b/data_share/frameworks/native/common/include/datashare_log.h deleted file mode 100644 index 7f8025351..000000000 --- a/data_share/frameworks/native/common/include/datashare_log.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_LOG_PRINT_H -#define DATASHARE_LOG_PRINT_H - -#ifndef LOG_TAG -#define LOG_TAG -#endif - -#include "hilog/log.h" - -namespace OHOS::DataShare { -static const OHOS::HiviewDFX::HiLogLabel DATASHARE_LABEL = { LOG_CORE, 0xD001651, "DataShare" }; - -#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) - -#define LOG_DEBUG(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Debug(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_INFO(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Info(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_WARN(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Warn(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_ERROR(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Error(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_FATAL(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Fatal(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -} // namespace OHOS::DataShare -#endif diff --git a/data_share/frameworks/native/common/include/datashare_operation.h b/data_share/frameworks/native/common/include/datashare_operation.h deleted file mode 100644 index 4a81f688c..000000000 --- a/data_share/frameworks/native/common/include/datashare_operation.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_OPERATION_H -#define DATASHARE_OPERATION_H - -#include -#include -#include "datashare_operation_builder.h" -#include "datashare_predicates.h" -#include "datashare_values_bucket.h" -#include "uri.h" -#include "parcel.h" - -using Uri = OHOS::Uri; - -namespace OHOS { -namespace DataShare { -class DataShareOperationBuilder; -class DataShareOperation final : public Parcelable, public std::enable_shared_from_this { -public: - ~DataShareOperation(); - - DataShareOperation( - const std::shared_ptr &dataShareOperation, const std::shared_ptr &withUri); - explicit DataShareOperation(Parcel &in); - explicit DataShareOperation(const std::shared_ptr &builder); - DataShareOperation(); - /** - * @brief Creates an operation for inserting data. - * @param uri Indicates the path of data to operate. - * @return Returns an insert DataShareOperationBuilder object. - */ - static std::shared_ptr NewInsertBuilder(const std::shared_ptr &uri); - /** - * @brief Creates an operation for updating data. - * @param uri Indicates the path of data to operate. - * @return Returns an update DataShareOperationBuilder object. - */ - static std::shared_ptr NewUpdateBuilder(const std::shared_ptr &uri); - /** - * @brief Creates an operation for deleting data. - * @param uri Indicates the path of data to operate. - * @return Returns an delete DataShareOperationBuilder object. - */ - static std::shared_ptr NewDeleteBuilder(const std::shared_ptr &uri); - /** - * @brief Creates an operation for asserting data. - * @param uri Indicates the path of data to operate. - * @return Returns an assert DataShareOperationBuilder object. - */ - static std::shared_ptr NewAssertBuilder(const std::shared_ptr &uri); - /** - * @brief Obtains the value of the type attribute included in this DataShareOperation. - * @return Returns the type included in this DataShareOperation. - */ - int GetType() const; - /** - * @brief Obtains the value of the uri attribute included in this DataShareOperation. - * @return Returns the uri included in this DataShareOperation. - */ - std::shared_ptr GetUri() const; - /** - * @brief Obtains the value of the databaseValuesBucket attribute included in this DataShareOperation. - * @return Returns the databaseValuesBucket included in this DataShareOperation. - */ - std::shared_ptr GetValuesBucket() const; - /** - * @brief Obtains the value of the expectedCount attribute included in this DataShareOperation. - * @return Returns the expectedCount included in this DataShareOperation. - */ - int GetExpectedCount() const; - /** - * @brief Obtains the value of the dataBasePredicates attribute included in this DataShareOperation. - * @return Returns the dataBasePredicates included in this DataShareOperation. - */ - std::shared_ptr GetDataSharePredicates() const; - /** - * @brief Obtains the value of the valuesBucketReferences attribute included in this DataShareOperation. - * @return Returns the valuesBucketReferences included in this DataShareOperation. - */ - std::shared_ptr GetValuesBucketReferences() const; - /** - * @brief Obtains the value of the dataSharePredicatesBackReferences attribute included in this - * DataShareOperation. - * @return Returns the dataSharePredicatesBackReferences included in this DataShareOperation. - */ - std::map GetDataSharePredicatesBackReferences() const; - /** - * @brief Checks whether an insert operation is created. - * @return Returns true if it is an insert operation; returns false otherwise. - */ - bool IsInsertOperation() const; - /** - * @brief Checks whether an delete operation is created. - * @return Returns true if it is an delete operation; returns false otherwise. - */ - bool IsDeleteOperation() const; - /** - * @brief Checks whether an update operation is created. - * @return Returns true if it is an update operation; returns false otherwise. - */ - bool IsUpdateOperation() const; - /** - * @brief Checks whether an assert operation is created. - * @return Returns true if it is an assert operation; returns false otherwise. - */ - bool IsAssertOperation() const; - /** - * @brief Checks whether an operation can be interrupted. - * @return Returns true if the operation can be interrupted; returns false otherwise. - */ - bool IsInterruptionAllowed() const; - - bool operator==(const DataShareOperation &other) const; - DataShareOperation &operator=(const DataShareOperation &other); - bool Marshalling(Parcel &out) const; - static DataShareOperation *Unmarshalling(Parcel &in); - - /** - * @brief Creates a DataShareOperation instance based on the given Parcel object - * @param in Indicates the Parcel object. - * @return Returns the DataShareOperation object. - */ - static std::shared_ptr CreateFromParcel(Parcel &in); - -public: - static constexpr int TYPE_INSERT = 1; - static constexpr int TYPE_UPDATE = 2; - static constexpr int TYPE_DELETE = 3; - static constexpr int TYPE_ASSERT = 4; - -private: - void PutMap(Parcel &in); - bool ReadFromParcel(Parcel &in); - -private: - // no object in parcel - static constexpr int VALUE_NULL = 0; - // object exist in parcel - static constexpr int VALUE_OBJECT = 1; - static constexpr int REFERENCE_THRESHOLD = 3 * 1024 * 1024; - int type_ = -1; - int expectedCount_ = 0; - bool interrupted_ = false; - std::shared_ptr uri_ = nullptr; - std::shared_ptr valuesBucket_ = nullptr; - std::shared_ptr dataSharePredicates_ = nullptr; - std::shared_ptr valuesBucketReferences_ = nullptr; - std::map dataSharePredicatesBackReferences_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_OPERATION_H \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/datashare_operation_builder.h b/data_share/frameworks/native/common/include/datashare_operation_builder.h deleted file mode 100644 index 39866fbcd..000000000 --- a/data_share/frameworks/native/common/include/datashare_operation_builder.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_OPERATION_BUILDER_H -#define DATASHARE_OPERATION_BUILDER_H - -#include -#include -#include "datashare_operation.h" -#include "datashare_predicates.h" -#include "datashare_values_bucket.h" -#include "uri.h" -#include "parcel.h" - -using Uri = OHOS::Uri; -namespace OHOS { -namespace DataShare { -class DataShareOperation; -class DataShareOperationBuilder final : public std::enable_shared_from_this { - friend class DataShareOperation; - -public: - DataShareOperationBuilder(const int type, const std::shared_ptr &uri); - ~DataShareOperationBuilder(); - /** - * @brief Creates a DataShareOperation object. - * @return Returns the DataShareOperation object. - */ - std::shared_ptr Build(); - /** - * @brief Sets the data records to be inserted or updated. - * @param values Indicates the data values to be set. - * @return Returns a DataShareOperationBuilder object containing the given values parameter. - */ - std::shared_ptr WithValuesBucket(std::shared_ptr &values); - /** - * @brief Sets filter criteria used for deleting updating or assert query data. - * @param predicates Indicates the filter criteria to set. If this parameter is null, all data records will be - * operated by default. - * @return Returns an object containing the given filter criteria. - */ - std::shared_ptr WithPredicates(std::shared_ptr &predicates); - /** - * @brief Sets the expected number of rows to update ,delete or assert query. - * @param count Indicates the expected number of rows to update or delete. - * @return Returns a DataShareOperationBuilder object containing the given count parameter. - */ - std::shared_ptr WithExpectedCount(int count); - /** - * @brief Adds a back reference to be used as a filter criterion in withPredicates(DataSharePredicates). - * @param requestArgIndex Indicates the index referencing the predicate parameter whose value is to be replaced. - * @param previousResult Indicates the index referencing the historical DataShareResult used to replace the value - * of the specified predicate parameter. - * @return Returns a DataShareOperationBuilder object containing the given requestArgIndex and previousResult - * parameters. - */ - std::shared_ptr WithPredicatesBackReference(int requestArgIndex, int previousResult); - /** - * @brief Adds a back reference to be used in withValuesBucket(DataShareValuesBucket). - * @param backReferences Indicates the DataShareValuesBucket object containing a set of key-value pairs. - * In each pair, the key specifies the value to be updated and the value specifies. - * In each pair, the replace the specified value. This parameter cannot be null. - * @return Returns a DataShareOperationBuilder object containing the given backReferences parameter. - */ - std::shared_ptr WithValueBackReferences( - std::shared_ptr &backReferences); - /** - * @brief Sets an interrupt flag bit for a batch operation, which can be insert, update, delete, or assert. - * @param interrupted Specifies whether a batch operation can be interrupted. The value true indicates that the - * operation can be interrupted, and false indicates the opposite. - * @return Returns a DataShareOperationBuilder object containing the given interrupted parameter. - */ - std::shared_ptr WithInterruptionAllowed(bool interrupted); - -private: - int type_; - int expectedCount_; - bool interrupted_; - std::shared_ptr uri_; - std::shared_ptr valuesBucket_; - std::shared_ptr dataSharePredicates_; - std::shared_ptr valuesBucketReferences_; - std::map dataSharePredicatesBackReferences_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_OPERATION_BUILDER_H \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/datashare_result.h b/data_share/frameworks/native/common/include/datashare_result.h deleted file mode 100644 index 3490e2d50..000000000 --- a/data_share/frameworks/native/common/include/datashare_result.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_RESULT_H -#define DATASHARE_RESULT_H - -#include "parcel.h" -#include "uri.h" - -using Uri = OHOS::Uri; - -namespace OHOS { -namespace DataShare { -class DataShareResult final : public Parcelable { -public: - /** - * @brief A constructor used to create a DataShareResult instance - * with the input parameter count specified. - */ - explicit DataShareResult(int count); - - /** - * @brief A constructor used to create a DataShareResult instance - * with the input parameter uri specified - */ - explicit DataShareResult(const Uri &uri); - - /** - * @brief A constructor used to create a DataShareResult instance - * with a Parcel object specified. - */ - explicit DataShareResult(Parcel &parcel); - - /** - * @brief A constructor used to create a DataShareResult instance - * with input parameters uri, count, and failure specified. - */ - DataShareResult(const Uri &uri, int count); - - ~DataShareResult(); - - /** - * @brief Obtains the Uri object corresponding to the operation. - * @return Obtains the Uri object corresponding to the operation. - */ - Uri GetUri(); - - /** - * @brief Obtains the number of rows affected by the operation. - * @return Returns the number of rows affected by the operation. - */ - int GetCount(); - - /** - * @brief Prints out a string containing the class object information. - * @return Returns object information. - */ - std::string ToString(); - - /** - * @brief Marshals a DataShareResult object into a Parcel. - * @param parcel Indicates the Parcel object for marshalling. - * @return Returns true if the marshalling is successful; returns false otherwise. - */ - virtual bool Marshalling(Parcel &parcel) const; - - /** - * @brief Unmarshals a DataShareResult object from a Parcel. - * @param parcel Indicates the Parcel object for unmarshalling. - * @return Returns true if the unmarshalling is successful; returns false otherwise. - */ - static DataShareResult *Unmarshalling(Parcel &parcel); - - /** - * @brief Creates a DataShareResult instance based on the given Parcel object. - * Used to transfer DataShareResult object using Parcel. - * @param parcel Indicates the Parcel object. - * @return Returns the DataShareResult object. - */ - static DataShareResult *CreateFromParcel(Parcel &parcel); - -private: - Uri uri_; - int count_; - - bool ReadFromParcel(Parcel &parcel); - // no object in parcel - static constexpr int VALUE_NULL = -1; - // object exist in parcel - static constexpr int VALUE_OBJECT = 1; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_RESULT_H diff --git a/data_share/frameworks/native/common/include/datashare_shared_result_set.h b/data_share/frameworks/native/common/include/datashare_shared_result_set.h deleted file mode 100644 index c1b465cf8..000000000 --- a/data_share/frameworks/native/common/include/datashare_shared_result_set.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_SHARED_RESULT_SET_H -#define DATASHARE_SHARED_RESULT_SET_H - -#include -#include "shared_block.h" - -namespace OHOS { -namespace DataShare { -class DataShareSharedResultSet { -public: - DataShareSharedResultSet() {} - ~DataShareSharedResultSet() {} - /** - * Obtains a block from the {@link SharedResultSet} - */ - virtual AppDataFwk::SharedBlock *GetBlock() const = 0; - /** - * Adds the data of a {@code SharedResultSet} to a {@link SharedBlock} - */ - virtual void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) = 0; - /** - * Called when the position of the result set changes - */ - virtual bool OnGo(int oldRowIndex, int newRowIndex) = 0; -}; -} // namespace DataShare -} // namespace OHOS - -#endif \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/datashare_string_utils.h b/data_share/frameworks/native/common/include/datashare_string_utils.h deleted file mode 100644 index 3bfd570f1..000000000 --- a/data_share/frameworks/native/common/include/datashare_string_utils.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_STRINGUTILS_H -#define DATASHARE_STRINGUTILS_H - - -#include -#include - -namespace OHOS { -namespace DataShare { -class DataShareStringUtils { -public: - static std::string SurroundWithQuote(std::string value, std::string quote); - static std::string SurroundWithFunction(std::string function, std::string separator, - std::vector array); - static bool IsEmpty(std::string source) - { - return (source.empty()); - } - -private: - DataShareStringUtils(); - ~DataShareStringUtils(); -}; -} // namespace DataShare -} // namespace OHOS - -#endif \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/idatashare.h b/data_share/frameworks/native/common/include/idatashare.h deleted file mode 100644 index 50c367119..000000000 --- a/data_share/frameworks/native/common/include/idatashare.h +++ /dev/null @@ -1,221 +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 I_DATASHARE_H -#define I_DATASHARE_H - -#include -#include -#include "uri.h" - -#include "datashare_values_bucket.h" -#include "datashare_result.h" -#include "datashare_predicates.h" -#include "datashare_result_set.h" -#include "datashare_operation.h" - -namespace OHOS { -namespace AAFwk { -class IDataAbilityObserver; -} -namespace DataShare { -class IDataShare : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DataShare.IDataShare"); - - enum { - CMD_GET_FILE_TYPES = 1, - CMD_OPEN_FILE = 2, - CMD_OPEN_RAW_FILE = 3, - CMD_INSERT = 4, - CMD_UPDATE = 5, - CMD_DELETE = 6, - CMD_QUERY = 7, - CMD_GET_TYPE = 8, - CMD_BATCH_INSERT = 9, - CMD_REGISTER_OBSERVER = 10, - CMD_UNREGISTER_OBSERVER = 11, - CMD_NOTIFY_CHANGE = 12, - CMD_NORMALIZE_URI = 13, - CMD_DENORMALIZE_URI = 14, - CMD_EXECUTE_BATCH = 15, - }; - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0; - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - virtual int OpenFile(const Uri &uri, const std::string &mode) = 0; - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - virtual int OpenRawFile(const Uri &uri, const std::string &mode) = 0; - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) = 0; - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param value Indicates the data to update. This parameter can be null. - * - * @return Returns the number of data records updated. - */ - virtual int Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) = 0; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) = 0; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * - * @return Returns the query result. - */ - virtual std::shared_ptr Query( - const Uri &uri, const DataSharePredicates &predicates, std::vector &columns) = 0; - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - virtual std::string GetType(const Uri &uri) = 0; - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - virtual int BatchInsert(const Uri &uri, const std::vector &values) = 0; - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) = 0; - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) = 0; - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - * - * @return Return true if success. otherwise return false. - */ - virtual bool NotifyChange(const Uri &uri) = 0; - - /** - * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if - * the context has changed. If you implement URI normalization for a Data ability, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data ability must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data ability does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. - */ - virtual Uri NormalizeUri(const Uri &uri) = 0; - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri - * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot - * be found in the current environment. - */ - virtual Uri DenormalizeUri(const Uri &uri) = 0; - - /** - * @brief Performs batch operations on the database. - * - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - virtual std::vector> ExecuteBatch( - const std::vector> &operations) = 0; -}; -} // namespace DataShare -} // namespace OHOS -#endif // I_DATASHARE_H - diff --git a/data_share/frameworks/native/common/include/ishared_result_set.h b/data_share/frameworks/native/common/include/ishared_result_set.h deleted file mode 100644 index f8d7d1d12..000000000 --- a/data_share/frameworks/native/common/include/ishared_result_set.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_I_SHARED_RESULT_SET_H -#define DATASHARE_I_SHARED_RESULT_SET_H -#include -#include "iremote_broker.h" -#include "datashare_result_set.h" -namespace OHOS::DataShare { -class ISharedResultSet : public DataShareResultSet, public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DataShare.ISharedResultSet") - static std::shared_ptr ReadFromParcel(MessageParcel &parcel); - static sptr WriteToParcel(std::shared_ptr resultSet, - MessageParcel &parcel); - -protected: - enum { - FUNC_GET_ROW_COUNT, - FUNC_GET_ALL_COLUMN_NAMES, - FUNC_ON_GO, - FUNC_CLOSE, - FUNC_GET_BLOB, - FUNC_GET_STRING, - FUNC_GET_INT, - FUNC_GET_LONG, - FUNC_GET_DOUBLE, - FUNC_IS_COLUMN_NULL, - FUNC_GO_TO, - FUNC_GO_TO_ROW, - FUNC_GO_TO_FISTR_ROW, - FUNC_GO_TO_LAST_ROW, - FUNC_GO_TO_NEXT_ROW, - FUNC_GO_TO_PREV_ROW, - FUNC_IS_AT_FIRST_ROW, - FUNC_IS_AT_LAST_ROW, - FUNC_IS_STARTED_ROW, - FUNC_IS_ENDED_ROW, - FUNC_IS_CLOSED, - FUNC_GET_COLUMN_COUNT, - FUNC_GET_COLUMN_INDEX, - FUNC_GET_COLUMN_NAME, - FUNC_GET_COLUMN_TYPE, - FUNC_GET_ROW_INDEX, - FUNC_BUTT - }; - -private: - static std::function(MessageParcel &parcel)> consumerCreator_; - static std::function(std::shared_ptr, - MessageParcel &)> providerCreator_; -}; -} // namespace OHOS::DataShare - -#endif // DATASHARE_I_SHARED_RESULT_SET_H diff --git a/data_share/frameworks/native/common/include/ishared_result_set_proxy.h b/data_share/frameworks/native/common/include/ishared_result_set_proxy.h deleted file mode 100644 index 10d5be8bc..000000000 --- a/data_share/frameworks/native/common/include/ishared_result_set_proxy.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_I_SHARED_RESULT_SET_PROXY_H -#define DATASHARE_I_SHARED_RESULT_SET_PROXY_H -#include "ishared_result_set.h" -#include "iremote_proxy.h" -#include "datashare_errno.h" - -namespace OHOS::DataShare { -class ISharedResultSetProxy : public IRemoteProxy { -public: - static std::shared_ptr CreateProxy(MessageParcel &parcel); - explicit ISharedResultSetProxy(const sptr &impl); - virtual ~ISharedResultSetProxy() = default; - int GetAllColumnNames(std::vector &columnNames) override; - int GetRowCount(int &count) override; - bool OnGo(int oldRowIndex, int newRowIndex) override; - int Close() override; -private: - static BrokerDelegator delegator_; - std::vector columnNames_; - int32_t rowCount_ = -1; -}; -} // namespace OHOS::DataShare -#endif // DATASHARE_I_SHARED_RESULT_SET_PROXY_H diff --git a/data_share/frameworks/native/common/include/ishared_result_set_stub.h b/data_share/frameworks/native/common/include/ishared_result_set_stub.h deleted file mode 100644 index 9a9d2975e..000000000 --- a/data_share/frameworks/native/common/include/ishared_result_set_stub.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_I_SHARED_RESULT_SET_STUB_H -#define DATASHARE_I_SHARED_RESULT_SET_STUB_H -#include -#include -#include "safe_block_queue.h" -#include "ishared_result_set.h" -#include "iremote_stub.h" -namespace OHOS::DataShare { -class ISharedResultSetStub : public IRemoteStub { -public: - explicit ISharedResultSetStub(std::shared_ptr resultSet); - ~ISharedResultSetStub(); - static sptr CreateStub(std::shared_ptr resultSet, - MessageParcel &parcel); - int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - -protected: - int HandleGetRowCountRequest(MessageParcel &data, MessageParcel &reply); - int HandleGetAllColumnNamesRequest(MessageParcel &data, MessageParcel &reply); - int HandleOnGoRequest(MessageParcel &data, MessageParcel &reply); - int HandleCloseRequest(MessageParcel &data, MessageParcel &reply); - template - auto Submit(F&& func, Args&&... args) -> std::future::type> - { - auto exec = std::bind(std::forward(func), std::forward(args)...); - auto task = std::make_shared::type()>>(std::move(exec)); - auto future = task->get_future(); - runnables_.Push([task, this] { - bool isRunning = isRunning_; - (*task)(); - return isRunning; - }); - return future; - } - -private: - void Run(); - using Handler = int(ISharedResultSetStub::*)(MessageParcel &request, MessageParcel &reply); - static constexpr int MAX_RUNNABLE = 1024; - std::shared_ptr resultSet_; - SafeBlockQueue> runnables_; - bool isRunning_ = true; - std::thread thread_; - static constexpr Handler handlers[FUNC_BUTT] { - &ISharedResultSetStub::HandleGetRowCountRequest, - &ISharedResultSetStub::HandleGetAllColumnNamesRequest, - &ISharedResultSetStub::HandleOnGoRequest, - &ISharedResultSetStub::HandleCloseRequest, - }; -}; -} // namespace OHOS::DataShare - -#endif // DATASHARE_I_SHARED_RESULT_SET_STUB_H diff --git a/data_share/frameworks/native/common/include/result_set.h b/data_share/frameworks/native/common/include/result_set.h deleted file mode 100644 index ff94b1df7..000000000 --- a/data_share/frameworks/native/common/include/result_set.h +++ /dev/null @@ -1,229 +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_DATASHARE_COMMON_INCLUDE_RESULT_SET_H -#define NATIVE_DATASHARE_COMMON_INCLUDE_RESULT_SET_H - -#include -namespace OHOS { -namespace DataShare { -/* Value returned by getDataType(int) */ -enum class DataType { - TYPE_NULL = 0, - TYPE_INTEGER, - TYPE_FLOAT, - TYPE_STRING, - TYPE_BLOB, -}; - -class ResultSet { -public: - virtual ~ResultSet() {} - - /** - * Returns a string array holding the names of all of the columns in the - * result set. - * - * return the names of the columns contains in this query result. - */ - virtual int GetAllColumnNames(std::vector &columnNames) = 0; - - /** - * Return the total number of columns - * - * return the number of columns - */ - virtual int GetColumnCount(int &count) = 0; - - /** - * Returns data type of the given column's value. - * - * param columnIndex the zero-based index of the target column. - * return column value type. - */ - virtual int GetDataType(int columnIndex, DataType &dataType) = 0; - - /** - * Returns the zero-based index for the given column name. - * - * param columnName the name of the column. - * return the column index for the given column, or -1 if - * the column does not exist. - */ - virtual int GetColumnIndex(const std::string &columnName, int &columnIndex) = 0; - - /** - * Returns the column name at the given column index. - * - * param columnIndex the zero-based index. - * return the column name for the given index. - */ - virtual int GetColumnName(int columnIndex, std::string &columnName) = 0; - - /** - * return the numbers of rows in the result set. - */ - virtual int GetRowCount(int &count) = 0; - - /** - * Returns the current position of the cursor in the result set. - * The value is zero-based. When the result set is first returned the cursor - * will be at position -1, which is before the first row. - * After the last row is returned another call to next() will leave the cursor past - * the last entry, at a position of count(). - * - * return the current cursor position. - */ - virtual int GetRowIndex(int &position) const = 0; - - /** - * Move the cursor a relative amount from current position. Positive offset move forward, - * negative offset move backward. - * - * param offset the offset to be applied from the current position. - * return whether the requested move succeeded. - */ - virtual int GoTo(int offset) = 0; - - /** - * Move the cursor to an absolute position. - * - * param position the zero-based position to move to. - * return whether the requested move succeeded. - */ - virtual int GoToRow(int position) = 0; - - /** - * Move the cursor to the first row. - * - * return whether the requested move succeeded. - */ - virtual int GoToFirstRow() = 0; - - /** - * Move the cursor to the last row. - * - * return whether the requested move succeeded. - */ - virtual int GoToLastRow() = 0; - - /** - * Move the cursor to the next row. - * - * return whether the requested move succeeded. - */ - virtual int GoToNextRow() = 0; - - /** - * Move the cursor to the previous row. - * - * return whether the requested move succeeded. - */ - virtual int GoToPreviousRow() = 0; - - /** - * Returns whether the cursor is pointing to the position after the last - * row. - * - * return whether the cursor is before the first row. - */ - virtual int IsEnded(bool &result) = 0; - - /** - * Returns whether the cursor is pointing to the position before the first - * row. - * - * return whether the cursor is before the first row. - */ - virtual int IsStarted(bool &result) const = 0; - - /** - * Returns whether the cursor is pointing to the first row. - * - * return whether the cursor is pointing at the first entry. - */ - virtual int IsAtFirstRow(bool &result) const = 0; - - /** - * Returns whether the cursor is pointing to the last row. - * - * return whether the cursor is pointing at the last entry. - */ - virtual int IsAtLastRow(bool &result) = 0; - - /** - * Returns the value of the requested column as a byte array. - * - * param columnIndex the zero-based index of the target column. - * return the value of the requested column as a byte array. - */ - virtual int GetBlob(int columnIndex, std::vector &blob) = 0; - - /** - * Returns the value of the requested column as a String. - * - * param columnIndex the zero-based index of the target column. - * return the value of the requested column as a String. - */ - virtual int GetString(int columnIndex, std::string &value) = 0; - - /** - * Returns the value of the requested column as a int. - * - * param columnIndex the zero-based index of the target column. - * return the value of the requested column as a int. - */ - virtual int GetInt(int columnIndex, int &value) = 0; - - /** - * Returns the value of the requested column as a long. - * - * param columnIndex the zero-based index of the target column. - * return the value of the requested column as a long. - */ - virtual int GetLong(int columnIndex, int64_t &value) = 0; - - /** - * Returns the value of the requested column as a double. - * - * param columnIndex the zero-based index of the target column. - * return the value of the requested column as a double. - */ - virtual int GetDouble(int columnIndex, double &value) = 0; - - /** - * Whether the value of the requested column is null. - * - * param columnIndex the zero-based index of the target column. - * return whether the column value is null. - */ - virtual int IsColumnNull(int columnIndex, bool &isNull) = 0; - - /** - * Return true if the result set is closed. - * - * return true if the result set is closed. - */ - virtual bool IsClosed() const = 0; - - /** - * Closes the result set, releasing all of its resources and making it - * completely invalid. - */ - virtual int Close() = 0; -}; -} // namespace DataShare -} // namespace OHOS -#endif diff --git a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp b/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp deleted file mode 100644 index a7e6d81d3..000000000 --- a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp +++ /dev/null @@ -1,240 +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 "datashare_abs_result_set.h" -#include -#include "datashare_log.h" -#include "datashare_errno.h" - -namespace OHOS { -namespace DataShare { -DataShareAbsResultSet::DataShareAbsResultSet() : rowPos_(INIT_POS), isClosed_(false) -{} - -DataShareAbsResultSet::~DataShareAbsResultSet() {} - -int DataShareAbsResultSet::GetRowCount(int &count) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetAllColumnNames(std::vector &columnNames) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetBlob(int columnIndex, std::vector &blob) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetString(int columnIndex, std::string &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetInt(int columnIndex, int &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetLong(int columnIndex, int64_t &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetDouble(int columnIndex, double &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::IsColumnNull(int columnIndex, bool &isNull) -{ - return E_OK; -} - -int DataShareAbsResultSet::GoToRow(int position) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetDataType(int columnIndex, DataType &dataType) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetRowIndex(int &position) const -{ - position = rowPos_; - return E_OK; -} - -int DataShareAbsResultSet::GoTo(int offset) -{ - int ret = GoToRow(rowPos_ + offset); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GoTo return ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToFirstRow() -{ - int ret = GoToRow(0); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GoToFirstRow return ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToLastRow() -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GoToLastRow return GetRowCount::ret is wrong!"); - return ret; - } - - ret = GoToRow(rowCnt - 1); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GoToLastRow return GoToRow::ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToNextRow() -{ - int ret = GoToRow(rowPos_ + 1); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GoToNextRow return GoToRow::ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToPreviousRow() -{ - int ret = GoToRow(rowPos_ - 1); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GoToPreviousRow return GoToRow::ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::IsAtFirstRow(bool &result) const -{ - result = (rowPos_ == 0); - return E_OK; -} - -int DataShareAbsResultSet::IsAtLastRow(bool &result) -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::IsAtLastRow return GetRowCount::ret is wrong!"); - return ret; - } - result = (rowPos_ == (rowCnt - 1)); - return E_OK; -} - -int DataShareAbsResultSet::IsStarted(bool &result) const -{ - result = (rowPos_ != INIT_POS); - return E_OK; -} - -int DataShareAbsResultSet::IsEnded(bool &result) -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::IsEnded return GetRowCount::ret is wrong!"); - return ret; - } - result = (rowCnt == 0) ? true : (rowPos_ == rowCnt); - return E_OK; -} - -int DataShareAbsResultSet::GetColumnCount(int &count) -{ - std::vector columnNames; - int ret = GetAllColumnNames(columnNames); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GetColumnCount return GetAllColumnNames::ret is wrong!"); - return ret; - } - count = static_cast(columnNames.size()); - return E_OK; -} - -int DataShareAbsResultSet::GetColumnIndex(const std::string &columnName, int &columnIndex) -{ - auto periodIndex = columnName.rfind('.'); - std::string columnNameLower = columnName; - if (periodIndex != std::string::npos) { - columnNameLower = columnNameLower.substr(periodIndex + 1); - } - transform(columnNameLower.begin(), columnNameLower.end(), columnNameLower.begin(), ::tolower); - std::vector columnNames; - int ret = GetAllColumnNames(columnNames); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GetColumnIndex return GetAllColumnNames::ret is wrong!"); - return ret; - } - - columnIndex = 0; - for (const auto& name : columnNames) { - std::string lowerName = name; - transform(name.begin(), name.end(), lowerName.begin(), ::tolower); - if (lowerName == columnNameLower) { - return E_OK; - } - columnIndex++; - } - columnIndex = -1; - return E_ERROR; -} - -int DataShareAbsResultSet::GetColumnName(int columnIndex, std::string &columnName) -{ - int rowCnt = 0; - int ret = GetColumnCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("DataShareAbsResultSet::GetColumnName return GetColumnCount::ret is wrong!"); - return ret; - } - if (columnIndex >= rowCnt || columnIndex < 0) { - return E_INVALID_COLUMN_INDEX; - } - std::vector columnNames; - GetAllColumnNames(columnNames); - columnName = columnNames[columnIndex]; - return E_OK; -} - -bool DataShareAbsResultSet::IsClosed() const -{ - return isClosed_; -} - -int DataShareAbsResultSet::Close() -{ - isClosed_ = true; - return E_OK; -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp b/data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp deleted file mode 100644 index bc0d9653a..000000000 --- a/data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp +++ /dev/null @@ -1,211 +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 "datashare_block_writer_impl.h" -#include "datashare_log.h" -#include "datashare_errno.h" - -namespace OHOS { -namespace DataShare { -DataShareBlockWriterImpl::DataShareBlockWriterImpl() : shareBlock_(nullptr) -{ -} - -DataShareBlockWriterImpl::DataShareBlockWriterImpl(const std::string &name, size_t size) - : shareBlock_(nullptr) -{ - AppDataFwk::SharedBlock::Create(name, size, shareBlock_); -} - -DataShareBlockWriterImpl::~DataShareBlockWriterImpl() -{ -} - -int DataShareBlockWriterImpl::Clear() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::Clear shareBlock_ is nullptr"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->Clear()); -} - -int DataShareBlockWriterImpl::SetColumnNum(uint32_t numColumns) -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::SetColumnNum shareBlock_ is nullptr"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->SetColumnNum(numColumns)); -} - -int DataShareBlockWriterImpl::AllocRow() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::AllocRow shareBlock_ is nullptr"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->AllocRow()); -} - -int DataShareBlockWriterImpl::FreeLastRow() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::FreeLastRow shareBlock_ is nullptr"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->FreeLastRow()); -} - -int DataShareBlockWriterImpl::Write(uint32_t column) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_INFO("Write null fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutNull(currentRowIndex, column)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, int64_t value) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_INFO("Write long fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutLong(currentRowIndex, column, value)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, double value) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_INFO("Write double fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutDouble(currentRowIndex, column, value)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, const uint8_t *value, size_t size) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_INFO("Write blob fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutBlob(currentRowIndex, column, value, size)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, const char *value, size_t sizeIncludingNull) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_INFO("Write string fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutString(currentRowIndex, column, value, sizeIncludingNull)); -} - -const void *DataShareBlockWriterImpl::GetHeader() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::GetHeader shareBlock_ is nullptr"); - return nullptr; - } - return shareBlock_->GetHeader(); -} - -size_t DataShareBlockWriterImpl::GetUsedBytes() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::GetUsedBytes shareBlock_ is nullptr"); - return E_ERROR; - } - return shareBlock_->GetUsedBytes(); -} - -std::string DataShareBlockWriterImpl::Name() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::Name shareBlock_ is nullptr"); - } - return shareBlock_->Name(); -} - -size_t DataShareBlockWriterImpl::Size() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::Size shareBlock_ is nullptr"); - return E_ERROR; - } - return shareBlock_->Size(); -} - -uint32_t DataShareBlockWriterImpl::GetRowNum() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::GetRowNum shareBlock_ is nullptr"); - return E_ERROR; - } - return shareBlock_->GetRowNum(); -} - -uint32_t DataShareBlockWriterImpl::GetColumnNum() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::GetColumnNum shareBlock_ is nullptr"); - return E_ERROR; - } - return shareBlock_->GetColumnNum(); -} - -size_t DataShareBlockWriterImpl::SetRawData(const void *rawData, size_t size) -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::SetRawData shareBlock_ is nullptr"); - return E_ERROR; - } - return shareBlock_->SetRawData(rawData, size); -} - -int DataShareBlockWriterImpl::GetFd() -{ - if (shareBlock_ == nullptr) { - LOG_INFO("DataShareBlockWriterImpl::GetFd shareBlock_ is nullptr"); - return E_ERROR; - } - return shareBlock_->GetFd(); -} - -AppDataFwk::SharedBlock *DataShareBlockWriterImpl::GetBlock() const -{ - return shareBlock_; -} - -bool DataShareBlockWriterImpl::GetCurrentRowIndex(uint32_t &rowIndex) -{ - if (shareBlock_ == nullptr) { - LOG_INFO("shareBlock_ is nullptr"); - return false; - } - uint32_t rowNum = shareBlock_->GetRowNum(); - if (rowNum > 0) { - rowIndex = rowNum - 1; - return true; - } - return false; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/datashare_operation.cpp b/data_share/frameworks/native/common/src/datashare_operation.cpp deleted file mode 100644 index edb16b3a5..000000000 --- a/data_share/frameworks/native/common/src/datashare_operation.cpp +++ /dev/null @@ -1,482 +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 "datashare_operation.h" -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -DataShareOperation::DataShareOperation( - const std::shared_ptr &dataShareOperation, const std::shared_ptr &withUri) -{ - uri_ = withUri; - if (dataShareOperation != nullptr) { - type_ = dataShareOperation->type_; - valuesBucket_ = dataShareOperation->valuesBucket_; - expectedCount_ = dataShareOperation->expectedCount_; - dataSharePredicates_ = dataShareOperation->dataSharePredicates_; - valuesBucketReferences_ = dataShareOperation->valuesBucketReferences_; - dataSharePredicatesBackReferences_ = dataShareOperation->dataSharePredicatesBackReferences_; - interrupted_ = dataShareOperation->interrupted_; - } else { - type_ = 0; - expectedCount_ = 0; - valuesBucket_ = std::make_shared(); - dataSharePredicates_ = std::make_shared(); - valuesBucketReferences_ = std::make_shared(); - dataSharePredicatesBackReferences_.clear(); - interrupted_ = false; - } -} -DataShareOperation::DataShareOperation(Parcel &in) -{ - ReadFromParcel(in); -} -DataShareOperation::DataShareOperation(const std::shared_ptr &builder) -{ - if (builder != nullptr) { - type_ = builder->type_; - uri_ = builder->uri_; - valuesBucket_ = builder->valuesBucket_; - expectedCount_ = builder->expectedCount_; - dataSharePredicates_ = builder->dataSharePredicates_; - valuesBucketReferences_ = builder->valuesBucketReferences_; - dataSharePredicatesBackReferences_ = builder->dataSharePredicatesBackReferences_; - interrupted_ = builder->interrupted_; - } -} - -DataShareOperation::DataShareOperation() -{ - type_ = 0; - uri_ = nullptr; - expectedCount_ = 0; - valuesBucket_ = std::make_shared(); - dataSharePredicates_ = std::make_shared(); - valuesBucketReferences_ = std::make_shared(); - dataSharePredicatesBackReferences_.clear(); - interrupted_ = false; -} - -DataShareOperation::~DataShareOperation() -{ - dataSharePredicatesBackReferences_.clear(); -} - -bool DataShareOperation::operator==(const DataShareOperation &other) const -{ - if (type_ != other.type_) { - return false; - } - if ((uri_ != nullptr) && (other.uri_ != nullptr) && (uri_->ToString() != other.uri_->ToString())) { - return false; - } - if (expectedCount_ != other.expectedCount_) { - return false; - } - if (valuesBucket_ != other.valuesBucket_) { - return false; - } - if (dataSharePredicates_ != other.dataSharePredicates_) { - return false; - } - if (valuesBucketReferences_ != other.valuesBucketReferences_) { - return false; - } - size_t backReferencesCount = dataSharePredicatesBackReferences_.size(); - size_t otherBackReferencesCount = other.dataSharePredicatesBackReferences_.size(); - if (backReferencesCount != otherBackReferencesCount) { - return false; - } - - std::map::const_iterator it = dataSharePredicatesBackReferences_.begin(); - while (it != dataSharePredicatesBackReferences_.end()) { - std::map::const_iterator otherIt = other.dataSharePredicatesBackReferences_.find(it->first); - if (otherIt != other.dataSharePredicatesBackReferences_.end()) { - if (otherIt->second != it->second) { - return false; - } - } else { - return false; - } - ++it; - } - - if (interrupted_ != other.interrupted_) { - return false; - } - return true; -} - -DataShareOperation &DataShareOperation::operator=(const DataShareOperation &other) -{ - if (this != &other) { - type_ = other.type_; - uri_ = other.uri_; - expectedCount_ = other.expectedCount_; - valuesBucket_ = other.valuesBucket_; - dataSharePredicates_ = other.dataSharePredicates_; - valuesBucketReferences_ = other.valuesBucketReferences_; - dataSharePredicatesBackReferences_ = other.dataSharePredicatesBackReferences_; - interrupted_ = other.interrupted_; - } - return *this; -} - -std::shared_ptr DataShareOperation::NewInsertBuilder(const std::shared_ptr &uri) -{ - LOG_DEBUG("DataShareOperation::NewInsertBuilder start"); - if (uri == nullptr) { - LOG_ERROR("DataShareOperation::NewInsertBuilder uri is nullptr"); - return nullptr; - } - std::shared_ptr builder = - std::make_shared(TYPE_INSERT, uri); - LOG_DEBUG("DataShareOperation::NewInsertBuilder end"); - return builder; -} - -std::shared_ptr DataShareOperation::NewUpdateBuilder(const std::shared_ptr &uri) -{ - LOG_DEBUG("DataShareOperation::NewUpdateBuilder start"); - if (uri == nullptr) { - LOG_ERROR("DataShareOperation::NewUpdateBuilder uri is nullptr"); - return nullptr; - } - std::shared_ptr builder = - std::make_shared(TYPE_UPDATE, uri); - LOG_DEBUG("DataShareOperation::NewUpdateBuilder end"); - return builder; -} - -std::shared_ptr DataShareOperation::NewDeleteBuilder(const std::shared_ptr &uri) -{ - LOG_DEBUG("DataShareOperation::NewDeleteBuilder start"); - if (uri == nullptr) { - LOG_ERROR("DataShareOperation::NewDeleteBuilder uri is nullptr"); - return nullptr; - } - std::shared_ptr builder = - std::make_shared(TYPE_DELETE, uri); - LOG_DEBUG("DataShareOperation::NewDeleteBuilder end"); - return builder; -} - -std::shared_ptr DataShareOperation::NewAssertBuilder(const std::shared_ptr &uri) -{ - LOG_DEBUG("DataShareOperation::NewAssertBuilder start"); - if (uri == nullptr) { - LOG_ERROR("DataShareOperation::NewAssertBuilder uri is nullptr"); - return nullptr; - } - std::shared_ptr builder = - std::make_shared(TYPE_ASSERT, uri); - LOG_DEBUG("DataShareOperation::NewAssertBuilder end"); - return builder; -} - -int DataShareOperation::GetType() const -{ - LOG_DEBUG("DataShareOperation::GetType"); - return type_; -} - -std::shared_ptr DataShareOperation::GetUri() const -{ - LOG_DEBUG("DataShareOperation::GetUri"); - return uri_; -} - -std::shared_ptr DataShareOperation::GetValuesBucket() const -{ - LOG_DEBUG("DataShareOperation::GetValuesBucket"); - return valuesBucket_; -} - -int DataShareOperation::GetExpectedCount() const -{ - LOG_DEBUG("DataShareOperation::GetExpectedCount"); - return expectedCount_; -} - -std::shared_ptr DataShareOperation::GetDataSharePredicates() const -{ - LOG_DEBUG("DataShareOperation::GetDataSharePredicates"); - return dataSharePredicates_; -} - -std::shared_ptr DataShareOperation::GetValuesBucketReferences() const -{ - LOG_DEBUG("DataShareOperation::GetValuesBucketReferences"); - return valuesBucketReferences_; -} -std::map DataShareOperation::GetDataSharePredicatesBackReferences() const -{ - LOG_DEBUG("DataShareOperation::GetDataSharePredicatesBackReferences"); - return dataSharePredicatesBackReferences_; -} -bool DataShareOperation::IsInsertOperation() const -{ - LOG_DEBUG("DataShareOperation::IsInsertOperation:%d", type_ == TYPE_INSERT); - return type_ == TYPE_INSERT; -} -bool DataShareOperation::IsUpdateOperation() const -{ - LOG_DEBUG("DataShareOperation::IsUpdateOperation:%d", type_ == TYPE_UPDATE); - return type_ == TYPE_UPDATE; -} -bool DataShareOperation::IsDeleteOperation() const -{ - LOG_DEBUG("DataShareOperation::IsDeleteOperation:%d", type_ == TYPE_DELETE); - return type_ == TYPE_DELETE; -} -bool DataShareOperation::IsAssertOperation() const -{ - LOG_DEBUG("DataShareOperation::IsAssertOperation:%d", type_ == TYPE_ASSERT); - return type_ == TYPE_ASSERT; -} -bool DataShareOperation::IsInterruptionAllowed() const -{ - LOG_DEBUG("DataShareOperation::IsInterruptionAllowed:%d", interrupted_); - return interrupted_; -} -bool DataShareOperation::Marshalling(Parcel &out) const -{ - LOG_DEBUG("DataShareOperation::Marshalling start"); - if (!out.WriteInt32(type_)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(type_) error"); - return false; - } - if (!out.WriteInt32(expectedCount_)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - - if (!out.WriteBool(interrupted_)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - - if (uri_ != nullptr) { - if (!out.WriteInt32(VALUE_OBJECT)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - - if (!out.WriteParcelable(uri_.get())) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - } else { - if (!out.WriteInt32(VALUE_NULL)) { - return false; - } - } - - if (valuesBucket_ != nullptr) { - if (!out.WriteInt32(VALUE_OBJECT)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - - if (!DataShareValuesBucket::Marshalling(*valuesBucket_, out)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - } else { - if (!out.WriteInt32(VALUE_NULL)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - } - - if (dataSharePredicates_ != nullptr) { - if (!out.WriteInt32(VALUE_OBJECT)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - if (!out.WriteParcelable(dataSharePredicates_.get())) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - } else { - if (!out.WriteInt32(VALUE_NULL)) { - return false; - } - } - - if (valuesBucketReferences_ != nullptr) { - if (!out.WriteInt32(VALUE_OBJECT)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - if (!DataShareValuesBucket::Marshalling(*valuesBucketReferences_, out)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - } else { - if (!out.WriteInt32(VALUE_NULL)) { - return false; - } - } - - int referenceSize = 0; - if (!dataSharePredicatesBackReferences_.empty()) { - referenceSize = (int)dataSharePredicatesBackReferences_.size(); - if (!out.WriteInt32(referenceSize)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - if (referenceSize >= REFERENCE_THRESHOLD) { - LOG_INFO("DataShareOperation::Marshalling referenceSize >= REFERENCE_THRESHOLD"); - return true; - } - for (auto &it : dataSharePredicatesBackReferences_) { - if (!out.WriteInt32(it.first)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - if (!out.WriteInt32(it.second)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - } - } else { - LOG_DEBUG("DataShareOperation::Marshalling dataSharePredicatesBackReferences_ is empty"); - if (!out.WriteInt32(referenceSize)) { - LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); - return false; - } - } - - LOG_DEBUG("DataShareOperation::Marshalling end"); - return true; -} -DataShareOperation *DataShareOperation::Unmarshalling(Parcel &in) -{ - LOG_DEBUG("DataShareOperation::Unmarshalling start"); - DataShareOperation *dataShareOperation = new (std::nothrow) DataShareOperation(); - if (dataShareOperation != nullptr && !dataShareOperation->ReadFromParcel(in)) { - LOG_ERROR("DataShareOperation::Unmarshalling dataShareOperation error"); - delete dataShareOperation; - dataShareOperation = nullptr; - } - LOG_DEBUG("DataShareOperation::Unmarshalling end"); - return dataShareOperation; -} -bool DataShareOperation::ReadFromParcel(Parcel &in) -{ - LOG_DEBUG("DataShareOperation::ReadFromParcel start"); - if (!in.ReadInt32(type_)) { - LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(type_) error"); - return false; - } - if (!in.ReadInt32(expectedCount_)) { - LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error"); - return false; - } - interrupted_ = in.ReadBool(); - int empty = VALUE_NULL; - if (!in.ReadInt32(empty)) { - LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error"); - return false; - } - if (empty == VALUE_OBJECT) { - uri_.reset(in.ReadParcelable()); - } else { - uri_.reset(); - } - empty = VALUE_NULL; - if (!in.ReadInt32(empty)) { - LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error"); - return false; - } - LOG_DEBUG("DataShareOperation::ReadFromParcel empty is %{public}s", - empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL"); - if (empty == VALUE_OBJECT) { - valuesBucket_.reset(DataShareValuesBucket::Unmarshalling(in)); - } else { - valuesBucket_.reset(); - } - empty = VALUE_NULL; - if (!in.ReadInt32(empty)) { - LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error"); - return false; - } - LOG_DEBUG("DataShareOperation::ReadFromParcel empty is %{public}s", - empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL"); - if (empty == VALUE_OBJECT) { - dataSharePredicates_.reset(in.ReadParcelable()); - } else { - dataSharePredicates_.reset(); - } - empty = VALUE_NULL; - if (!in.ReadInt32(empty)) { - LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error"); - return false; - } - LOG_DEBUG("DataShareOperation::ReadFromParcel empty is %{public}s", - (empty == VALUE_OBJECT) ? "VALUE_OBJECT" : "VALUE_NULL"); - if (empty == VALUE_OBJECT) { - valuesBucketReferences_.reset(DataShareValuesBucket::Unmarshalling(in)); - } else { - valuesBucketReferences_.reset(); - } - int referenceSize = 0; - if (!in.ReadInt32(referenceSize)) { - LOG_ERROR("DataShareOperation::ReadFromParcel end"); - return false; - } - if (referenceSize >= REFERENCE_THRESHOLD) { - LOG_INFO("DataShareOperation::ReadFromParcel referenceSize:%{public}d >= REFERENCE_THRESHOLD:%{public}d", - referenceSize, REFERENCE_THRESHOLD); - return true; - } - for (int i = 0; i < REFERENCE_THRESHOLD && i < referenceSize; ++i) { - int first = 0; - int second = 0; - if (!in.ReadInt32(first)) { - LOG_ERROR("DataShareOperation::ReadFromParcel end"); - return false; - } - if (!in.ReadInt32(second)) { - LOG_ERROR("DataShareOperation::ReadFromParcel end"); - return false; - } - dataSharePredicatesBackReferences_.insert(std::make_pair(first, second)); - } - LOG_DEBUG("DataShareOperation::ReadFromParcel end"); - return true; -} -std::shared_ptr DataShareOperation::CreateFromParcel(Parcel &in) -{ - LOG_DEBUG("DataShareOperation::CreateFromParcel start"); - std::shared_ptr operation = std::make_shared(in); - LOG_DEBUG("DataShareOperation::CreateFromParcel end"); - return operation; -} -void DataShareOperation::PutMap(Parcel &in) -{ - LOG_DEBUG("DataShareOperation::PutMap start"); - int count = in.ReadInt32(); - if (count > 0 && count < REFERENCE_THRESHOLD) { - for (int i = 0; i < count; ++i) { - dataSharePredicatesBackReferences_.insert(std::make_pair(in.ReadInt32(), in.ReadInt32())); - } - } - LOG_DEBUG("DataShareOperation::PutMap end"); -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/datashare_operation_builder.cpp b/data_share/frameworks/native/common/src/datashare_operation_builder.cpp deleted file mode 100644 index 6c24f89a3..000000000 --- a/data_share/frameworks/native/common/src/datashare_operation_builder.cpp +++ /dev/null @@ -1,154 +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 "datashare_operation_builder.h" -#include "datashare_log.h" -#include "datashare_operation.h" -#include "datashare_value_object.h" -#include "datashare_values_bucket.h" -namespace OHOS::DataShare { class DataSharePredicates; } - -namespace OHOS { -namespace DataShare { -DataShareOperationBuilder::DataShareOperationBuilder(const int type, const std::shared_ptr &uri) -{ - type_ = type; - uri_ = uri; - expectedCount_ = 0; - interrupted_ = false; - valuesBucket_ = nullptr; - dataSharePredicates_ = nullptr; - valuesBucketReferences_ = nullptr; - dataSharePredicatesBackReferences_.clear(); -} -DataShareOperationBuilder::~DataShareOperationBuilder() -{ - dataSharePredicatesBackReferences_.clear(); -} - -std::shared_ptr DataShareOperationBuilder::Build() -{ - LOG_DEBUG("DataShareOperationBuilder::Build start"); - if (type_ != DataShareOperation::TYPE_UPDATE || (valuesBucket_ != nullptr && !valuesBucket_->IsEmpty())) { - std::shared_ptr operation = std::make_shared(shared_from_this()); - LOG_DEBUG("DataShareOperationBuilder::Build end"); - return operation; - } - LOG_ERROR("DataShareOperationBuilder::Build return nullptr"); - return nullptr; -} -std::shared_ptr DataShareOperationBuilder::WithValuesBucket( - std::shared_ptr &values) -{ - LOG_DEBUG("DataShareOperationBuilder::WithValuesBucket start"); - if (type_ != DataShareOperation::TYPE_INSERT && type_ != DataShareOperation::TYPE_UPDATE && - type_ != DataShareOperation::TYPE_ASSERT) { - LOG_ERROR( - "DataShareOperationBuilder::WithValuesBucket only inserts, updates can have values, type=%{public}d", - type_); - return nullptr; - } - - std::map valuesMap; - values->GetAll(valuesMap); - - valuesBucket_.reset(new (std::nothrow) DataShareValuesBucket(valuesMap)); - LOG_DEBUG("DataShareOperationBuilder::WithValuesBucket end"); - return shared_from_this(); -} - -std::shared_ptr DataShareOperationBuilder::WithPredicates( - std::shared_ptr &predicates) -{ - LOG_DEBUG("DataShareOperationBuilder::WithPredicates start"); - if (type_ != DataShareOperation::TYPE_DELETE && type_ != DataShareOperation::TYPE_UPDATE && - type_ != DataShareOperation::TYPE_ASSERT) { - LOG_ERROR( - "DataShareOperationBuilder::withPredicates only deletes and updates can have selections, type=%{public}d", - type_); - return nullptr; - } - dataSharePredicates_ = predicates; - LOG_DEBUG("DataShareOperationBuilder::WithPredicates end"); - return shared_from_this(); -} -std::shared_ptr DataShareOperationBuilder::WithExpectedCount(int count) -{ - LOG_DEBUG("DataShareOperationBuilder::WithExpectedCount start"); - LOG_INFO("DataShareOperationBuilder::WithExpectedCount expectedCount:%{public}d", count); - if (type_ != DataShareOperation::TYPE_UPDATE && type_ != DataShareOperation::TYPE_DELETE && - type_ != DataShareOperation::TYPE_ASSERT) { - LOG_ERROR("DataShareOperationBuilder::withExpectedCount only updates, deletes can have expected counts, " - "type=%{public}d", - type_); - return nullptr; - } - expectedCount_ = count; - LOG_DEBUG("DataShareOperationBuilder::WithExpectedCount end"); - return shared_from_this(); -} -std::shared_ptr DataShareOperationBuilder::WithPredicatesBackReference( - int requestArgIndex, int previousResult) -{ - LOG_DEBUG("DataShareOperationBuilder::WithPredicatesBackReference start"); - LOG_INFO("DataShareOperationBuilder::WithPredicatesBackReference requestArgIndex:%{public}d, " - "previousResult:%{public}d", - requestArgIndex, - previousResult); - if (type_ != DataShareOperation::TYPE_UPDATE && type_ != DataShareOperation::TYPE_DELETE && - type_ != DataShareOperation::TYPE_ASSERT) { - LOG_ERROR( - "DataShareOperationBuilder::withPredicatesBackReference only updates, deletes, and asserts can have " - "select back-references, type=%{public}d", - type_); - return nullptr; - } - dataSharePredicatesBackReferences_.insert(std::make_pair(requestArgIndex, previousResult)); - LOG_DEBUG("DataShareOperationBuilder::WithPredicatesBackReference end"); - return shared_from_this(); -} -std::shared_ptr DataShareOperationBuilder::WithValueBackReferences( - std::shared_ptr &backReferences) -{ - LOG_DEBUG("DataShareOperationBuilder::WithValueBackReferences start"); - if (type_ != DataShareOperation::TYPE_INSERT && type_ != DataShareOperation::TYPE_UPDATE && - type_ != DataShareOperation::TYPE_ASSERT) { - LOG_ERROR("DataShareOperationBuilder::withValueBackReferences only inserts, updates, and asserts can have " - "value back-references, type=%{public}d", - type_); - return nullptr; - } - valuesBucketReferences_ = backReferences; - LOG_DEBUG("DataShareOperationBuilder::WithValueBackReferences end"); - return shared_from_this(); -} -std::shared_ptr DataShareOperationBuilder::WithInterruptionAllowed(bool interrupted) -{ - LOG_DEBUG("DataShareOperationBuilder::WithInterruptionAllowed start"); - LOG_INFO("DataShareOperationBuilder::WithInterruptionAllowed interrupted=%{public}d", interrupted); - if (type_ != DataShareOperation::TYPE_INSERT && type_ != DataShareOperation::TYPE_UPDATE && - type_ != DataShareOperation::TYPE_ASSERT && type_ != DataShareOperation::TYPE_DELETE) { - LOG_ERROR( - "DataShareOperationBuilder::withInterruptionAllowed only inserts, updates, delete, and asserts can " - "have value back-references, type=%{public}d", - type_); - return nullptr; - } - interrupted_ = interrupted; - LOG_DEBUG("DataShareOperationBuilder::WithInterruptionAllowed end"); - return shared_from_this(); -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/datashare_predicates.cpp b/data_share/frameworks/native/common/src/datashare_predicates.cpp deleted file mode 100644 index dac66a601..000000000 --- a/data_share/frameworks/native/common/src/datashare_predicates.cpp +++ /dev/null @@ -1,559 +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 "datashare_predicates.h" -#include "datashare_log.h" -#include "datashare_errno.h" -namespace OHOS { -namespace DataShare { -DataSharePredicates::DataSharePredicates() -{ -} - -DataSharePredicates::DataSharePredicates(Predicates &predicates) - : predicates_(predicates) -{ -} - -DataSharePredicates::~DataSharePredicates() -{ -} - -/** - * EqualTo - */ -DataSharePredicates *DataSharePredicates::EqualTo(const std::string &field, const DataSharePredicatesObject &value) -{ - LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str()); - SetOperationList(EQUAL_TO, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::EqualTo End"); - return this; -} - -/** - * NotEqualTo - */ -DataSharePredicates *DataSharePredicates::NotEqualTo(const std::string &field, const DataSharePredicatesObject &value) -{ - LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str()); - SetOperationList(NOT_EQUAL_TO, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::NotEqualTo End"); - return this; -} - -/** - * GreaterThan - */ -DataSharePredicates *DataSharePredicates::GreaterThan(const std::string &field, const DataSharePredicatesObject &value) -{ - LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str()); - SetOperationList(GREATER_THAN, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::GreaterThan End"); - return this; -} - -/** - * LessThan - */ -DataSharePredicates *DataSharePredicates::LessThan(const std::string &field, const DataSharePredicatesObject &value) -{ - LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str()); - SetOperationList(LESS_THAN, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::LessThan End"); - return this; -} - -/** - * GreaterThanOrEqualTo - */ -DataSharePredicates *DataSharePredicates::GreaterThanOrEqualTo(const std::string &field, - const DataSharePredicatesObject &value) -{ - LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str()); - SetOperationList(GREATER_THAN_OR_EQUAL_TO, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::GreaterThanOrEqualTo End"); - return this; -} - -/** - * LessThanOrEqualTo - */ -DataSharePredicates *DataSharePredicates::LessThanOrEqualTo(const std::string &field, - const DataSharePredicatesObject &value) -{ - LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str()); - SetOperationList(LESS_THAN_OR_EQUAL_TO, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::LessThanOrEqualTo End"); - return this; -} - -/** - * In - */ -DataSharePredicates *DataSharePredicates::In(const std::string &field, const DataSharePredicatesObject &value) -{ - LOG_DEBUG("DataSharePredicates::In Start field%{public}s", field.c_str()); - SetOperationList(IN, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::In End"); - return this; -} - -/** - * NotIn - */ -DataSharePredicates *DataSharePredicates::NotIn(const std::string &field, const DataSharePredicatesObject &value) -{ - LOG_DEBUG("DataSharePredicates::NotIn Start field%{public}s", field.c_str()); - SetOperationList(NOT_IN, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::NotIn End"); - return this; -} - -/** - * BeginWrap - */ -DataSharePredicates *DataSharePredicates::BeginWrap() -{ - LOG_DEBUG("DataSharePredicates::BeginWrap Start"); - SetOperationList(BEGIN_WARP, {}, {}, {}, ZERO_COUNT); - LOG_DEBUG("DataSharePredicates::BeginWrap End"); - return this; -} - -/** - * EndWrap - */ -DataSharePredicates *DataSharePredicates::EndWrap() -{ - LOG_DEBUG("DataSharePredicates::EndWrap Start"); - SetOperationList(END_WARP, {}, {}, {}, ZERO_COUNT); - LOG_DEBUG("DataSharePredicates::EndWrap End"); - return this; -} - -/** - * Or - */ -DataSharePredicates *DataSharePredicates::Or() -{ - LOG_DEBUG("DataSharePredicates::Or Start"); - SetOperationList(OR, {}, {}, {}, ZERO_COUNT); - LOG_DEBUG("DataSharePredicates::Or End"); - return this; -} - -/** - * And - */ -DataSharePredicates *DataSharePredicates::And() -{ - LOG_DEBUG("DataSharePredicates::And Start"); - SetOperationList(AND, {}, {}, {}, ZERO_COUNT); - LOG_DEBUG("DataSharePredicates::And End"); - return this; -} - -/** - * Contains - */ -DataSharePredicates *DataSharePredicates::Contains(const std::string &field, const std::string &value) -{ - LOG_DEBUG("DataSharePredicates::Contains Start field%{public}s,value%{public}s", field.c_str(), value.c_str()); - SetOperationList(CONTAINS, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::Contains End"); - return this; -} - -/** - * BeginsWith - */ -DataSharePredicates *DataSharePredicates::BeginsWith(const std::string &field, const std::string &value) -{ - LOG_DEBUG("DataSharePredicates::BeginsWith Start field%{public}s,value%{public}s", field.c_str(), value.c_str()); - SetOperationList(BEGIN_WITH, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::BeginsWith End"); - return this; -} - -/** - * EndsWith - */ -DataSharePredicates *DataSharePredicates::EndsWith(const std::string &field, const std::string &value) -{ - LOG_DEBUG("DataSharePredicates::EndsWith Start field%{public}s,value%{public}s", field.c_str(), value.c_str()); - SetOperationList(END_WITH, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::EndsWith End"); - return this; -} - -/** - * IsNull - */ -DataSharePredicates *DataSharePredicates::IsNull(const std::string &field) -{ - LOG_DEBUG("DataSharePredicates::IsNull Start field%{public}s", field.c_str()); - SetOperationList(IS_NULL, field, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::IsNull End"); - return this; -} - -/** - * IsNotNull - */ -DataSharePredicates *DataSharePredicates::IsNotNull(const std::string &field) -{ - LOG_DEBUG("DataSharePredicates::IsNotNull Start field%{public}s", field.c_str()); - SetOperationList(IS_NOT_NULL, field, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::IsNotNull End"); - return this; -} - -/** - * Like - */ -DataSharePredicates *DataSharePredicates::Like(const std::string &field, const std::string &value) -{ - LOG_DEBUG("DataSharePredicates::Like Start field%{public}s value%{public}s", field.c_str(), value.c_str()); - SetOperationList(LIKE, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::Like End"); - return this; -} - -/** - * UnLike - */ -DataSharePredicates *DataSharePredicates::Unlike(const std::string &field, const std::string &value) -{ - LOG_DEBUG("DataSharePredicates::Unlike Start field%{public}s value%{public}s", field.c_str(), value.c_str()); - SetOperationList(UNLIKE, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::Unlike End"); - return this; -} - -/** - * Glob - */ -DataSharePredicates *DataSharePredicates::Glob(const std::string &field, const std::string &value) -{ - LOG_DEBUG("DataSharePredicates::Glob Start field%{public}s value%{public}s", field.c_str(), value.c_str()); - SetOperationList(GLOB, field, value, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::Glob End"); - return this; -} - -/** - * Between - */ -DataSharePredicates *DataSharePredicates::Between(const std::string &field, - const std::string &low, const std::string &high) -{ - LOG_DEBUG("DataSharePredicates::Between Start field%{public}s low%{public}s high%{public}s", - field.c_str(), low.c_str(), high.c_str()); - SetOperationList(BETWEEN, field, low, high, THREE_COUNT); - LOG_DEBUG("DataSharePredicates::Between End"); - return this; -} - -/** - * NotBetween - */ -DataSharePredicates *DataSharePredicates::NotBetween(const std::string &field, - const std::string &low, const std::string &high) -{ - LOG_DEBUG("DataSharePredicates::NotBetween Start field%{public}s low%{public}s high%{public}s", - field.c_str(), low.c_str(), high.c_str()); - SetOperationList(NOTBETWEEN, field, low, high, THREE_COUNT); - LOG_DEBUG("DataSharePredicates::NotBetween End"); - return this; -} - -/** - * OrderByAsc - */ -DataSharePredicates *DataSharePredicates::OrderByAsc(const std::string &field) -{ - LOG_DEBUG("DataSharePredicates::OrderByAsc Start field%{public}s", field.c_str()); - SetOperationList(ORDER_BY_ASC, field, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::OrderByAsc End"); - return this; -} - -/** - * OrderByDesc - */ -DataSharePredicates *DataSharePredicates::OrderByDesc(const std::string &field) -{ - LOG_DEBUG("DataSharePredicates::OrderByDesc Start field%{public}s", field.c_str()); - SetOperationList(ORDER_BY_DESC, field, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::OrderByDesc End"); - return this; -} - -/** - * Distinct - */ -DataSharePredicates *DataSharePredicates::Distinct() -{ - LOG_DEBUG("DataSharePredicates::Distinct Start"); - SetOperationList(DISTINCT, {}, {}, {}, ZERO_COUNT); - LOG_DEBUG("DataSharePredicates::Distinct End"); - return this; -} - -/** - * Limit - */ -DataSharePredicates *DataSharePredicates::Limit(const int number, const int offset) -{ - LOG_DEBUG("DataSharePredicates::Limit Start number : %{public}d, offset : %{public}d", number, offset); - SetOperationList(LIMIT, number, offset, {}, TWO_COUNT); - LOG_DEBUG("DataSharePredicates::Limit End"); - return this; -} - -/** - * GroupBy - */ -DataSharePredicates *DataSharePredicates::GroupBy(const std::vector &fields) -{ - LOG_DEBUG("DataSharePredicates::GroupBy Start fields%{public}s", fields.at(0).c_str()); - SetOperationList(GROUP_BY, fields, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::GroupBy End"); - return this; -} - -/** - * IndexedBy - */ -DataSharePredicates *DataSharePredicates::IndexedBy(const std::string &indexName) -{ - LOG_DEBUG("DataSharePredicates::IndexedBy Start indexName%{public}s", indexName.c_str()); - SetOperationList(INDEXED_BY, indexName, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::IndexedBy End"); - return this; -} - -/** - * KeyPrefix - */ -DataSharePredicates *DataSharePredicates::KeyPrefix(const std::string &prefix) -{ - LOG_DEBUG("DataSharePredicates::KeyPrefix Start prefix%{public}s", prefix.c_str()); - SetOperationList(KEY_PREFIX, prefix, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::KeyPrefix End"); - return this; -} - -/** - * InKeys - */ -DataSharePredicates *DataSharePredicates::InKeys(const std::vector &keys) -{ - LOG_DEBUG("DataSharePredicates::InKeys Start keys%{public}s", keys.at(0).c_str()); - SetOperationList(IN_KEY, keys, {}, {}, ONE_COUNT); - LOG_DEBUG("DataSharePredicates::InKeys End"); - return this; -} - -/** - * Obtains the table name. - */ -std::string DataSharePredicates::GetTableName() const -{ - return predicates_.tableName; -} - -/** - * GetOperationList - */ -const std::list& DataSharePredicates::GetOperationList() const -{ - return predicates_.operationList; -} - -/** - * Get WhereClause - */ -std::string DataSharePredicates::GetWhereClause() const -{ - return whereClause_; -} - -/** - * Set WhereClause - */ -int DataSharePredicates::SetWhereClause(const std::string &whereClause) -{ - if ((settingMode_ != PREDICATES_METHOD) && (!whereClause.empty())) { - this->whereClause_ = whereClause; - settingMode_ = QUERY_LANGUAGE; - return E_OK; - } - return E_ERROR; -} - -/** - * Get WhereArgs - */ -std::vector DataSharePredicates::GetWhereArgs() const -{ - return whereArgs_; -} - -/** - * Get WhereArgs - */ -int DataSharePredicates::SetWhereArgs(const std::vector &whereArgs) -{ - if ((settingMode_ != PREDICATES_METHOD) && (!whereArgs.empty())) { - if (!whereArgs.empty()) { - this->whereArgs_ = whereArgs; - settingMode_ = QUERY_LANGUAGE; - return E_OK; - } - } - return E_ERROR; -} - -/** - * Get Order - */ -std::string DataSharePredicates::GetOrder() const -{ - return order_; -} - -/** - * Set Order - */ -int DataSharePredicates::SetOrder(const std::string &order) -{ - LOG_DEBUG("DataSharePredicates::SetOrder Start order%{public}s", order.c_str()); - if ((settingMode_ != PREDICATES_METHOD) && (!order.empty())) { - this->order_ = order; - settingMode_ = QUERY_LANGUAGE; - return E_OK; - } - return E_ERROR; -} - -/** - * Clear Query Language - */ -void DataSharePredicates::ClearQueryLanguage() -{ - whereClause_ = ""; - whereArgs_ = {}; - order_ = ""; -} - -/** - * Set Setting Mode - */ -void DataSharePredicates::SetSettingMode(const SettingMode &settingMode) -{ - settingMode_ = settingMode; -} - -/** - * Get Setting Mode - */ -SettingMode DataSharePredicates::GetSettingMode() const -{ - return settingMode_; -} - -/** - * SetOperationList - */ -void DataSharePredicates::SetOperationList(OperationType operationType, const DataSharePredicatesObject ¶1, - const DataSharePredicatesObject ¶2, const DataSharePredicatesObject ¶3, ParameterCount parameterCount) -{ - LOG_DEBUG("DataSharePredicates::SetOperationList Start"); - OperationItem operationItem {}; - operationItem.operation = operationType; - operationItem.para1 = para1; - operationItem.para2 = para2; - operationItem.para3 = para3; - operationItem.parameterCount = parameterCount; - predicates_.operationList.push_back(operationItem); - if (settingMode_ != PREDICATES_METHOD) { - ClearQueryLanguage(); - settingMode_ = PREDICATES_METHOD; - } - LOG_DEBUG("DataSharePredicates::SetOperationList END settingMode_%{public}d", settingMode_); -} - -/** - * Write DataSharePredicates object to Parcel. - */ -bool DataSharePredicates::Marshalling(OHOS::Parcel &parcel) const -{ - LOG_DEBUG("DataSharePredicates::Marshalling Start"); - parcel.WriteInt32(predicates_.operationList.size()); - for (auto &it : predicates_.operationList) { - parcel.WriteInt64(static_cast(it.operation)); - parcel.WriteParcelable(&it.para1); - parcel.WriteParcelable(&it.para2); - parcel.WriteParcelable(&it.para3); - parcel.WriteInt64(static_cast(it.parameterCount)); - } - parcel.WriteString(whereClause_); - parcel.WriteStringVector(whereArgs_); - parcel.WriteString(order_); - parcel.WriteInt64(static_cast(settingMode_)); - LOG_DEBUG("DataSharePredicates::Marshalling End"); - return true; -} - -/** - * Read from Parcel object. - */ -DataSharePredicates* DataSharePredicates::Unmarshalling(OHOS::Parcel &parcel) -{ - LOG_DEBUG("DataSharePredicates::Unmarshalling Start"); - Predicates predicates {}; - OperationItem listitem {}; - std::string whereClause = ""; - std::vector whereArgs; - std::string order = ""; - int64_t settingMode = INVALID_MODE; - int listSize = parcel.ReadInt32(); - for (int i = 0; i < listSize; i++) { - listitem.operation = static_cast(parcel.ReadInt64()); - DataSharePredicatesObject *parameter1 = parcel.ReadParcelable(); - listitem.para1 = *parameter1; - DataSharePredicatesObject *parameter2 = parcel.ReadParcelable(); - listitem.para2 = *parameter2; - DataSharePredicatesObject *parameter3 = parcel.ReadParcelable(); - listitem.para3 = *parameter3; - listitem.parameterCount = static_cast(parcel.ReadInt64()); - predicates.operationList.push_back(listitem); - } - parcel.ReadString(whereClause); - parcel.ReadStringVector(&whereArgs); - parcel.ReadString(order); - parcel.ReadInt64(settingMode); - SettingMode settingmode = static_cast(settingMode); - auto predicatesObject = new DataSharePredicates(predicates); - predicatesObject->SetWhereClause(whereClause); - predicatesObject->SetWhereArgs(whereArgs); - predicatesObject->SetOrder(order); - predicatesObject->SetSettingMode(settingmode); - LOG_DEBUG("DataSharePredicates::Unmarshalling End"); - return predicatesObject; -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/datashare_predicates_object.cpp b/data_share/frameworks/native/common/src/datashare_predicates_object.cpp deleted file mode 100644 index d98d076c2..000000000 --- a/data_share/frameworks/native/common/src/datashare_predicates_object.cpp +++ /dev/null @@ -1,358 +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 "datashare_predicates_object.h" -#include "datashare_log.h" -#include "datashare_errno.h" - -namespace OHOS { -namespace DataShare { -DataSharePredicatesObject::DataSharePredicatesObject() : type(DataSharePredicatesObjectType::TYPE_NULL) -{ -} - -DataSharePredicatesObject::DataSharePredicatesObject(DataSharePredicatesObject &&DataSharePredicatesObject) noexcept -{ - if (this == &DataSharePredicatesObject) { - return; - } - type = DataSharePredicatesObject.type; - value = std::move(DataSharePredicatesObject.value); - DataSharePredicatesObject.type = DataSharePredicatesObjectType::TYPE_NULL; -} - -DataSharePredicatesObject::DataSharePredicatesObject(const DataSharePredicatesObject &DataSharePredicatesObject) -{ - if (this == &DataSharePredicatesObject) { - return; - } - type = DataSharePredicatesObject.type; - value = DataSharePredicatesObject.value; -} - -DataSharePredicatesObject::~DataSharePredicatesObject() -{ -} - -DataSharePredicatesObject::DataSharePredicatesObject(int val) : type(DataSharePredicatesObjectType::TYPE_INT) -{ - value = val; -} - -DataSharePredicatesObject::DataSharePredicatesObject(int64_t val) : type(DataSharePredicatesObjectType::TYPE_LONG) -{ - value = val; -} - -DataSharePredicatesObject::DataSharePredicatesObject(double val) : type(DataSharePredicatesObjectType::TYPE_DOUBLE) -{ - value = val; -} - -DataSharePredicatesObject::DataSharePredicatesObject(bool val) : type(DataSharePredicatesObjectType::TYPE_BOOL) -{ - value = val; -} - -DataSharePredicatesObject::DataSharePredicatesObject(const std::string &val) - : type(DataSharePredicatesObjectType::TYPE_STRING) -{ - value = val; -} - -DataSharePredicatesObject::DataSharePredicatesObject(const std::vector &val) - : type(DataSharePredicatesObjectType::TYPE_INT_VECTOR) -{ - std::vector int64val {}; - if (!val.empty()) { - for (const auto &it : val) { - int64val.push_back(static_cast(it)); - } - value = int64val; - } -} - -DataSharePredicatesObject::DataSharePredicatesObject(const std::vector &val) - : type(DataSharePredicatesObjectType::TYPE_LONG_VECTOR) -{ - std::vector parameter = val; - value = parameter; -} - -DataSharePredicatesObject::DataSharePredicatesObject(const std::vector &val) - : type(DataSharePredicatesObjectType::TYPE_STRING_VECTOR) -{ - std::vector parameter = val; - value = parameter; -} - -DataSharePredicatesObject::DataSharePredicatesObject(const std::vector &val) - : type(DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR) -{ - std::vector parameter = val; - value = parameter; -} - -DataSharePredicatesObject &DataSharePredicatesObject::operator=( - DataSharePredicatesObject &&DataSharePredicatesObject) noexcept -{ - if (this == &DataSharePredicatesObject) { - return *this; - } - type = DataSharePredicatesObject.type; - value = std::move(DataSharePredicatesObject.value); - DataSharePredicatesObject.type = DataSharePredicatesObjectType::TYPE_NULL; - return *this; -} - -DataSharePredicatesObject &DataSharePredicatesObject::operator=( - const DataSharePredicatesObject &DataSharePredicatesObject) -{ - if (this == &DataSharePredicatesObject) { - return *this; - } - type = DataSharePredicatesObject.type; - value = DataSharePredicatesObject.value; - return *this; -} - -DataSharePredicatesObjectType DataSharePredicatesObject::GetType() const -{ - return type; -} - -int DataSharePredicatesObject::GetInt(int &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_INT) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataSharePredicatesObject::GetLong(int64_t &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_INT) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataSharePredicatesObject::GetDouble(double &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_DOUBLE) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataSharePredicatesObject::GetBool(bool &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_BOOL) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataSharePredicatesObject::GetString(std::string &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_STRING) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataSharePredicatesObject::GetIntVector(std::vector &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_INT_VECTOR) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get>(value); - return E_OK; -} - -int DataSharePredicatesObject::GetLongVector(std::vector &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_LONG_VECTOR) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get>(value); - return E_OK; -} - -int DataSharePredicatesObject::GetDoubleVector(std::vector &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get>(value); - return E_OK; -} - -int DataSharePredicatesObject::GetStringVector(std::vector &val) const -{ - if (type != DataSharePredicatesObjectType::TYPE_STRING_VECTOR) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get>(value); - return E_OK; -} - -bool DataSharePredicatesObject::Marshalling(Parcel &parcel) const -{ - LOG_DEBUG("DataSharePredicatesObject::Marshalling Start"); - parcel.WriteInt16((int16_t)this->type); - switch (this->type) { - case DataSharePredicatesObjectType::TYPE_NULL: { - break; - } - case DataSharePredicatesObjectType::TYPE_INT: { - parcel.WriteInt32(std::get(value)); - break; - } - case DataSharePredicatesObjectType::TYPE_LONG: { - parcel.WriteInt64(std::get(value)); - break; - } - case DataSharePredicatesObjectType::TYPE_DOUBLE: { - parcel.WriteDouble(std::get(value)); - break; - } - case DataSharePredicatesObjectType::TYPE_STRING: { - parcel.WriteString(std::get(value)); - break; - } - case DataSharePredicatesObjectType::TYPE_BOOL: { - parcel.WriteBool(std::get(value)); - break; - } - default: - break; - } - MarshallingVector(parcel); - LOG_DEBUG("DataSharePredicatesObject::Marshalling End"); - return true; -} - -DataSharePredicatesObject *DataSharePredicatesObject::Unmarshalling(Parcel &parcel) -{ - LOG_DEBUG("DataSharePredicatesObject::Unmarshalling Start"); - auto *pValueObject = new DataSharePredicatesObject(); - if (pValueObject != nullptr) { - pValueObject->type = (DataSharePredicatesObjectType)parcel.ReadInt16(); - switch (pValueObject->type) { - case DataSharePredicatesObjectType::TYPE_NULL: { - break; - } - case DataSharePredicatesObjectType::TYPE_INT: { - pValueObject->value = parcel.ReadInt32(); - break; - } - case DataSharePredicatesObjectType::TYPE_LONG: { - pValueObject->value = parcel.ReadInt64(); - break; - } - case DataSharePredicatesObjectType::TYPE_DOUBLE: { - pValueObject->value = parcel.ReadDouble(); - break; - } - case DataSharePredicatesObjectType::TYPE_STRING: { - pValueObject->value = parcel.ReadString(); - break; - } - case DataSharePredicatesObjectType::TYPE_BOOL: { - pValueObject->value = parcel.ReadBool(); - break; - } - default: - break; - } - UnmarshallingVector(pValueObject->type, pValueObject, parcel); - } - LOG_DEBUG("DataSharePredicatesObject::Unmarshalling End"); - return pValueObject; -} - -void DataSharePredicatesObject::UnmarshallingVector(DataSharePredicatesObjectType type, - DataSharePredicatesObject *pValueObject, Parcel &parcel) -{ - switch (type) { - case DataSharePredicatesObjectType::TYPE_INT_VECTOR: { - std::vector intval {}; - parcel.ReadInt32Vector(&intval); - pValueObject->value = intval; - break; - } - case DataSharePredicatesObjectType::TYPE_LONG_VECTOR: { - std::vector int64val {}; - parcel.ReadInt64Vector(&int64val); - pValueObject->value = int64val; - break; - } - case DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR: { - std::vector doubleval {}; - parcel.ReadDoubleVector(&doubleval); - pValueObject->value = doubleval; - break; - } - case DataSharePredicatesObjectType::TYPE_STRING_VECTOR: { - std::vector stringval {}; - parcel.ReadStringVector(&stringval); - pValueObject->value = stringval; - break; - } - default: - break; - } -} - -void DataSharePredicatesObject::MarshallingVector(Parcel &parcel) const -{ - switch (this->type) { - case DataSharePredicatesObjectType::TYPE_INT_VECTOR: { - parcel.WriteInt32Vector(std::get>(value)); - break; - } - case DataSharePredicatesObjectType::TYPE_LONG_VECTOR: { - parcel.WriteInt64Vector(std::get>(value)); - break; - } - case DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR: { - parcel.WriteDoubleVector(std::get>(value)); - break; - } - case DataSharePredicatesObjectType::TYPE_STRING_VECTOR: { - parcel.WriteStringVector(std::get>(value)); - break; - } - default: - break; - } -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/datashare_result.cpp b/data_share/frameworks/native/common/src/datashare_result.cpp deleted file mode 100644 index 1346a6b03..000000000 --- a/data_share/frameworks/native/common/src/datashare_result.cpp +++ /dev/null @@ -1,180 +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 "datashare_result.h" - -#include "datashare_log.h" -#include "parcel_macro.h" - -namespace OHOS { -namespace DataShare { -using namespace AppExecFwk; -/** - * @brief A constructor used to create a DataShareResult instance - * with the input parameter count specified. - */ -DataShareResult::DataShareResult(int count) : uri_("") -{ - count_ = count; -} - -/** - * @brief A constructor used to create a DataShareResult instance - * with a Parcel object specified. - */ -DataShareResult::DataShareResult(Parcel &parcel) : uri_(""), count_(0) -{ - ReadFromParcel(parcel); -} - -/** - * @brief A constructor used to create a DataShareResult instance - * with the input parameter uri specified - */ -DataShareResult::DataShareResult(const Uri &uri) : uri_(uri.ToString()), count_(0) -{} - -/** - * @brief A constructor used to create a DataShareResult instance - * with input parameters uri, count, and failure specified. - */ -DataShareResult::DataShareResult(const Uri &uri, int count) : uri_(uri.ToString()) -{ - count_ = count; -} - -DataShareResult::~DataShareResult() -{} - -/** - * @brief Obtains the Uri object corresponding to the operation. - * @return Obtains the Uri object corresponding to the operation. - */ -Uri DataShareResult::GetUri() -{ - return uri_; -} - -/** - * @brief Obtains the number of rows affected by the operation. - * @return Returns the number of rows affected by the operation. - */ -int DataShareResult::GetCount() -{ - return count_; -} - -/** - * @brief Creates a DataShareResult instance based on the given Parcel object. - * Used to transfer DataShareResult object using Parcel. - * @param parcel Indicates the Parcel object. - * @return Returns the DataShareResult object. - */ -DataShareResult *DataShareResult::CreateFromParcel(Parcel &parcel) -{ - DataShareResult *dataShareResult = new (std::nothrow) DataShareResult(parcel); - if (dataShareResult == nullptr) { - LOG_ERROR("DataShareResult::CreateFromParcel dataShareResult is nullptr"); - } - return dataShareResult; -} - -/** - * @brief Prints out a string containing the class object information. - * @return Returns object information. - */ -std::string DataShareResult::ToString() -{ - std::string stringBuilder = "DataShareResult("; - stringBuilder.append("uri=").append(uri_.ToString()).append(" "); - stringBuilder.append("count=").append(std::to_string(count_)).append(" "); - stringBuilder.erase(stringBuilder.length() - 1, 1); - stringBuilder.append(")"); - return stringBuilder; -} - -/** - * @brief Marshals a DataShareResult object into a Parcel. - * @param parcel Indicates the Parcel object for marshalling. - * @return Returns true if the marshalling is successful; returns false otherwise. - */ -bool DataShareResult::Marshalling(Parcel &parcel) const -{ - // uri_ - if (uri_.ToString().empty()) { - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, VALUE_NULL); - } else { - if (!parcel.WriteInt32(VALUE_OBJECT)) { - return false; - } - if (!parcel.WriteParcelable(&uri_)) { - return false; - } - } - - // count_ - if (!parcel.WriteInt32(count_)) { - return false; - } - - return true; -} - -/** - * @brief Unmarshals a DataShareResult object from a Parcel. - * @param parcel Indicates the Parcel object for unmarshalling. - * @return Returns true if the unmarshalling is successful; returns false otherwise. - */ -DataShareResult *DataShareResult::Unmarshalling(Parcel &parcel) -{ - DataShareResult *dataShareResult = new (std::nothrow) DataShareResult(0); - if (dataShareResult != nullptr) { - if (!dataShareResult->ReadFromParcel(parcel)) { - delete dataShareResult; - dataShareResult = nullptr; - } - } - - return dataShareResult; -} - -bool DataShareResult::ReadFromParcel(Parcel &parcel) -{ - // uri_ - int32_t empty = VALUE_NULL; - if (!parcel.ReadInt32(empty)) { - return false; - } - - if (empty == VALUE_OBJECT) { - auto uri = parcel.ReadParcelable(); - if (uri != nullptr) { - uri_ = *uri; - delete uri; - uri = nullptr; - } else { - return false; - } - } - - // count_ - if (!parcel.ReadInt32(count_)) { - return false; - } - - return true; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/datashare_result_set.cpp b/data_share/frameworks/native/common/src/datashare_result_set.cpp deleted file mode 100644 index b0fd23787..000000000 --- a/data_share/frameworks/native/common/src/datashare_result_set.cpp +++ /dev/null @@ -1,426 +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 "datashare_result_set.h" - -#include -#include -#include "datashare_log.h" -#include "parcel.h" -#include "datashare_errno.h" -#include "shared_block.h" -#include "string_ex.h" - -namespace OHOS { -namespace DataShare { -namespace { - // The default position of the cursor - static const int INITIAL_POS = -1; - static const size_t DEFAULT_SHARE_BLOCK_SIZE = 2 * 1024 * 1024; - // Equivalent to filling in setp + 1 rows each time - static const int STEP_LEN = 2; -} // namespace -int DataShareResultSet::blockId_ = 0; -DataShareResultSet::DataShareResultSet() -{ -} - -DataShareResultSet::DataShareResultSet(std::shared_ptr &bridge) - : bridge_(bridge) -{ - std::string name = "DataShare" + std::to_string(blockId_++); - blockWriter_ = std::make_shared(name, DEFAULT_SHARE_BLOCK_SIZE); - sharedBlock_ = blockWriter_->GetBlock(); -} - -DataShareResultSet::~DataShareResultSet() -{ - ClosedBlock(); -} - -int DataShareResultSet::GetAllColumnNames(std::vector &columnNames) -{ - if (bridge_ == nullptr) { - LOG_ERROR("bridge_ is null!"); - return E_ERROR; - } - return bridge_->GetAllColumnNames(columnNames); -} - -int DataShareResultSet::GetRowCount(int &count) -{ - if (bridge_ == nullptr) { - LOG_ERROR("bridge_ is null!"); - return E_ERROR; - } - return bridge_->GetRowCount(count); -} - -bool DataShareResultSet::OnGo(int startRowIndex, int targetRowIndex) -{ - if (bridge_ == nullptr || blockWriter_ == nullptr) { - LOG_ERROR("bridge_ or blockWriter_ is null!"); - return E_ERROR; - } - return bridge_->OnGo(startRowIndex, targetRowIndex, *blockWriter_); -} - -void DataShareResultSet::FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) -{ - return; -} - -/** - * Get current shared block - */ -AppDataFwk::SharedBlock *DataShareResultSet::GetBlock() const -{ - return sharedBlock_; -} - -int DataShareResultSet::GetDataType(int columnIndex, DataType &dataType) -{ - AppDataFwk::SharedBlock::CellUnit *cellUnit = - sharedBlock_->GetCellUnit((uint32_t)rowPos_ - startRowPos_, (uint32_t)columnIndex); - if (!cellUnit) { - LOG_ERROR("DataShareResultSet::GetDataType cellUnit is null!"); - return E_ERROR; - } - dataType = (DataType)cellUnit->type; - return E_OK; -} - -int DataShareResultSet::GoToRow(int position) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("sharedBlock_ is null!"); - return E_ERROR; - } - int rowCnt = 0; - GetRowCount(rowCnt); - if (position >= rowCnt) { - rowPos_ = rowCnt; - return E_ERROR; - } - if (position < 0) { - rowPos_ = INITIAL_POS; - return E_ERROR; - } - if (position == rowPos_) { - return E_OK; - } - bool result = true; - if (position > endRowPos_ || position < startRowPos_) { - result = OnGo(position, std::min(position + STEP_LEN, rowCnt - 1)); - if (result) { - startRowPos_ = position; - endRowPos_ = position + static_cast(sharedBlock_->GetRowNum()) -1; - } - } - - if (!result) { - rowPos_ = INITIAL_POS; - startRowPos_ = INITIAL_POS; - endRowPos_ = INITIAL_POS; - return E_ERROR; - } else { - rowPos_ = position; - return E_OK; - } -} - -int DataShareResultSet::GetBlob(int columnIndex, std::vector &value) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("DataShareResultSet::GetBlob cellUnit is null!"); - return E_ERROR; - } - - value.resize(0); - int type = cellUnit->type; - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB - || type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t size; - const auto *blob = static_cast(sharedBlock_->GetCellUnitValueBlob(cellUnit, &size)); - if (size == 0 || blob == nullptr) { - LOG_WARN("blob data is empty!"); - } else { - value.resize(size); - value.assign(blob, blob + size); - } - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER!"); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT!"); - return E_OK; - } else { - LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::nothing !"); - return E_INVALID_OBJECT_TYPE; - } -} - -int DataShareResultSet::GetString(int columnIndex, std::string &value) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("DataShareResultSet::GetString cellUnit is null!"); - return E_ERROR; - } - int type = cellUnit->type; - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t sizeIncludingNull; - const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull); - if ((sizeIncludingNull <= 1) || (tempValue == nullptr)) { - value = ""; - return E_ERROR; - } - value = tempValue; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - int64_t tempValue = cellUnit->cell.longValue; - value = std::to_string(tempValue); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - double tempValue = cellUnit->cell.doubleValue; - std::ostringstream os; - if (os << tempValue) - value = os.str(); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - LOG_ERROR("DataShareResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); - return E_ERROR; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - LOG_ERROR("DataShareResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!"); - return E_ERROR; - } else { - LOG_ERROR("DataShareResultSet::GetString is failed!"); - return E_ERROR; - } -} - -int DataShareResultSet::GetInt(int columnIndex, int &value) -{ - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("DataShareResultSet::GetInt cellUnit is null!"); - return E_ERROR; - } - value = (int)cellUnit->cell.longValue; - return E_OK; -} - -int DataShareResultSet::GetLong(int columnIndex, int64_t &value) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("DataShareResultSet::GetLong cellUnit is null!"); - return E_ERROR; - } - - int type = cellUnit->type; - - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - value = cellUnit->cell.longValue; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t sizeIncludingNull; - const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull); - value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? long(strtoll(tempValue, nullptr, 0)) : 0L; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - value = (int64_t)cellUnit->cell.doubleValue; - LOG_ERROR("DataShareResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT !"); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - LOG_ERROR("DataShareResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL !"); - value = 0L; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - LOG_ERROR("DataShareResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB !"); - value = 0L; - return E_OK; - } else { - LOG_ERROR("DataShareResultSet::GetLong Nothing !"); - return E_INVALID_OBJECT_TYPE; - } -} - -int DataShareResultSet::GetDouble(int columnIndex, double &value) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("DataShareResultSet::GetDouble cellUnit is null!"); - return E_ERROR; - } - int type = cellUnit->type; - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - value = cellUnit->cell.doubleValue; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t sizeIncludingNull; - const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull); - value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? strtod(tempValue, nullptr) : 0.0; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - value = cellUnit->cell.longValue; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); - value = 0.0; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!"); - value = 0.0; - return E_OK; - } else { - LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::nothing !"); - value = 0.0; - return E_INVALID_OBJECT_TYPE; - } -} - -int DataShareResultSet::IsColumnNull(int columnIndex, bool &isNull) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("DataShareResultSet::IsColumnNull cellUnit is null!"); - return E_ERROR; - } - if (cellUnit->type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - isNull = true; - return E_OK; - } - isNull = false; - return E_OK; -} - -int DataShareResultSet::Close() -{ - DataShareAbsResultSet::Close(); - ClosedBlock(); - return E_OK; -} - -/** - * Allocates a new shared block to an {@link DataShareResultSet} - */ -void DataShareResultSet::SetBlock(AppDataFwk::SharedBlock *block) -{ - if (sharedBlock_ != block) { - ClosedBlock(); - sharedBlock_ = block; - } -} - -/** - * Checks whether an {@code DataShareResultSet} object contains shared blocks - */ -bool DataShareResultSet::HasBlock() const -{ - return sharedBlock_ != nullptr; -} - -/** - * Closes a shared block that is not empty in this {@code DataShareResultSet} object - */ -void DataShareResultSet::ClosedBlock() -{ - delete sharedBlock_; - sharedBlock_ = nullptr; -} - -void DataShareResultSet::ClearBlock() -{ - if (sharedBlock_ != nullptr) { - sharedBlock_->Clear(); - } -} - -void DataShareResultSet::Finalize() -{ - Close(); -} - -/** - * Check current status - */ -int DataShareResultSet::CheckState(int columnIndex) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("DataShareResultSet::CheckState sharedBlock is null!"); - return E_ERROR; - } - int cnt = 0; - GetColumnCount(cnt); - if (columnIndex >= cnt || columnIndex < 0) { - return E_INVALID_COLUMN_INDEX; - } - int rowCnt = 0; - GetRowCount(rowCnt); - if (rowPos_ < 0 || rowPos_ >= rowCnt) { - return E_INVALID_STATEMENT; - } - return E_OK; -} - -bool DataShareResultSet::Marshalling(MessageParcel &parcel) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("DataShareResultSet::Marshalling sharedBlock is null."); - return false; - } - LOG_DEBUG("DataShareResultSet::Marshalling sharedBlock."); - return sharedBlock_->WriteMessageParcel(parcel); -} - -bool DataShareResultSet::Unmarshalling(MessageParcel &parcel) -{ - if (sharedBlock_ != nullptr) { - return false; - } - int result = AppDataFwk::SharedBlock::ReadMessageParcel(parcel, sharedBlock_); - if (result < 0) { - LOG_ERROR("DataShareResultSet: create from parcel error is %{public}d.", result); - } - return true; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/datashare_string_utils.cpp b/data_share/frameworks/native/common/src/datashare_string_utils.cpp deleted file mode 100644 index 1db79753e..000000000 --- a/data_share/frameworks/native/common/src/datashare_string_utils.cpp +++ /dev/null @@ -1,51 +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 "datashare_string_utils.h" - -namespace OHOS { -namespace DataShare { -std::string DataShareStringUtils::SurroundWithQuote(std::string value, std::string quote) -{ - if (value.empty()) { - return value; - } - std::string str = quote + value + quote; - return str; -} - -// Join array members as parameters of a function call. -std::string DataShareStringUtils::SurroundWithFunction(std::string function, std::string separator, - std::vector array) -{ - std::string builder(function); - builder += "("; - bool isFirst = true; - for (auto text : array) { - if (!isFirst) { - builder = builder + " " + separator + " "; - } else { - isFirst = false; - } - builder += text; - } - builder += ")"; - return builder; -} - -DataShareStringUtils::DataShareStringUtils() {} -DataShareStringUtils::~DataShareStringUtils() {} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/datashare_value_object.cpp b/data_share/frameworks/native/common/src/datashare_value_object.cpp deleted file mode 100644 index ef44308a0..000000000 --- a/data_share/frameworks/native/common/src/datashare_value_object.cpp +++ /dev/null @@ -1,167 +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 "datashare_value_object.h" - -#include "datashare_errno.h" - -namespace OHOS { -namespace DataShare { -DataShareValueObjectType DataShareValueObject::GetType() const -{ - return type; -} - -int DataShareValueObject::GetInt(int &val) const -{ - if (type != DataShareValueObjectType::TYPE_INT) { - return E_INVALID_OBJECT_TYPE; - } - - int64_t v = std::get(value); - val = static_cast(v); - return E_OK; -} - -int DataShareValueObject::GetLong(int64_t &val) const -{ - if (type != DataShareValueObjectType::TYPE_INT) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataShareValueObject::GetDouble(double &val) const -{ - if (type != DataShareValueObjectType::TYPE_DOUBLE) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataShareValueObject::GetBool(bool &val) const -{ - if (type != DataShareValueObjectType::TYPE_BOOL) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataShareValueObject::GetString(std::string &val) const -{ - if (type != DataShareValueObjectType::TYPE_STRING) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get(value); - return E_OK; -} - -int DataShareValueObject::GetBlob(std::vector &val) const -{ - if (type != DataShareValueObjectType::TYPE_BLOB) { - return E_INVALID_OBJECT_TYPE; - } - - val = std::get>(value); - return E_OK; -} - -bool DataShareValueObject::Marshalling(const DataShareValueObject &valueObject, Parcel &parcel) -{ - switch (valueObject.type) { - case DataShareValueObjectType::TYPE_NULL: { - parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_NULL); - break; - } - case DataShareValueObjectType::TYPE_INT: { - parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_INT); - parcel.WriteInt64(std::get(valueObject.value)); - break; - } - case DataShareValueObjectType::TYPE_DOUBLE: { - parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_DOUBLE); - parcel.WriteDouble(std::get(valueObject.value)); - break; - } - case DataShareValueObjectType::TYPE_STRING: { - parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_STRING); - parcel.WriteString(std::get(valueObject.value)); - break; - } - case DataShareValueObjectType::TYPE_BLOB: { - parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_BLOB); - parcel.WriteUInt8Vector(std::get>(valueObject.value)); - break; - } - case DataShareValueObjectType::TYPE_BOOL: { - parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_BOOL); - parcel.WriteBool(std::get(valueObject.value)); - break; - } - default: - break; - } - return true; -} - -DataShareValueObject *DataShareValueObject::Unmarshalling(Parcel &parcel) -{ - auto *pValueObject = new DataShareValueObject(); - switch (parcel.ReadInt16()) { - case (int16_t)DataShareValueObjectType::TYPE_NULL: { - pValueObject->type = DataShareValueObjectType::TYPE_NULL; - break; - } - case (int16_t)DataShareValueObjectType::TYPE_INT: { - pValueObject->type = DataShareValueObjectType::TYPE_INT; - pValueObject->value = parcel.ReadInt64(); - break; - } - case (int16_t)DataShareValueObjectType::TYPE_DOUBLE: { - pValueObject->type = DataShareValueObjectType::TYPE_DOUBLE; - pValueObject->value = parcel.ReadDouble(); - break; - } - case (int16_t)DataShareValueObjectType::TYPE_STRING: { - pValueObject->type = DataShareValueObjectType::TYPE_STRING; - pValueObject->value = parcel.ReadString(); - break; - } - case (int16_t)DataShareValueObjectType::TYPE_BLOB: { - pValueObject->type = DataShareValueObjectType::TYPE_BLOB; - std::vector val; - parcel.ReadUInt8Vector(&val); - pValueObject->value = val; - break; - } - case (int16_t)DataShareValueObjectType::TYPE_BOOL: { - pValueObject->type = DataShareValueObjectType::TYPE_BOOL; - pValueObject->value = parcel.ReadBool(); - break; - } - default: - break; - } - return pValueObject; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/datashare_values_bucket.cpp b/data_share/frameworks/native/common/src/datashare_values_bucket.cpp deleted file mode 100644 index 8e1ad6c39..000000000 --- a/data_share/frameworks/native/common/src/datashare_values_bucket.cpp +++ /dev/null @@ -1,123 +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 "datashare_values_bucket.h" -#include "datashare_value_object.h" - -namespace OHOS { -namespace DataShare { -void DataShareValuesBucket::PutString(const std::string &columnName, const std::string &value) -{ - valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value))); -} - -void DataShareValuesBucket::PutInt(const std::string &columnName, int value) -{ - valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value))); -} - -void DataShareValuesBucket::PutLong(const std::string &columnName, int64_t value) -{ - valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value))); -} - -void DataShareValuesBucket::PutDouble(const std::string &columnName, double value) -{ - valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value))); -} - -void DataShareValuesBucket::PutBool(const std::string &columnName, bool value) -{ - valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value))); -} - -void DataShareValuesBucket::PutBlob(const std::string &columnName, const std::vector &value) -{ - valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value))); -} - -void DataShareValuesBucket::PutNull(const std::string &columnName) -{ - valuesMap.insert(std::make_pair(columnName, DataShareValueObject())); -} - -void DataShareValuesBucket::Delete(const std::string &columnName) -{ - valuesMap.erase(columnName); -} - -void DataShareValuesBucket::Clear() -{ - valuesMap.clear(); -} - -int DataShareValuesBucket::Size() const -{ - return valuesMap.size(); -} - -bool DataShareValuesBucket::IsEmpty() const -{ - return valuesMap.empty(); -} - -bool DataShareValuesBucket::HasColumn(const std::string &columnName) const -{ - auto iter = valuesMap.find(columnName); - if (iter == valuesMap.end()) { - return false; - } - return true; -} - -bool DataShareValuesBucket::GetObject(const std::string &columnName, DataShareValueObject &value) const -{ - auto iter = valuesMap.find(columnName); - if (iter == valuesMap.end()) { - return false; - } - value = iter->second; - return true; -} - -void DataShareValuesBucket::GetAll(std::map &outValuesMap) const -{ - outValuesMap = valuesMap; -} - -bool DataShareValuesBucket::Marshalling(const DataShareValuesBucket &valuesBucket, Parcel &parcel) -{ - parcel.WriteInt32(valuesBucket.valuesMap.size()); - for (auto &it : valuesBucket.valuesMap) { - parcel.WriteString(it.first); - DataShareValueObject::Marshalling(it.second, parcel); - } - return true; -} - -DataShareValuesBucket *DataShareValuesBucket::Unmarshalling(Parcel &parcel) -{ - int mapSize = parcel.ReadInt32(); - std::map valuesMap; - for (int i = 0; i < mapSize; i++) { - std::string key = parcel.ReadString(); - DataShareValueObject *value = DataShareValueObject::Unmarshalling(parcel); - valuesMap.insert(std::make_pair(key, *value)); - delete value; - } - return new DataShareValuesBucket(valuesMap); -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/ishared_result_set.cpp b/data_share/frameworks/native/common/src/ishared_result_set.cpp deleted file mode 100644 index d394957be..000000000 --- a/data_share/frameworks/native/common/src/ishared_result_set.cpp +++ /dev/null @@ -1,29 +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 "ishared_result_set.h" - -namespace OHOS::DataShare { -std::shared_ptr ISharedResultSet::ReadFromParcel(MessageParcel &parcel) -{ - return consumerCreator_(parcel); -} - -sptr ISharedResultSet::WriteToParcel(std::shared_ptr resultSet, - MessageParcel &parcel) -{ - return providerCreator_(std::move(resultSet), parcel); -} -} // namespace OHOS::DataShare \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/ishared_result_set_proxy.cpp b/data_share/frameworks/native/common/src/ishared_result_set_proxy.cpp deleted file mode 100644 index 567b0aa99..000000000 --- a/data_share/frameworks/native/common/src/ishared_result_set_proxy.cpp +++ /dev/null @@ -1,128 +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 "ishared_result_set_proxy.h" -#include "datashare_errno.h" -#include "iremote_proxy.h" -#include "datashare_log.h" -namespace OHOS::DataShare { -std::function( - MessageParcel &parcel)> ISharedResultSet::consumerCreator_ = ISharedResultSetProxy::CreateProxy; -BrokerDelegator ISharedResultSetProxy::delegator_; -ISharedResultSetProxy::ISharedResultSetProxy(const sptr &impl) - : IRemoteProxy(impl) -{ -} - -std::shared_ptr ISharedResultSetProxy::CreateProxy(MessageParcel &parcel) -{ - sptr remoter = parcel.ReadRemoteObject(); - if (remoter == nullptr) { - return nullptr; - } - sptr result = iface_cast(remoter); - result->Unmarshalling(parcel); - return std::shared_ptr(result.GetRefPtr(), - [keep = result] (DataShareResultSet *) {}); -} - -int ISharedResultSetProxy::GetAllColumnNames(std::vector &columnNames) -{ - LOG_DEBUG("GetAllColumnNames Begin"); - if (!columnNames_.empty()) { - columnNames = columnNames_; - return E_OK; - } - MessageParcel request; - request.WriteInterfaceToken(GetDescriptor()); - MessageParcel reply; - MessageOption msgOption; - int errCode = Remote()->SendRequest(FUNC_GET_ALL_COLUMN_NAMES, request, reply, msgOption); - if (errCode != 0) { - LOG_ERROR("GetAllColumnNames IPC Error %{public}x", errCode); - return -errCode; - } - errCode = reply.ReadInt32(); - if (errCode != E_OK) { - LOG_ERROR("GetAllColumnNames Reply Error %{public}d", errCode); - return errCode; - } - if (!reply.ReadStringVector(&columnNames)) { - return E_INVALID_PARCEL; - } - columnNames_ = columnNames; - return E_OK; -} - -int ISharedResultSetProxy::GetRowCount(int &count) -{ - LOG_DEBUG("GetRowCount Begin"); - if (rowCount_ >= 0) { - count = rowCount_; - return E_OK; - } - MessageParcel request; - request.WriteInterfaceToken(GetDescriptor()); - MessageParcel reply; - MessageOption msgOption; - int errCode = Remote()->SendRequest(FUNC_GET_ROW_COUNT, request, reply, msgOption); - if (errCode != 0) { - LOG_ERROR("GetRowCount IPC Error %{public}x", errCode); - return -errCode; - } - errCode = reply.ReadInt32(); - if (errCode != E_OK) { - LOG_ERROR("GetRowCount Reply Error %{public}d", errCode); - return errCode; - } - count = reply.ReadInt32(); - LOG_DEBUG("GetRowCount count %{public}d", count); - rowCount_ = count; - return E_OK; -} - -bool ISharedResultSetProxy::OnGo(int oldRowIndex, int newRowIndex) -{ - LOG_DEBUG("OnGo Begin"); - MessageParcel request; - request.WriteInterfaceToken(GetDescriptor()); - request.WriteInt32(oldRowIndex); - request.WriteInt32(newRowIndex); - MessageParcel reply; - MessageOption msgOption; - int errCode = Remote()->SendRequest(FUNC_ON_GO, request, reply, msgOption); - if (errCode != 0) { - LOG_ERROR("OnGo IPC Error %{public}x", errCode); - return -errCode; - } - return reply.ReadBool(); -} - -int ISharedResultSetProxy::Close() -{ - LOG_DEBUG("Close Begin"); - DataShareResultSet::Close(); - MessageParcel request; - request.WriteInterfaceToken(GetDescriptor()); - MessageParcel reply; - MessageOption msgOption; - int errCode = Remote()->SendRequest(FUNC_CLOSE, request, reply, msgOption); - if (errCode != 0) { - LOG_ERROR("Close IPC Error %{public}x", errCode); - return -errCode; - } - return reply.ReadInt32(); -} -} // namespace OHOS::DataShare \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/ishared_result_set_stub.cpp b/data_share/frameworks/native/common/src/ishared_result_set_stub.cpp deleted file mode 100644 index 02df23544..000000000 --- a/data_share/frameworks/native/common/src/ishared_result_set_stub.cpp +++ /dev/null @@ -1,142 +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 "ishared_result_set_stub.h" -#include -#include "datashare_log.h" -#include "datashare_errno.h" - -namespace OHOS::DataShare { -std::function(std::shared_ptr, - MessageParcel &)> ISharedResultSet::providerCreator_ = ISharedResultSetStub::CreateStub; -constexpr ISharedResultSetStub::Handler ISharedResultSetStub::handlers[ISharedResultSet::FUNC_BUTT]; - -sptr ISharedResultSetStub::CreateStub(std::shared_ptr result, - OHOS::MessageParcel &parcel) -{ - sptr stub = new ISharedResultSetStub(result); - parcel.WriteRemoteObject(stub->AsObject().GetRefPtr()); - result->Marshalling(parcel); - return stub; -} - -ISharedResultSetStub::ISharedResultSetStub(std::shared_ptr resultSet) - : resultSet_(std::move(resultSet)), - runnables_(MAX_RUNNABLE), - thread_(&ISharedResultSetStub::Run, this) -{ - thread_.detach(); - LOG_ERROR("ISharedResultSetStub start thread(%{public}" PRIx64 ")", uint64_t(thread_.native_handle())); -} -ISharedResultSetStub::~ISharedResultSetStub() -{ - auto handle = thread_.native_handle(); - isRunning_ = false; - // do not delete this code, this code is waiting the thread exit. - isRunning_ = Submit([this]() -> bool { return isRunning_;}).get(); - LOG_ERROR("~ISharedResultSetStub thread(%{public}" PRIx64 ")", uint64_t(handle)); -} - -int ISharedResultSetStub::OnRemoteRequest(uint32_t code, OHOS::MessageParcel &data, - OHOS::MessageParcel &reply, OHOS::MessageOption &option) -{ - if (GetDescriptor() != data.ReadInterfaceToken()) { - LOG_ERROR("IPC descriptor is not equal"); - return INVALID_FD; - } - - if (code >= FUNC_BUTT) { - LOG_ERROR("OnRemoteRequest method code(%{public}d) out of range", code); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - Handler handler = handlers[code]; - if (handler == nullptr) { - LOG_ERROR("OnRemoteRequest method code(%{public}d) is not support", code); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - - auto future = Submit([this, &data, &reply, handler]() -> int { - return (this->*handler)(data, reply); - }); - return future.get(); -} - -int ISharedResultSetStub::HandleGetRowCountRequest(MessageParcel &data, MessageParcel &reply) -{ - int count = -1; - int errCode = resultSet_->GetRowCount(count); - reply.WriteInt32(errCode); - if (errCode == E_OK) { - reply.WriteInt32(count); - } - LOG_DEBUG("HandleGetRowCountRequest call %{public}d", errCode); - return NO_ERROR; -} - -int ISharedResultSetStub::HandleGetAllColumnNamesRequest(MessageParcel &data, MessageParcel &reply) -{ - std::vector names; - int errCode = resultSet_->GetAllColumnNames(names); - reply.WriteInt32(errCode); - if (errCode == E_OK) { - reply.WriteStringVector(names); - } - LOG_DEBUG("HandleGetAllColumnNamesRequest call %{public}d", errCode); - return NO_ERROR; -} - -int ISharedResultSetStub::HandleOnGoRequest(MessageParcel &data, MessageParcel &reply) -{ - int oldRow = data.ReadInt32(); - int newRow = data.ReadInt32(); - std::vector columnNames; - resultSet_->GetAllColumnNames(columnNames); - auto block = resultSet_->GetBlock(); - int errCode = block->Clear(); - if (errCode != E_OK) { - reply.WriteInt32(errCode); - return NO_ERROR; - } - errCode = block->SetColumnNum(columnNames.size()); - if (errCode == E_OK) { - errCode = resultSet_->OnGo(oldRow, newRow); - } - reply.WriteInt32(errCode); - LOG_DEBUG("HandleOnGoRequest call %{public}d", errCode); - return NO_ERROR; -} - -int ISharedResultSetStub::HandleCloseRequest(MessageParcel &data, MessageParcel &reply) -{ - int errCode = resultSet_->Close(); - reply.WriteInt32(errCode); - LOG_DEBUG("HandleCloseRequest call %{public}d", errCode); - return NO_ERROR; -} - -void ISharedResultSetStub::Run() -{ - auto handle = thread_.native_handle(); - bool isRunning = true; - while (isRunning) { - auto runnable = runnables_.Pop(); - if (runnable == nullptr) { - continue; - } - isRunning = runnable(); - } - LOG_ERROR("ISharedResultSetStub thread(%{public}" PRIx64 ") is exited", uint64_t(handle)); -} -} // namespace OHOS::DataShare \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/include/datashare_connection.h b/data_share/frameworks/native/consumer/include/datashare_connection.h deleted file mode 100644 index e2acc0a5d..000000000 --- a/data_share/frameworks/native/consumer/include/datashare_connection.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_CONNECTION_H -#define DATASHARE_CONNECTION_H - -#include - -#include "ability_connect_callback_stub.h" -#include "event_handler.h" -#include "idatashare.h" -#include "want.h" - -namespace OHOS { -namespace DataShare { -using namespace AppExecFwk; -class DataShareConnection : public AAFwk::AbilityConnectionStub { -public: - DataShareConnection(const Uri &uri) : uri_(uri) {} - virtual ~DataShareConnection() = default; - - /** - * @brief This method is called back to receive the connection result after an ability calls the - * ConnectAbility method to connect it to an extension ability. - * - * @param element: Indicates information about the connected extension ability. - * @param remote: Indicates the remote proxy object of the extension ability. - * @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any - * other value indicates a connection failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - - /** - * @brief This method is called back to receive the disconnection result after the connected extension ability - * crashes or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and - * each ability previously connected to it will call onAbilityDisconnectDone. - * - * @param element: Indicates information about the disconnected extension ability. - * @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, - * and any other value indicates a disconnection failure. - */ - void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - - /** - * @brief connect remote ability of DataShareExtAbility. - */ - void ConnectDataShareExtAbility(const Uri &uri, const sptr &token); - - /** - * @brief disconnect remote ability of DataShareExtAbility. - */ - void DisconnectDataShareExtAbility(); - - /** - * @brief check whether connected to remote extension ability. - * - * @return bool true if connected, otherwise false. - */ - bool IsExtAbilityConnected(); - - /** - * @brief get the proxy of datashare extension ability. - * - * @return the proxy of datashare extension ability. - */ - sptr GetDataShareProxy(); - - struct ConnectCondition { - std::condition_variable condition; - std::mutex mutex; - }; -private: - static sptr instance_; - static std::mutex mutex_; - std::atomic isConnected_ = {false}; - sptr dataShareProxy_; - ConnectCondition condition_; - Uri uri_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_CONNECTION_H diff --git a/data_share/frameworks/native/consumer/include/datashare_proxy.h b/data_share/frameworks/native/consumer/include/datashare_proxy.h deleted file mode 100644 index ea9c37ae1..000000000 --- a/data_share/frameworks/native/consumer/include/datashare_proxy.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_PROXY_H -#define DATASHARE_PROXY_H - -#include -#include "idatashare.h" - -namespace OHOS { -namespace DataShare { -class DataShareProxy : public IRemoteProxy { -public: - explicit DataShareProxy(const sptr& remote) : IRemoteProxy(remote) {} - - virtual ~DataShareProxy() {} - - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; - - virtual int OpenFile(const Uri &uri, const std::string &mode) override; - - virtual int OpenRawFile(const Uri &uri, const std::string &mode) override; - - virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) override; - - virtual int Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) override; - - virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) override; - - virtual std::shared_ptr Query(const Uri &uri, - const DataSharePredicates &predicates, std::vector &columns) override; - - virtual std::string GetType(const Uri &uri) override; - - virtual int BatchInsert(const Uri &uri, const std::vector &values) override; - - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; - - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; - - virtual bool NotifyChange(const Uri &uri) override; - - virtual Uri NormalizeUri(const Uri &uri) override; - - virtual Uri DenormalizeUri(const Uri &uri) override; - - virtual std::vector> ExecuteBatch( - const std::vector> &operations) override; - -private: - static inline BrokerDelegator delegator_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_PROXY_H - diff --git a/data_share/frameworks/native/consumer/src/datashare_connection.cpp b/data_share/frameworks/native/consumer/src/datashare_connection.cpp deleted file mode 100644 index de3d2acf3..000000000 --- a/data_share/frameworks/native/consumer/src/datashare_connection.cpp +++ /dev/null @@ -1,118 +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 "datashare_connection.h" - -#include "ability_manager_client.h" -#include "datashare_proxy.h" -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -using namespace AppExecFwk; -constexpr int WAIT_TIME = 1; -sptr DataShareConnection::instance_ = nullptr; -std::mutex DataShareConnection::mutex_; - -/** - * @brief This method is called back to receive the connection result after an ability calls the - * ConnectAbility method to connect it to an extension ability. - * - * @param element: Indicates information about the connected extension ability. - * @param remote: Indicates the remote proxy object of the extension ability. - * @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any - * other value indicates a connection failure. - */ -void DataShareConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - LOG_INFO("called begin"); - if (remoteObject == nullptr) { - LOG_ERROR("DataShareConnection::OnAbilityConnectDone failed, remote is nullptr"); - return; - } - dataShareProxy_ = iface_cast(remoteObject); - std::unique_lock lock(condition_.mutex); - condition_.condition.notify_all(); - if (dataShareProxy_ == nullptr) { - LOG_ERROR("DataShareConnection::OnAbilityConnectDone failed, dataShareProxy_ is nullptr"); - return; - } - isConnected_.store(true); - LOG_INFO("called end"); -} - -/** - * @brief This method is called back to receive the disconnection result after the connected extension ability crashes - * or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and each ability - * previously connected to it will call onAbilityDisconnectDone. - * - * @param element: Indicates information about the disconnected extension ability. - * @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, and - * any other value indicates a disconnection failure. - */ -void DataShareConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) -{ - LOG_INFO("called begin"); - dataShareProxy_ = nullptr; - isConnected_.store(false); - LOG_INFO("called end"); -} - -/** - * @brief connect remote ability of DataShareExtAbility. - */ -void DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr &token) -{ - LOG_INFO("called begin"); - std::unique_lock lock(condition_.mutex); - AAFwk::Want want; - want.SetUri(uri); - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, this, token); - if (condition_.condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), - [this] { return dataShareProxy_ != nullptr; })) { - LOG_INFO("Wait connect timeout."); - } - LOG_INFO("called end, ret=%{public}d", ret); -} - -/** - * @brief disconnect remote ability of DataShareExtAbility. - */ -void DataShareConnection::DisconnectDataShareExtAbility() -{ - LOG_INFO("called begin"); - dataShareProxy_ = nullptr; - isConnected_.store(false); - ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(this); - LOG_INFO("called end, ret=%{public}d", ret); -} - -/** - * @brief check whether connected to remote extension ability. - * - * @return bool true if connected, otherwise false. - */ -bool DataShareConnection::IsExtAbilityConnected() -{ - return isConnected_.load(); -} - -sptr DataShareConnection::GetDataShareProxy() -{ - return dataShareProxy_; -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/src/datashare_helper.cpp b/data_share/frameworks/native/consumer/src/datashare_helper.cpp deleted file mode 100644 index 60416dda4..000000000 --- a/data_share/frameworks/native/consumer/src/datashare_helper.cpp +++ /dev/null @@ -1,826 +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 "datashare_helper.h" - -#include "datashare_result_set.h" -#include "data_ability_observer_interface.h" -#include "datashare_log.h" -#include "idatashare.h" - -namespace OHOS { -namespace DataShare { -using namespace AppExecFwk; -namespace { -const std::string SCHEME_DATASHARE = "datashare"; -constexpr int INVALID_VALUE = -1; -} // namespace - -std::mutex DataShareHelper::oplock_; - -DataShareHelper::DataShareHelper(const sptr &token, - const Uri &uri, const sptr &dataShareProxy, sptr dataShareConnection) -{ - LOG_INFO("DataShareHelper::DataShareHelper start"); - token_ = token; - uri_ = uri; - dataShareProxy_ = dataShareProxy; - dataShareConnection_ = dataShareConnection; - LOG_INFO("DataShareHelper::DataShareHelper end"); -} - -DataShareHelper::~DataShareHelper() -{ - if (callerDeathRecipient_ != nullptr) { - dataShareProxy_->AsObject()->RemoveDeathRecipient(callerDeathRecipient_); - callerDeathRecipient_ = nullptr; - } -} - -void DataShareHelper::AddDataShareDeathRecipient(const sptr &token) -{ - LOG_INFO("DataShareHelper::AddDataShareDeathRecipient start."); - if (token == nullptr) { - LOG_INFO("token is nullptr"); - return; - } - if (callerDeathRecipient_ != nullptr) { - LOG_INFO("exist callerDeathRecipient_."); - return; - } - - LOG_INFO("token AddDeathRecipient."); - callerDeathRecipient_ = - new DataShareDeathRecipient(std::bind(&DataShareHelper::OnSchedulerDied, this, std::placeholders::_1)); - token->AddDeathRecipient(callerDeathRecipient_); - - LOG_INFO("DataShareHelper::AddDataShareDeathRecipient end."); -} - -void DataShareHelper::OnSchedulerDied(const wptr &remote) -{ - LOG_INFO("start."); - if (callerDeathRecipient_ != nullptr) { - dataShareProxy_->AsObject()->RemoveDeathRecipient(callerDeathRecipient_); - callerDeathRecipient_ = nullptr; - } - dataShareProxy_ = nullptr; - dataShareConnection_->ConnectDataShareExtAbility(uri_, token_); - LOG_INFO("DataShareHelper::OnSchedulerDied end."); -} - -/** - * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship - * between the ability using the Data template (data share for short) and the associated client process in - * a DataShareHelper instance. - * - * @param context Indicates the Context object on OHOS. - * @param strUri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance. - */ -std::shared_ptr DataShareHelper::Creator( - const std::shared_ptr &context, const std::string &strUri) -{ - LOG_INFO("DataShareHelper::Creator with context and uri called start."); - if (context == nullptr) { - LOG_ERROR("DataShareHelper::Creator failed, context == nullptr"); - return nullptr; - } - sptr token = context->GetToken(); - return Creator(token, strUri); -} - -/** - * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship - * between the ability using the Data template (data share for short) and the associated client process in - * a DataShareHelper instance. - * - * @param context Indicates the Context object on OHOS. - * @param strUri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance. - */ -std::shared_ptr DataShareHelper::Creator( - const std::shared_ptr &context, const std::string &strUri) -{ - LOG_INFO("DataShareHelper::Creator with runtime context and uri called start."); - if (context == nullptr) { - LOG_ERROR("DataShareHelper::Creator failed, context == nullptr"); - return nullptr; - } - sptr token = context->GetToken(); - return Creator(token, strUri); -} - -/** - * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship - * between the ability using the Data template (data share for short) and the associated client process in - * a DataShareHelper instance. - * - * @param token Indicates the System token. - * @param strUri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance. - */ -std::shared_ptr DataShareHelper::Creator(const sptr &token, const std::string &strUri) -{ - LOG_INFO("DataShareHelper::Creator with runtime token and uri called start."); - if (token == nullptr) { - LOG_ERROR("DataShareHelper::Creator failed, token == nullptr"); - return nullptr; - } - - Uri uri(strUri); - if (uri.GetScheme() != SCHEME_DATASHARE) { - LOG_ERROR("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s", - uri.GetScheme().c_str()); - return nullptr; - } - - LOG_INFO("DataShareHelper::Creator before ConnectDataShareExtAbility."); - sptr dataShareConnection = new (std::nothrow) DataShareConnection(uri); - if (!dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->ConnectDataShareExtAbility(uri, token); - } - sptr dataShareProxy = dataShareConnection->GetDataShareProxy(); - if (dataShareProxy == nullptr) { - LOG_ERROR("DataShareHelper::Creator get invalid dataShareProxy"); - if (dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->DisconnectDataShareExtAbility(); - } - return nullptr; - } - LOG_INFO("DataShareHelper::Creator after ConnectDataShareExtAbility."); - - DataShareHelper *ptrDataShareHelper = - new (std::nothrow) DataShareHelper(token, uri, dataShareProxy, dataShareConnection); - if (ptrDataShareHelper == nullptr) { - LOG_ERROR("DataShareHelper::Creator failed, create DataShareHelper failed"); - if (dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->DisconnectDataShareExtAbility(); - } - return nullptr; - } - - LOG_INFO("DataShareHelper::Creator out."); - return std::shared_ptr(ptrDataShareHelper); -} - -/** - * @brief Releases the client resource of the data share. - * You should call this method to releases client resource after the data operations are complete. - * - * @return Returns true if the resource is successfully released; returns false otherwise. - */ -bool DataShareHelper::Release() -{ - LOG_INFO("DataShareHelper::Release start."); - LOG_INFO("DataShareHelper::Release before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - LOG_INFO("DataShareHelper::Release after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - dataShareConnection_ = nullptr; - uri_ = Uri(""); - LOG_INFO("DataShareHelper::Release end."); - return true; -} - -/** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ -std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) -{ - LOG_INFO("DataShareHelper::GetFileTypes start."); - std::vector matchedMIMEs; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return matchedMIMEs; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return matchedMIMEs; - } - - LOG_INFO("DataShareHelper::GetFileTypes before dataShareProxy_->GetFileTypes."); - matchedMIMEs = dataShareProxy_->GetFileTypes(uri, mimeTypeFilter); - LOG_INFO("DataShareHelper::GetFileTypes after dataShareProxy_->GetFileTypes."); - - LOG_INFO("DataShareHelper::GetFileTypes end."); - return matchedMIMEs; -} - -/** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ -int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) -{ - LOG_INFO("DataShareHelper::OpenFile start."); - int fd = INVALID_VALUE; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return fd; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return fd; - } - - LOG_INFO("DataShareHelper::OpenFile before dataShareProxy_->OpenFile."); - fd = dataShareProxy_->OpenFile(uri, mode); - LOG_INFO("DataShareHelper::OpenFile after dataShareProxy_->OpenFile."); - - LOG_INFO("DataShareHelper::OpenFile end."); - return fd; -} - -/** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ -int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) -{ - LOG_INFO("DataShareHelper::OpenRawFile start."); - int fd = INVALID_VALUE; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return fd; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return fd; - } - - LOG_INFO("DataShareHelper::OpenRawFile before dataShareProxy_->OpenRawFile."); - fd = dataShareProxy_->OpenRawFile(uri, mode); - LOG_INFO("DataShareHelper::OpenRawFile after dataShareProxy_->OpenRawFile."); - - LOG_INFO("DataShareHelper::OpenRawFile end."); - return fd; -} - -/** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ -int DataShareHelper::Insert(Uri &uri, const DataShareValuesBucket &value) -{ - LOG_INFO("DataShareHelper::Insert start."); - int index = INVALID_VALUE; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return index; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return index; - } - - LOG_INFO("DataShareHelper::Insert before dataShareProxy_->Insert."); - index = dataShareProxy_->Insert(uri, value); - LOG_INFO("DataShareHelper::Insert after dataShareProxy_->Insert."); - - LOG_INFO("DataShareHelper::Insert end."); - return index; -} - -/** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param value Indicates the data to update. This parameter can be null. - * - * @return Returns the number of data records updated. - */ -int DataShareHelper::Update( - Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) -{ - LOG_INFO("DataShareHelper::Update start."); - int index = INVALID_VALUE; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return index; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return index; - } - - LOG_INFO("DataShareHelper::Update before dataShareProxy_->Update."); - index = dataShareProxy_->Update(uri, predicates, value); - LOG_INFO("DataShareHelper::Update after dataShareProxy_->Update."); - - LOG_INFO("DataShareHelper::Update end."); - return index; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ -int DataShareHelper::Delete(Uri &uri, const DataSharePredicates &predicates) -{ - LOG_INFO("DataShareHelper::Delete start."); - int index = INVALID_VALUE; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return index; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return index; - } - - LOG_INFO("DataShareHelper::Delete before dataShareProxy_->Delete."); - index = dataShareProxy_->Delete(uri, predicates); - LOG_INFO("DataShareHelper::Delete after dataShareProxy_->Delete."); - - LOG_INFO("DataShareHelper::Delete end."); - return index; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * - * @return Returns the query result. - */ -std::shared_ptr DataShareHelper::Query( - Uri &uri, const DataSharePredicates &predicates, std::vector &columns) -{ - LOG_INFO("DataShareHelper::Query start."); - std::shared_ptr resultset = nullptr; - - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return resultset; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return resultset; - } - - LOG_INFO("DataShareHelper::Query before dataShareProxy_->Query."); - resultset = dataShareProxy_->Query(uri, predicates, columns); - LOG_INFO("DataShareHelper::Query after dataShareProxy_->Query."); - - LOG_INFO("DataShareHelper::Query end."); - return resultset; -} - -/** - * @brief Obtains the MIME type matching the data specified by the URI of the data share. This method should be - * implemented by a data share. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ -std::string DataShareHelper::GetType(Uri &uri) -{ - LOG_INFO("DataShareHelper::GetType start."); - std::string type; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return type; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return type; - } - - LOG_INFO("DataShareHelper::GetType before dataShareProxy_->GetType."); - type = dataShareProxy_->GetType(uri); - LOG_INFO("DataShareHelper::GetType after dataShareProxy_->GetType."); - - LOG_INFO("DataShareHelper::GetType end."); - return type; -} - -/** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ -int DataShareHelper::BatchInsert(Uri &uri, const std::vector &values) -{ - LOG_INFO("DataShareHelper::BatchInsert start."); - int ret = INVALID_VALUE; - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return ret; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return ret; - } - - LOG_INFO("DataShareHelper::BatchInsert before dataShareProxy_->BatchInsert."); - ret = dataShareProxy_->BatchInsert(uri, values); - LOG_INFO("DataShareHelper::BatchInsert after dataShareProxy_->BatchInsert."); - - LOG_INFO("DataShareHelper::BatchInsert end."); - return ret; -} - -bool DataShareHelper::CheckUriParam(const Uri &uri) -{ - LOG_INFO("DataShareHelper::CheckUriParam start."); - Uri checkUri(uri.ToString()); - if (!CheckOhosUri(checkUri)) { - LOG_ERROR("DataShareHelper::CheckUriParam failed. CheckOhosUri uri failed"); - return false; - } - - if (uri_.ToString().empty()) { - if (!CheckOhosUri(uri_)) { - LOG_ERROR("DataShareHelper::CheckUriParam failed. CheckOhosUri uri_ failed"); - return false; - } - - std::vector checkSegments; - checkUri.GetPathSegments(checkSegments); - - std::vector segments; - uri_.GetPathSegments(segments); - - if (checkSegments[0] != segments[0]) { - LOG_ERROR("DataShareHelper::CheckUriParam failed. the datashare in uri doesn't equal the one in uri_."); - return false; - } - } - LOG_INFO("DataShareHelper::CheckUriParam end."); - return true; -} - -bool DataShareHelper::CheckOhosUri(const Uri &uri) -{ - LOG_INFO("DataShareHelper::CheckOhosUri start."); - Uri checkUri(uri.ToString()); - if (checkUri.GetScheme() != SCHEME_DATASHARE) { - LOG_ERROR("DataShareHelper::CheckOhosUri failed. uri is not a datashare one."); - return false; - } - - std::vector segments; - checkUri.GetPathSegments(segments); - if (segments.empty()) { - LOG_ERROR("DataShareHelper::CheckOhosUri failed. There is no segments in the uri."); - return false; - } - - if (checkUri.GetPath() == "") { - LOG_ERROR("DataShareHelper::CheckOhosUri failed. The path in the uri is empty."); - return false; - } - LOG_INFO("DataShareHelper::CheckOhosUri end."); - return true; -} - -/** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ -void DataShareHelper::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("DataShareHelper::RegisterObserver start."); - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return; - } - - if (dataObserver == nullptr) { - LOG_ERROR("%{public}s called. dataObserver is nullptr", __func__); - return; - } - - Uri tmpUri(uri.ToString()); - std::lock_guard lock_l(oplock_); - if (uri_.ToString().empty()) { - auto datashare = registerMap_.find(dataObserver); - if (datashare == registerMap_.end()) { - if (!dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->ConnectDataShareExtAbility(uri, token_); - } - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - registerMap_.emplace(dataObserver, dataShareProxy_); - uriMap_.emplace(dataObserver, tmpUri.GetPath()); - } else { - auto path = uriMap_.find(dataObserver); - if (path->second != tmpUri.GetPath()) { - LOG_ERROR("DataShareHelper::RegisterObserver failed input uri's path is not equal the one the " - "observer used"); - return; - } - dataShareProxy_ = datashare->second; - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - LOG_ERROR("DataShareHelper::RegisterObserver failed dataShareProxy_ == nullptr"); - registerMap_.erase(dataObserver); - uriMap_.erase(dataObserver); - return; - } - dataShareProxy_->RegisterObserver(uri, dataObserver); - LOG_INFO("DataShareHelper::RegisterObserver end."); -} - -/** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ -void DataShareHelper::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("DataShareHelper::UnregisterObserver start."); - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return; - } - - if (dataObserver == nullptr) { - LOG_ERROR("%{public}s called. dataObserver is nullptr", __func__); - return; - } - - Uri tmpUri(uri.ToString()); - std::lock_guard lock_l(oplock_); - if (uri_.ToString().empty()) { - auto datashare = registerMap_.find(dataObserver); - if (datashare == registerMap_.end()) { - return; - } - auto path = uriMap_.find(dataObserver); - if (path->second != tmpUri.GetPath()) { - LOG_ERROR("DataShareHelper::UnregisterObserver failed input uri's path is not equal the one the " - "observer used"); - return; - } - dataShareProxy_ = datashare->second; - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_ == nullptr) { - LOG_ERROR("DataShareHelper::UnregisterObserver failed dataShareProxy_ == nullptr"); - return; - } - - dataShareProxy_->UnregisterObserver(uri, dataObserver); - if (uri_.ToString().empty()) { - LOG_INFO("DataShareHelper::UnregisterObserver before DisconnectDataShareExtAbility."); - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - LOG_INFO("DataShareHelper::UnregisterObserver after DisconnectDataShareExtAbility."); - dataShareProxy_ = nullptr; - } - registerMap_.erase(dataObserver); - uriMap_.erase(dataObserver); - LOG_INFO("DataShareHelper::UnregisterObserver end."); -} - -/** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - */ -void DataShareHelper::NotifyChange(const Uri &uri) -{ - LOG_INFO("DataShareHelper::NotifyChange start."); - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return; - } - - LOG_INFO("DataShareHelper::NotifyChange before dataShareProxy_->NotifyChange."); - dataShareProxy_->NotifyChange(uri); - LOG_INFO("DataShareHelper::NotifyChange after dataShareProxy_->NotifyChange."); - - LOG_INFO("DataShareHelper::NotifyChange end."); -} - -/** - * @brief Converts the given uri that refer to the data share into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the data share even if the - * context has changed. If you implement URI normalization for a data share, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any - * method that is called on the data share must require normalization verification and denormalization. The default - * implementation of this method returns null, indicating that this data share does not support URI normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the data share supports URI normalization; returns null otherwise. - */ -Uri DataShareHelper::NormalizeUri(Uri &uri) -{ - LOG_INFO("DataShareHelper::NormalizeUri start."); - Uri urivalue(""); - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return urivalue; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return urivalue; - } - - LOG_INFO("DataShareHelper::NormalizeUri before dataShareProxy_->NormalizeUri."); - urivalue = dataShareProxy_->NormalizeUri(uri); - LOG_INFO("DataShareHelper::NormalizeUri after dataShareProxy_->NormalizeUri."); - - LOG_INFO("DataShareHelper::NormalizeUri end."); - return urivalue; -} - -/** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to - * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in - * the current environment. - */ -Uri DataShareHelper::DenormalizeUri(Uri &uri) -{ - LOG_INFO("DataShareHelper::DenormalizeUri start."); - Uri urivalue(""); - if (!CheckUriParam(uri)) { - LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__); - return urivalue; - } - - if (dataShareProxy_ == nullptr) { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } - - if (dataShareProxy_) { - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - } else { - LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__); - return urivalue; - } - - LOG_INFO("DataShareHelper::DenormalizeUri before dataShareProxy_->DenormalizeUri."); - urivalue = dataShareProxy_->DenormalizeUri(uri); - LOG_INFO("DataShareHelper::DenormalizeUri after dataShareProxy_->DenormalizeUri."); - - LOG_INFO("DataShareHelper::DenormalizeUri end."); - return urivalue; -} - -void DataShareDeathRecipient::OnRemoteDied(const wptr &remote) -{ - LOG_INFO("recv DataShareDeathRecipient death notice"); - if (handler_) { - handler_(remote); - } - LOG_INFO("DataShareHelper::OnRemoteDied end."); -} - -DataShareDeathRecipient::DataShareDeathRecipient(RemoteDiedHandler handler) : handler_(handler) -{} - -DataShareDeathRecipient::~DataShareDeathRecipient() -{} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp b/data_share/frameworks/native/consumer/src/datashare_proxy.cpp deleted file mode 100644 index 081843aee..000000000 --- a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp +++ /dev/null @@ -1,580 +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 "datashare_proxy.h" - -#include - -#include "datashare_result_set.h" -#include "data_ability_observer_interface.h" -#include "datashare_operation.h" -#include "datashare_log.h" -#include "ipc_types.h" -#include "ishared_result_set.h" -#include "pac_map.h" - -namespace OHOS { -namespace DataShare { -std::vector DataShareProxy::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - LOG_INFO("begin."); - std::vector types; - - MessageParcel data; - MessageParcel reply; - MessageOption option; - - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return types; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return types; - } - - if (!data.WriteString(mimeTypeFilter)) { - LOG_ERROR("fail to WriteString mimeTypeFilter"); - return types; - } - - int32_t err = Remote()->SendRequest(CMD_GET_FILE_TYPES, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); - } - - if (!reply.ReadStringVector(&types)) { - LOG_ERROR("fail to ReadStringVector types"); - } - - LOG_INFO("end successfully."); - return types; -} - -int DataShareProxy::OpenFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - int fd = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return fd; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return fd; - } - - if (!data.WriteString(mode)) { - LOG_ERROR("fail to WriteString mode"); - return fd; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_OPEN_FILE, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("OpenFile fail to SendRequest. err: %d", err); - return fd; - } - - fd = reply.ReadFileDescriptor(); - if (fd == -1) { - LOG_ERROR("fail to ReadFileDescriptor fd"); - return fd; - } - - LOG_INFO("end successfully."); - return fd; -} - -int DataShareProxy::OpenRawFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - int fd = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return fd; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return fd; - } - - if (!data.WriteString(mode)) { - LOG_ERROR("fail to WriteString mode"); - return fd; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_OPEN_RAW_FILE, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("OpenRawFile fail to SendRequest. err: %d", err); - return fd; - } - - if (!reply.ReadInt32(fd)) { - LOG_ERROR("fail to ReadInt32 fd"); - return fd; - } - - LOG_INFO("end successfully."); - return fd; -} - -int DataShareProxy::Insert(const Uri &uri, const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - int index = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return index; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!DataShareValuesBucket::Marshalling(value, data)) { - LOG_ERROR("fail to WriteParcelable value"); - return index; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_INSERT, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("Insert fail to SendRequest. err: %d", err); - return index; - } - - if (!reply.ReadInt32(index)) { - LOG_ERROR("fail to ReadInt32 index"); - return index; - } - - LOG_INFO("end successfully."); - return index; -} - -int DataShareProxy::Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - int index = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return index; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!data.WriteParcelable(&predicates)) { - LOG_ERROR("fail to WriteParcelable predicates"); - return index; - } - - if (!DataShareValuesBucket::Marshalling(value, data)) { - LOG_ERROR("fail to WriteParcelable value"); - return index; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_UPDATE, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("Update fail to SendRequest. err: %d", err); - return index; - } - - if (!reply.ReadInt32(index)) { - LOG_ERROR("fail to ReadInt32 index"); - return index; - } - - LOG_INFO("end successfully."); - return index; -} - -int DataShareProxy::Delete(const Uri &uri, const DataSharePredicates &predicates) -{ - LOG_INFO("begin."); - int index = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return index; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!data.WriteParcelable(&predicates)) { - LOG_ERROR("fail to WriteParcelable predicates"); - return index; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_DELETE, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("Delete fail to SendRequest. err: %d", err); - return index; - } - - if (!reply.ReadInt32(index)) { - LOG_ERROR("fail to ReadInt32 index"); - return index; - } - - LOG_INFO("end successfully."); - return index; -} - -std::shared_ptr DataShareProxy::Query(const Uri &uri, - const DataSharePredicates &predicates, std::vector &columns) -{ - LOG_INFO("begin."); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return nullptr; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return nullptr; - } - - if (!data.WriteParcelable(&predicates)) { - LOG_ERROR("fail to WriteParcelable predicates"); - return nullptr; - } - - if (!data.WriteStringVector(columns)) { - LOG_ERROR("fail to WriteStringVector columns"); - return nullptr; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_QUERY, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("Query fail to SendRequest. err: %d", err); - return nullptr; - } - LOG_INFO("end successfully."); - return ISharedResultSet::ReadFromParcel(reply); -} - -std::string DataShareProxy::GetType(const Uri &uri) -{ - LOG_INFO("begin."); - std::string type; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return type; - } - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return type; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_GET_TYPE, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); - return type; - } - - type = reply.ReadString(); - if (type.empty()) { - LOG_ERROR("fail to ReadString type"); - return type; - } - - LOG_INFO("end successfully."); - return type; -} - -int DataShareProxy::BatchInsert(const Uri &uri, const std::vector &values) -{ - LOG_INFO("begin."); - int ret = -1; - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return ret; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return ret; - } - - int count = (int)values.size(); - if (!data.WriteInt32(count)) { - LOG_ERROR("fail to WriteInt32 ret"); - return ret; - } - - for (int i = 0; i < count; i++) { - if (!DataShareValuesBucket::Marshalling(values[i], data)) { - LOG_ERROR("fail to WriteParcelable ret, index = %{public}d", i); - return ret; - } - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_BATCH_INSERT, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err); - return ret; - } - - if (!reply.ReadInt32(ret)) { - LOG_ERROR("fail to ReadInt32 index"); - return ret; - } - - LOG_INFO("end successfully."); - return ret; -} - -bool DataShareProxy::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return false; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__); - return false; - } - - if (!data.WriteRemoteObject(dataObserver->AsObject())) { - LOG_ERROR("%{public}s failed to WriteParcelable dataObserver ", __func__); - return false; - } - - MessageParcel reply; - MessageOption option; - int32_t result = Remote()->SendRequest(CMD_REGISTER_OBSERVER, data, reply, option); - if (result == ERR_NONE) { - LOG_INFO("SendRequest ok, retval is %{public}d", reply.ReadInt32()); - } else { - LOG_ERROR("SendRequest error, result=%{public}d", result); - return false; - } - LOG_INFO("end."); - return true; -} - -bool DataShareProxy::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return false; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__); - return false; - } - - if (!data.WriteRemoteObject(dataObserver->AsObject())) { - LOG_ERROR("%{public}s failed to WriteParcelable dataObserver ", __func__); - return false; - } - - MessageParcel reply; - MessageOption option; - int32_t result = Remote()->SendRequest(CMD_UNREGISTER_OBSERVER, data, reply, option); - if (result == ERR_NONE) { - LOG_INFO("SendRequest ok, retval is %{public}d", reply.ReadInt32()); - } else { - LOG_ERROR("SendRequest error, result=%{public}d", result); - return false; - } - LOG_INFO("end successfully."); - return true; -} - -bool DataShareProxy::NotifyChange(const Uri &uri) -{ - LOG_INFO("begin."); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return false; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__); - return false; - } - - MessageParcel reply; - MessageOption option; - int32_t result = Remote()->SendRequest(CMD_NOTIFY_CHANGE, data, reply, option); - if (result == ERR_NONE) { - LOG_INFO("SendRequest ok, retval is %{public}d", reply.ReadInt32()); - } else { - LOG_ERROR("SendRequest error, result=%{public}d", result); - return false; - } - LOG_INFO("end successfully."); - return true; -} - -Uri DataShareProxy::NormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - Uri urivalue(""); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return urivalue; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return urivalue; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_NORMALIZE_URI, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("NormalizeUri fail to SendRequest. err: %d", err); - return urivalue; - } - - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - LOG_ERROR("ReadParcelable value is nullptr."); - return urivalue; - } - LOG_INFO("end successfully."); - return *info; -} - -Uri DataShareProxy::DenormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - Uri urivalue(""); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return urivalue; - } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return urivalue; - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_DENORMALIZE_URI, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("DenormalizeUri fail to SendRequest. err: %d", err); - return urivalue; - } - - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - LOG_ERROR("ReadParcelable value is nullptr."); - return urivalue; - } - LOG_INFO("end successfully."); - return *info; -} - -std::vector> DataShareProxy::ExecuteBatch( - const std::vector> &operations) -{ - LOG_INFO("begin."); - MessageParcel data; - std::vector> results; - results.clear(); - - if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { - LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__); - return results; - } - - int count = (int)operations.size(); - if (!data.WriteInt32(count)) { - LOG_ERROR("fail to WriteInt32 ret"); - return results; - } - - for (int i = 0; i < count; i++) { - if (!data.WriteParcelable(operations[i].get())) { - LOG_ERROR("fail to WriteParcelable ret, index = %{public}d", i); - return results; - } - } - - MessageParcel reply; - MessageOption option; - int32_t err = Remote()->SendRequest(CMD_EXECUTE_BATCH, data, reply, option); - if (err != NO_ERROR) { - LOG_ERROR("fail to SendRequest. err: %{public}d", err); - return results; - } - - int total = 0; - if (!reply.ReadInt32(total)) { - LOG_ERROR("fail to ReadInt32 count %{public}d", total); - return results; - } - - for (int i = 0; i < total; i++) { - DataShareResult *result = reply.ReadParcelable(); - if (result == nullptr) { - LOG_ERROR("result is nullptr, index = %{public}d", i); - return results; - } - std::shared_ptr dataShareResult(result); - results.push_back(dataShareResult); - } - LOG_INFO("end successfully."); - return results; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/provider/include/datashare_ext_ability.h b/data_share/frameworks/native/provider/include/datashare_ext_ability.h deleted file mode 100644 index f49a8b090..000000000 --- a/data_share/frameworks/native/provider/include/datashare_ext_ability.h +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_EXT_ABILITY_H -#define DATASHARE_EXT_ABILITY_H - -#include "extension_base.h" -#include "datashare_values_bucket.h" -#include "datashare_result.h" -#include "datashare_predicates.h" -#include "datashare_result_set.h" -#include "datashare_operation.h" - -namespace OHOS { -namespace AAFwk { -class IDataAbilityObserver; -} -namespace AbilityRuntime { -class Runtime; -} -namespace DataShare { -using namespace AbilityRuntime; -class DataShareExtAbilityContext; -class DataShareExtAbility; -using CreatorFunc = std::function& runtime)>; -/** - * @brief Basic datashare extension ability components. - */ -class DataShareExtAbility : public ExtensionBase { -public: - DataShareExtAbility() = default; - virtual ~DataShareExtAbility() = default; - - /** - * @brief Init the extension. - * - * @param record the extension record. - * @param application the application info. - * @param handler the extension handler. - * @param token the remote token. - */ - virtual void Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) override; - - /** - * @brief Create Extension. - * - * @param runtime The runtime. - * @return The DataShareExtAbility instance. - */ - static DataShareExtAbility* Create(const std::unique_ptr& runtime); - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter); - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - virtual int OpenFile(const Uri &uri, const std::string &mode); - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - virtual int OpenRawFile(const Uri &uri, const std::string &mode); - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - virtual int Insert(const Uri &uri, const DataShareValuesBucket &value); - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param value Indicates the data to update. This parameter can be null. - * - * @return Returns the number of data records updated. - */ - virtual int Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - virtual int Delete(const Uri &uri, const DataSharePredicates &predicates); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * - * @return Returns the query result. - */ - virtual std::shared_ptr Query( - const Uri &uri, const DataSharePredicates &predicates, std::vector &columns); - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - virtual std::string GetType(const Uri &uri); - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - virtual int BatchInsert(const Uri &uri, const std::vector &values); - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - * - * @return Return true if success. otherwise return false. - */ - virtual bool NotifyChange(const Uri &uri); - - /** - * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if - * the context has changed. If you implement URI normalization for a Data ability, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data ability must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data ability does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. - */ - virtual Uri NormalizeUri(const Uri &uri); - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri - * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot - * be found in the current environment. - */ - virtual Uri DenormalizeUri(const Uri &uri); - - /** - * @brief Performs batch operations on the database. - * - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - virtual std::vector> ExecuteBatch( - const std::vector> &operations); - - /** - * @brief Set a creator function. - * - * @param creator The function for create a datashare extension ability. - */ - static void SetCreator(const CreatorFunc& creator); -private: - static CreatorFunc creator_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_EXT_ABILITY_H \ No newline at end of file diff --git a/data_share/frameworks/native/provider/include/datashare_ext_ability_context.h b/data_share/frameworks/native/provider/include/datashare_ext_ability_context.h deleted file mode 100644 index 70ac41f30..000000000 --- a/data_share/frameworks/native/provider/include/datashare_ext_ability_context.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_EXT_ABILITY_CONTEXT_H -#define DATASHARE_EXT_ABILITY_CONTEXT_H - -#include "extension_context.h" - -namespace OHOS { -namespace DataShare { -using namespace AbilityRuntime; -/** - * @brief context supply for datashare - * - */ -class DataShareExtAbilityContext : public ExtensionContext { -public: - DataShareExtAbilityContext(); - virtual ~DataShareExtAbilityContext() = default; - - using SelfType = DataShareExtAbilityContext; - static const size_t CONTEXT_TYPE_ID; - -protected: - bool IsContext(size_t contextTypeId) override - { - return contextTypeId == CONTEXT_TYPE_ID || ExtensionContext::IsContext(contextTypeId); - } -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_EXT_ABILITY_CONTEXT_H \ No newline at end of file diff --git a/data_share/frameworks/native/provider/include/datashare_ext_ability_module_loader.h b/data_share/frameworks/native/provider/include/datashare_ext_ability_module_loader.h deleted file mode 100644 index a2cbf0ccb..000000000 --- a/data_share/frameworks/native/provider/include/datashare_ext_ability_module_loader.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_EXT_ABILITY_MODULE_LOADER_H -#define DATASHARE_EXT_ABILITY_MODULE_LOADER_H - -#include "extension_module_loader.h" - -namespace OHOS::DataShare { -using namespace AbilityRuntime; -class DataShareExtAbilityModuleLoader : public ExtensionModuleLoader, - public Singleton { - DECLARE_SINGLETON(DataShareExtAbilityModuleLoader); - -public: - /** - * @brief Create Extension. - * - * @param runtime The runtime. - * @return The Extension instance. - */ - virtual Extension *Create(const std::unique_ptr& runtime) const override; -}; -} // namespace OHOS::DataShare -#endif // DATASHARE_EXT_ABILITY_MODULE_LOADER_H \ No newline at end of file diff --git a/data_share/frameworks/native/provider/include/datashare_stub.h b/data_share/frameworks/native/provider/include/datashare_stub.h deleted file mode 100644 index 573d7fb93..000000000 --- a/data_share/frameworks/native/provider/include/datashare_stub.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_STUB_H -#define DATASHARE_STUB_H - -#include -#include - -#include "idatashare.h" - -namespace OHOS { -namespace DataShare { -class DataShareStub : public IRemoteStub { -public: - DataShareStub(); - ~DataShareStub(); - int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; -private: - ErrCode CmdGetFileTypes(MessageParcel &data, MessageParcel &reply); - ErrCode CmdOpenFile(MessageParcel &data, MessageParcel &reply); - ErrCode CmdOpenRawFile(MessageParcel &data, MessageParcel &reply); - ErrCode CmdInsert(MessageParcel &data, MessageParcel &reply); - ErrCode CmdUpdate(MessageParcel &data, MessageParcel &reply); - ErrCode CmdDelete(MessageParcel &data, MessageParcel &reply); - ErrCode CmdQuery(MessageParcel &data, MessageParcel &reply); - ErrCode CmdGetType(MessageParcel &data, MessageParcel &reply); - ErrCode CmdBatchInsert(MessageParcel &data, MessageParcel &reply); - ErrCode CmdRegisterObserver(MessageParcel &data, MessageParcel &reply); - ErrCode CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply); - ErrCode CmdNotifyChange(MessageParcel &data, MessageParcel &reply); - ErrCode CmdNormalizeUri(MessageParcel &data, MessageParcel &reply); - ErrCode CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply); - ErrCode CmdExecuteBatch(MessageParcel &data, MessageParcel &reply); - - using RequestFuncType = int (DataShareStub::*)(MessageParcel &data, MessageParcel &reply); - std::map stubFuncMap_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_STUB_H - diff --git a/data_share/frameworks/native/provider/include/datashare_stub_impl.h b/data_share/frameworks/native/provider/include/datashare_stub_impl.h deleted file mode 100644 index a443bc539..000000000 --- a/data_share/frameworks/native/provider/include/datashare_stub_impl.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_STUB_IMPL_H -#define DATASHARE_STUB_IMPL_H - -#include -#include "datashare_stub.h" -#include "datashare_uv_queue.h" -#include "js_datashare_ext_ability.h" -#include "native_engine/native_value.h" - -namespace OHOS { -namespace DataShare { -using DataShare::JsDataShareExtAbility; -class DataShareStubImpl : public DataShareStub { -public: - explicit DataShareStubImpl(const std::shared_ptr& extension, napi_env env) - : extension_(extension) - { - uvQueue_ = std::make_shared(env); - } - - virtual ~DataShareStubImpl() {} - - std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; - - int OpenFile(const Uri &uri, const std::string &mode) override; - - int OpenRawFile(const Uri &uri, const std::string &mode) override; - - 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) override; - - std::string GetType(const Uri &uri) override; - - int BatchInsert(const Uri &uri, const std::vector &values) override; - - bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; - - bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; - - bool NotifyChange(const Uri &uri) override; - - Uri NormalizeUri(const Uri &uri) override; - - Uri DenormalizeUri(const Uri &uri) override; - - std::vector> ExecuteBatch( - const std::vector> &operations) override; - -private: - std::shared_ptr GetOwner(); - -private: - std::shared_ptr extension_; - std::shared_ptr uvQueue_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_STUB_IMPL_H - diff --git a/data_share/frameworks/native/provider/include/datashare_uv_queue.h b/data_share/frameworks/native/provider/include/datashare_uv_queue.h deleted file mode 100644 index 34cac5996..000000000 --- a/data_share/frameworks/native/provider/include/datashare_uv_queue.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_UV_QUEUE_H -#define DATASHARE_UV_QUEUE_H - -#include - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "uv.h" - -namespace OHOS { -namespace DataShare { -class DataShareUvQueue { - using NapiVoidFunc = std::function; - using NapiBoolFunc = std::function; - -public: - explicit DataShareUvQueue(napi_env env); - virtual ~DataShareUvQueue() = default; - - void SyncCall(NapiVoidFunc func = NapiVoidFunc(), NapiBoolFunc retFunc = NapiBoolFunc()); - - void CheckFuncAndExec(NapiBoolFunc retFunc); - -private: - struct UvEntry { - napi_env env; - NapiVoidFunc func; - bool done; - bool purge; - std::condition_variable condition; - std::mutex mutex; - NapiBoolFunc retFunc; - }; - - static void Purge(uv_work_t* work); - - napi_env env_ = nullptr; - uv_loop_s* loop_ = nullptr; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_UV_QUEUE_H \ No newline at end of file diff --git a/data_share/frameworks/native/provider/include/js_datashare_ext_ability.h b/data_share/frameworks/native/provider/include/js_datashare_ext_ability.h deleted file mode 100644 index f42e7892f..000000000 --- a/data_share/frameworks/native/provider/include/js_datashare_ext_ability.h +++ /dev/null @@ -1,320 +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 JS_DATASHARE_EXT_ABILITY_H -#define JS_DATASHARE_EXT_ABILITY_H - -#include "datashare_result_set.h" -#include "datashare_predicates.h" -#include "datashare_ext_ability.h" -#include "js_runtime.h" -#include "native_engine/native_reference.h" -#include "native_engine/native_value.h" - -namespace OHOS { -namespace DataShare { -using namespace AbilityRuntime; - -/** - * @brief Basic datashare extension ability components. - */ -class JsDataShareExtAbility : public DataShareExtAbility { -public: - explicit JsDataShareExtAbility(JsRuntime& jsRuntime); - virtual ~JsDataShareExtAbility() override; - - /** - * @brief Create JsDataShareExtAbility. - * - * @param runtime The runtime. - * @return The JsDataShareExtAbility instance. - */ - static JsDataShareExtAbility* Create(const std::unique_ptr& runtime); - - /** - * @brief Init the extension. - * - * @param record the extension record. - * @param application the application info. - * @param handler the extension handler. - * @param token the remote token. - */ - void Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) override; - - /** - * @brief Called when this datashare extension ability is started. You must override this function if you want to - * perform some initialization operations during extension startup. - * - * This function can be called only once in the entire lifecycle of an extension. - * @param Want Indicates the {@link Want} structure containing startup information about the extension. - */ - void OnStart(const AAFwk::Want &want) override; - - /** - * @brief Called when this datashare extension ability is connected for the first time. - * - * You can override this function to implement your own processing logic. - * - * @param want Indicates the {@link Want} structure containing connection information about the datashare - * extension. - * @return Returns a pointer to the sid of the connected datashare extension ability. - */ - sptr OnConnect(const AAFwk::Want &want) override; - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - int OpenFile(const Uri &uri, const std::string &mode) override; - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - int OpenRawFile(const Uri &uri, const std::string &mode) override; - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - int Insert(const Uri &uri, const DataShareValuesBucket &value) override; - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param value Indicates the data to update. This parameter can be null. - * - * @return Returns the number of data records updated. - */ - int Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) override; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - int Delete(const Uri &uri, const DataSharePredicates &predicates) override; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * - * @return Returns the query result. - */ - std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, - std::vector &columns) override; - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - std::string GetType(const Uri &uri) override; - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - int BatchInsert(const Uri &uri, const std::vector &values) override; - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - * - * @return Return true if success. otherwise return false. - */ - bool NotifyChange(const Uri &uri) override; - - /** - * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if - * the context has changed. If you implement URI normalization for a Data ability, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data ability must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data ability does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. - */ - Uri NormalizeUri(const Uri &uri) override; - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri - * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot - * be found in the current environment. - */ - Uri DenormalizeUri(const Uri &uri) override; - - /** - * @brief Performs batch operations on the database. - * - * @param operations Indicates a list of database operations on the database. - * @return Returns the result of each operation, in array. - */ - std::vector> ExecuteBatch( - const std::vector> &operations) override; - - bool GetBlockWaiting() const - { - return isBlockWaiting_; - } - void SetBlockWaiting(bool blockWaiting) - { - isBlockWaiting_ = blockWaiting; - } - - NativeValue* GetAsyncResult() const - { - return callbackData_; - } - - void SetAsyncResult(NativeValue* asyncResult) - { - callbackData_ = asyncResult; - } - - void GetResult(int &value) - { - value = callbackResultNumber_; - } - - void SetResult(const int value) - { - callbackResultNumber_ = value; - } - - void GetResult(std::string &value) - { - value = callbackResultString_; - } - - void SetResult(const std::string value) - { - callbackResultString_ = value; - } - - void GetResult(std::vector &value) - { - value = callbackResultStringArr_; - } - - void SetResult(const std::vector value) - { - callbackResultStringArr_ = value; - } - - void GetResult(std::shared_ptr &value) - { - value = callbackResultObject_; - } - - void SetResult(const std::shared_ptr value) - { - callbackResultObject_ = value; - } - -private: - NativeValue* CallObjectMethod(const char *name, NativeValue * const *argv = nullptr, size_t argc = 0, - bool isAsync = true); - void GetSrcPath(std::string &srcPath); - bool CheckCallingPermission(const std::string &permission); - napi_value MakePredicates(napi_env env, const DataSharePredicates &predicates); - static NativeValue* AsyncCallback(NativeEngine* engine, NativeCallbackInfo* info); - void CheckAndSetAsyncResult(NativeEngine* engine); - - JsRuntime& jsRuntime_; - std::unique_ptr jsObj_; - bool isBlockWaiting_ = false; - NativeValue* callbackData_ = nullptr; - int callbackResultNumber_ = -1; - std::string callbackResultString_ = ""; - std::vector callbackResultStringArr_ = {}; - std::shared_ptr callbackResultObject_ = nullptr; -}; -} // namespace DataShare -} // namespace OHOS -#endif // JS_DATASHARE_EXT_ABILITY_H \ No newline at end of file diff --git a/data_share/frameworks/native/provider/include/js_datashare_ext_ability_context.h b/data_share/frameworks/native/provider/include/js_datashare_ext_ability_context.h deleted file mode 100644 index e97c142a0..000000000 --- a/data_share/frameworks/native/provider/include/js_datashare_ext_ability_context.h +++ /dev/null @@ -1,33 +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 JS_DATASHARE_EXT_ABILITY_CONTEXT_H -#define JS_DATASHARE_EXT_ABILITY_CONTEXT_H - -#include - -#include "ability_connect_callback.h" -#include "datashare_ext_ability_context.h" -#include "native_engine/native_engine.h" -#include "native_engine/native_value.h" - -namespace OHOS { -namespace DataShare { -using namespace AbilityRuntime; -NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine, - std::shared_ptr context); -} // namespace DataShare -} // namespace OHOS -#endif // JS_DATASHARE_EXT_ABILITY_CONTEXT_H diff --git a/data_share/frameworks/native/provider/src/datashare_ext_ability.cpp b/data_share/frameworks/native/provider/src/datashare_ext_ability.cpp deleted file mode 100644 index 5bdc592d9..000000000 --- a/data_share/frameworks/native/provider/src/datashare_ext_ability.cpp +++ /dev/null @@ -1,177 +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 "datashare_ext_ability.h" - -#include "ability_loader.h" -#include "connection_manager.h" -#include "datashare_log.h" -#include "js_datashare_ext_ability.h" -#include "runtime.h" -#include "datashare_ext_ability_context.h" - -namespace OHOS { -namespace DataShare { -using namespace OHOS::AppExecFwk; - -CreatorFunc DataShareExtAbility::creator_ = nullptr; -void DataShareExtAbility::SetCreator(const CreatorFunc& creator) -{ - creator_ = creator; -} - -DataShareExtAbility* DataShareExtAbility::Create(const std::unique_ptr& runtime) -{ - if (!runtime) { - return new DataShareExtAbility(); - } - - if (creator_) { - return creator_(runtime); - } - - LOG_INFO("DataShareExtAbility::Create runtime"); - switch (runtime->GetLanguage()) { - case Runtime::Language::JS: - return JsDataShareExtAbility::Create(runtime); - - default: - return new DataShareExtAbility(); - } -} - -void DataShareExtAbility::Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) -{ - ExtensionBase::Init(record, application, handler, token); - LOG_INFO("DataShareExtAbility begin init context"); -} - -std::vector DataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - LOG_INFO("begin."); - std::vector ret; - LOG_INFO("end."); - return ret; -} - -int DataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return 0; -} - -int DataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return 0; -} - -int DataShareExtAbility::Insert(const Uri &uri, const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return 0; -} - -int DataShareExtAbility::Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return 0; -} - -int DataShareExtAbility::Delete(const Uri &uri, const DataSharePredicates &predicates) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return 0; -} - -std::shared_ptr DataShareExtAbility::Query(const Uri &uri, - const DataSharePredicates &predicates, std::vector &columns) -{ - LOG_INFO("begin."); - std::shared_ptr ret; - LOG_INFO("end."); - return ret; -} - -std::string DataShareExtAbility::GetType(const Uri &uri) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return ""; -} - -int DataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &values) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return 0; -} - -bool DataShareExtAbility::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return true; -} - -bool DataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return true; -} - -bool DataShareExtAbility::NotifyChange(const Uri &uri) -{ - LOG_INFO("begin."); - LOG_INFO("end."); - return true; -} - -Uri DataShareExtAbility::NormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - Uri urivalue(""); - LOG_INFO("end."); - return urivalue; -} - -Uri DataShareExtAbility::DenormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - Uri urivalue(""); - LOG_INFO("end."); - return urivalue; -} - -std::vector> DataShareExtAbility::ExecuteBatch( - const std::vector> &operations) -{ - LOG_INFO("begin."); - std::vector> results; - LOG_INFO("end."); - return results; -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/datashare_ext_ability_context.cpp b/data_share/frameworks/native/provider/src/datashare_ext_ability_context.cpp deleted file mode 100644 index 5bac89cd1..000000000 --- a/data_share/frameworks/native/provider/src/datashare_ext_ability_context.cpp +++ /dev/null @@ -1,25 +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 "datashare_ext_ability_context.h" - -namespace OHOS { -namespace DataShare { -using namespace AbilityRuntime; -const size_t DataShareExtAbilityContext::CONTEXT_TYPE_ID(std::hash {} ("DataShareExtAbilityContext")); - -DataShareExtAbilityContext::DataShareExtAbilityContext() {} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/datashare_ext_ability_module_loader.cpp b/data_share/frameworks/native/provider/src/datashare_ext_ability_module_loader.cpp deleted file mode 100644 index fd1dd90d4..000000000 --- a/data_share/frameworks/native/provider/src/datashare_ext_ability_module_loader.cpp +++ /dev/null @@ -1,38 +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 "datashare_ext_ability_module_loader.h" -#include "datashare_ext_ability.h" - -namespace OHOS::DataShare { -using namespace AbilityRuntime; -DataShareExtAbilityModuleLoader::DataShareExtAbilityModuleLoader() = default; -DataShareExtAbilityModuleLoader::~DataShareExtAbilityModuleLoader() = default; - -Extension *DataShareExtAbilityModuleLoader::Create(const std::unique_ptr& runtime) const -{ - return DataShareExtAbility::Create(runtime); -} - -extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule() -{ - return &DataShareExtAbilityModuleLoader::GetInstance(); -} - -extern "C" __attribute__((visibility("default"))) void SetCreator(const CreatorFunc& creator) -{ - return DataShareExtAbility::SetCreator(creator); -} -} // namespace OHOS::DataShare \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/datashare_stub.cpp b/data_share/frameworks/native/provider/src/datashare_stub.cpp deleted file mode 100644 index 327460626..000000000 --- a/data_share/frameworks/native/provider/src/datashare_stub.cpp +++ /dev/null @@ -1,418 +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 "datashare_stub.h" - -#include "data_ability_observer_interface.h" -#include "data_ability_operation.h" -#include "data_ability_predicates.h" -#include "datashare_log.h" -#include "ipc_types.h" -#include "ishared_result_set.h" -#include "values_bucket.h" - -namespace OHOS { -namespace DataShare { -DataShareStub::DataShareStub() -{ - stubFuncMap_[CMD_GET_FILE_TYPES] = &DataShareStub::CmdGetFileTypes; - stubFuncMap_[CMD_OPEN_FILE] = &DataShareStub::CmdOpenFile; - stubFuncMap_[CMD_OPEN_RAW_FILE] = &DataShareStub::CmdOpenRawFile; - stubFuncMap_[CMD_INSERT] = &DataShareStub::CmdInsert; - stubFuncMap_[CMD_UPDATE] = &DataShareStub::CmdUpdate; - stubFuncMap_[CMD_DELETE] = &DataShareStub::CmdDelete; - stubFuncMap_[CMD_QUERY] = &DataShareStub::CmdQuery; - stubFuncMap_[CMD_GET_TYPE] = &DataShareStub::CmdGetType; - stubFuncMap_[CMD_BATCH_INSERT] = &DataShareStub::CmdBatchInsert; - stubFuncMap_[CMD_REGISTER_OBSERVER] = &DataShareStub::CmdRegisterObserver; - stubFuncMap_[CMD_UNREGISTER_OBSERVER] = &DataShareStub::CmdUnregisterObserver; - stubFuncMap_[CMD_NOTIFY_CHANGE] = &DataShareStub::CmdNotifyChange; - stubFuncMap_[CMD_NORMALIZE_URI] = &DataShareStub::CmdNormalizeUri; - stubFuncMap_[CMD_DENORMALIZE_URI] = &DataShareStub::CmdDenormalizeUri; - stubFuncMap_[CMD_EXECUTE_BATCH] = &DataShareStub::CmdExecuteBatch; -} - -DataShareStub::~DataShareStub() -{ - stubFuncMap_.clear(); -} - -int DataShareStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, - MessageOption& option) -{ - LOG_INFO("Received stub message: %{public}d", code); - std::u16string descriptor = DataShareStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - LOG_INFO("local descriptor is not equal to remote"); - return ERR_INVALID_STATE; - } - - const auto &itFunc = stubFuncMap_.find(code); - if (itFunc != stubFuncMap_.end()) { - return (this->*(itFunc->second))(data, reply); - } - - LOG_INFO("remote request unhandled: %{public}d", code); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} - -ErrCode DataShareStub::CmdGetFileTypes(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string mimeTypeFilter = data.ReadString(); - if (mimeTypeFilter.empty()) { - LOG_ERROR("DataShareStub mimeTypeFilter is nullptr"); - return ERR_INVALID_VALUE; - } - std::vector types = GetFileTypes(*uri, mimeTypeFilter); - if (!reply.WriteStringVector(types)) { - LOG_ERROR("fail to WriteStringVector types"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdOpenFile(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string mode = data.ReadString(); - if (mode.empty()) { - LOG_ERROR("DataShareStub mode is nullptr"); - return ERR_INVALID_VALUE; - } - int fd = OpenFile(*uri, mode); - if (fd < 0) { - LOG_ERROR("OpenFile fail, fd is %{pubilc}d", fd); - return ERR_INVALID_VALUE; - } - if (!reply.WriteFileDescriptor(fd)) { - LOG_ERROR("fail to WriteFileDescriptor fd"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdOpenRawFile(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string mode = data.ReadString(); - if (mode.empty()) { - LOG_ERROR("DataShareStub mode is nullptr"); - return ERR_INVALID_VALUE; - } - int fd = OpenRawFile(*uri, mode); - if (!reply.WriteInt32(fd)) { - LOG_ERROR("fail to WriteInt32 fd"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdInsert(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr value(DataShareValuesBucket::Unmarshalling(data)); - if (value == nullptr) { - LOG_ERROR("ReadParcelable value is nullptr"); - return ERR_INVALID_VALUE; - } - int index = Insert(*uri, *value); - if (!reply.WriteInt32(index)) { - LOG_ERROR("fail to WriteInt32 index"); - return ERR_INVALID_VALUE; - } - LOG_INFO("DataShareStub::CmdInsertInner end"); - return NO_ERROR; -} - -ErrCode DataShareStub::CmdUpdate(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr predicates( - data.ReadParcelable()); - if (predicates == nullptr) { - LOG_ERROR("ReadParcelable predicates is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr value(DataShareValuesBucket::Unmarshalling(data)); - if (value == nullptr) { - LOG_ERROR("ReadParcelable value is nullptr"); - return ERR_INVALID_VALUE; - } - int index = Update(*uri, *predicates, *value); - if (!reply.WriteInt32(index)) { - LOG_ERROR("fail to WriteInt32 index"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdDelete(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr predicates( - data.ReadParcelable()); - if (predicates == nullptr) { - LOG_ERROR("ReadParcelable predicates is nullptr"); - return ERR_INVALID_VALUE; - } - int index = Delete(*uri, *predicates); - if (!reply.WriteInt32(index)) { - LOG_ERROR("fail to WriteInt32 index"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdQuery(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::shared_ptr predicates( - data.ReadParcelable()); - if (predicates == nullptr) { - LOG_ERROR("ReadParcelable predicates is nullptr"); - return ERR_INVALID_VALUE; - } - std::vector columns; - if (!data.ReadStringVector(&columns)) { - LOG_ERROR("fail to ReadStringVector columns"); - return ERR_INVALID_VALUE; - } - auto resultSet = Query(*uri, *predicates, columns); - if (resultSet == nullptr) { - LOG_ERROR("fail to WriteParcelable resultSet"); - return ERR_INVALID_VALUE; - } - auto result = ISharedResultSet::WriteToParcel(std::move(resultSet), reply); - if (result == nullptr) { - LOG_ERROR("!resultSet->Marshalling(reply)"); - return ERR_INVALID_VALUE; - } - LOG_INFO("DataShareStub::CmdQueryInner end"); - return NO_ERROR; -} - -ErrCode DataShareStub::CmdGetType(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - std::string type = GetType(*uri); - if (!reply.WriteString(type)) { - LOG_ERROR("fail to WriteString type"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdBatchInsert(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - int count = 0; - if (!data.ReadInt32(count)) { - LOG_ERROR("fail to ReadInt32 index"); - return ERR_INVALID_VALUE; - } - - std::vector values; - for (int i = 0; i < count; i++) { - std::unique_ptr value(DataShareValuesBucket::Unmarshalling(data)); - if (value == nullptr) { - LOG_ERROR("DataShareStub value is nullptr, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - values.emplace_back(*value); - } - - int ret = BatchInsert(*uri, values); - if (!reply.WriteInt32(ret)) { - LOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - - -ErrCode DataShareStub::CmdRegisterObserver(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - auto obServer = iface_cast(data.ReadRemoteObject()); - if (obServer == nullptr) { - LOG_ERROR("DataShareStub obServer is nullptr"); - return ERR_INVALID_VALUE; - } - - bool ret = RegisterObserver(*uri, obServer); - if (!reply.WriteInt32(ret)) { - LOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - auto obServer = iface_cast(data.ReadRemoteObject()); - if (obServer == nullptr) { - LOG_ERROR("DataShareStub obServer is nullptr"); - return ERR_INVALID_VALUE; - } - - bool ret = UnregisterObserver(*uri, obServer); - if (!reply.WriteInt32(ret)) { - LOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdNotifyChange(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - bool ret = NotifyChange(*uri); - if (!reply.WriteInt32(ret)) { - LOG_ERROR("fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdNormalizeUri(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - Uri ret(""); - ret = NormalizeUri(*uri); - if (!reply.WriteParcelable(&ret)) { - LOG_ERROR("fail to WriteParcelable type"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply) -{ - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } - - Uri ret(""); - ret = DenormalizeUri(*uri); - if (!reply.WriteParcelable(&ret)) { - LOG_ERROR("fail to WriteParcelable type"); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - -ErrCode DataShareStub::CmdExecuteBatch(MessageParcel &data, MessageParcel &reply) -{ - LOG_INFO("DataShareStub::CmdExecuteBatchInner start"); - int count = 0; - if (!data.ReadInt32(count)) { - LOG_ERROR("DataShareStub::CmdExecuteBatchInner fail to ReadInt32 count"); - return ERR_INVALID_VALUE; - } - LOG_INFO("DataShareStub::CmdExecuteBatchInner count:%{public}d", count); - std::vector> operations; - for (int i = 0; i < count; i++) { - DataShareOperation *operation = data.ReadParcelable(); - if (operation == nullptr) { - LOG_ERROR("DataShareStub::CmdExecuteBatchInner operation is nullptr, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - std::shared_ptr dataShareOperation(operation); - operations.push_back(dataShareOperation); - } - - std::vector> results = ExecuteBatch(operations); - int total = (int)(results.size()); - if (!reply.WriteInt32(total)) { - LOG_ERROR("DataShareStub::CmdExecuteBatchInner fail to WriteInt32 ret"); - return ERR_INVALID_VALUE; - } - LOG_INFO("DataShareStub::CmdExecuteBatchInner total:%{public}d", total); - for (int i = 0; i < total; i++) { - if (results[i] == nullptr) { - LOG_ERROR("DataShareStub::CmdExecuteBatchInner results[i] is nullptr, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - if (!reply.WriteParcelable(results[i].get())) { - LOG_ERROR( - "DataShareStub::CmdExecuteBatchInner fail to WriteParcelable operation, index = %{public}d", i); - return ERR_INVALID_VALUE; - } - } - LOG_INFO("DataShareStub::CmdExecuteBatchInner end"); - return NO_ERROR; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp b/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp deleted file mode 100644 index acac4e7cb..000000000 --- a/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp +++ /dev/null @@ -1,382 +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 "datashare_stub_impl.h" - -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -constexpr int DEFAULT_NUMBER = -1; -std::shared_ptr DataShareStubImpl::GetOwner() -{ - return extension_; -} - -std::vector DataShareStubImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - LOG_INFO("begin."); - std::vector ret; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->GetFileTypes(uri, mimeTypeFilter); - }; - std::function getRetFunc = [=, &ret, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(ret); - return (ret.size() != 0); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return ret; -} - -int DataShareStubImpl::OpenFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - int ret = -1; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->OpenFile(uri, mode); - }; - std::function getRetFunc = [=, &ret, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(ret); - return (ret != DEFAULT_NUMBER); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return ret; -} - -int DataShareStubImpl::OpenRawFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - int ret = -1; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->OpenRawFile(uri, mode); - }; - uvQueue_->SyncCall(syncTaskFunc); - LOG_INFO("end successfully."); - return ret; -} - -int DataShareStubImpl::Insert(const Uri &uri, const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->Insert(uri, value); - }; - std::function getRetFunc = [=, &ret, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(ret); - return (ret != DEFAULT_NUMBER); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return ret; -} - -int DataShareStubImpl::Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->Update(uri, predicates, value); - }; - std::function getRetFunc = [=, &ret, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(ret); - return (ret != DEFAULT_NUMBER); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return ret; -} - -int DataShareStubImpl::Delete(const Uri &uri, const DataSharePredicates &predicates) -{ - LOG_INFO("begin."); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->Delete(uri, predicates); - }; - std::function getRetFunc = [=, &ret, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(ret); - return (ret != DEFAULT_NUMBER); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return ret; -} - -std::shared_ptr DataShareStubImpl::Query(const Uri &uri, - const DataSharePredicates &predicates, std::vector &columns) -{ - LOG_INFO("begin."); - std::shared_ptr resultSet = nullptr; - std::function syncTaskFunc = [=, &columns, &resultSet, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - resultSet = extension->Query(uri, predicates, columns); - }; - std::function getRetFunc = [=, &resultSet, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(resultSet); - return (resultSet != nullptr); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return resultSet; -} - -std::string DataShareStubImpl::GetType(const Uri &uri) -{ - LOG_INFO("begin."); - std::string ret = ""; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->GetType(uri); - }; - std::function getRetFunc = [=, &ret, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(ret); - return (ret != ""); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return ret; -} - -int DataShareStubImpl::BatchInsert(const Uri &uri, const std::vector &values) -{ - LOG_INFO("begin."); - int ret = 0; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->BatchInsert(uri, values); - }; - std::function getRetFunc = [=, &ret, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - extension->GetResult(ret); - return (ret != DEFAULT_NUMBER); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return ret; -} - -bool DataShareStubImpl::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - bool ret = false; - std::function syncTaskFunc = [=, &dataObserver, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->RegisterObserver(uri, dataObserver); - }; - uvQueue_->SyncCall(syncTaskFunc); - LOG_INFO("end successfully."); - return ret; -} - -bool DataShareStubImpl::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - bool ret = false; - std::function syncTaskFunc = [=, &dataObserver, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->UnregisterObserver(uri, dataObserver); - }; - uvQueue_->SyncCall(syncTaskFunc); - LOG_INFO("end successfully."); - return ret; -} - -bool DataShareStubImpl::NotifyChange(const Uri &uri) -{ - LOG_INFO("begin."); - bool ret = false; - std::function syncTaskFunc = [=, &ret, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - ret = extension->NotifyChange(uri); - }; - uvQueue_->SyncCall(syncTaskFunc); - LOG_INFO("end successfully."); - return ret; -} - -Uri DataShareStubImpl::NormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - Uri urivalue(""); - std::function syncTaskFunc = [=, &urivalue, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - urivalue = extension->NormalizeUri(uri); - }; - std::function getRetFunc = [=, &urivalue, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - std::string ret; - extension->GetResult(ret); - Uri tmp(ret); - urivalue = tmp; - return (urivalue.ToString() != ""); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return urivalue; -} - -Uri DataShareStubImpl::DenormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - Uri urivalue(""); - std::function syncTaskFunc = [=, &urivalue, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - urivalue = extension->DenormalizeUri(uri); - }; - std::function getRetFunc = [=, &urivalue, client = sptr(this)]() -> bool { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return false; - } - std::string ret; - extension->GetResult(ret); - Uri tmp(ret); - urivalue = tmp; - return (urivalue.ToString() != ""); - }; - uvQueue_->SyncCall(syncTaskFunc, getRetFunc); - LOG_INFO("end successfully."); - return urivalue; -} - -std::vector> DataShareStubImpl::ExecuteBatch( - const std::vector> &operations) -{ - LOG_INFO("begin."); - std::vector> results; - std::function syncTaskFunc = [=, &results, client = sptr(this)]() { - auto extension = client->GetOwner(); - if (extension == nullptr) { - LOG_ERROR("%{public}s end failed.", __func__); - return; - } - results = extension->ExecuteBatch(operations); - }; - uvQueue_->SyncCall(syncTaskFunc); - LOG_INFO("end successfully."); - return results; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/frameworks/native/provider/src/datashare_uv_queue.cpp b/data_share/frameworks/native/provider/src/datashare_uv_queue.cpp deleted file mode 100644 index b9b39cdca..000000000 --- a/data_share/frameworks/native/provider/src/datashare_uv_queue.cpp +++ /dev/null @@ -1,116 +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 "datashare_uv_queue.h" -#include -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -constexpr int WAIT_TIME = 3; -constexpr int SLEEP_TIME = 100; -constexpr int TRY_TIMES = 20; -DataShareUvQueue::DataShareUvQueue(napi_env env) - : env_(env) -{ - napi_get_uv_event_loop(env, &loop_); -} - -void DataShareUvQueue::SyncCall(NapiVoidFunc func, NapiBoolFunc retFunc) -{ - LOG_INFO("begin."); - uv_work_t* work = new (std::nothrow) uv_work_t; - if (work == nullptr) { - return; - } - work->data = new UvEntry {env_, std::move(func), false, false, {}, {}, std::move(retFunc)}; - auto status = uv_queue_work( - loop_, work, [](uv_work_t* work) {}, - [](uv_work_t* work, int uvstatus) { - if (work == nullptr || work->data == nullptr) { - LOG_ERROR("%{public}s invalid work or work->data.", __func__); - return; - } - auto *entry = static_cast(work->data); - std::unique_lock lock(entry->mutex); - if (entry->func) { - entry->func(); - } - entry->done = true; - if (entry->purge) { - DataShareUvQueue::Purge(work); - } else { - entry->condition.notify_all(); - } - }); - if (status != napi_ok) { - LOG_ERROR("%{public}s queue work failed", __func__); - DataShareUvQueue::Purge(work); - return; - } - - bool noNeedPurge = false; - auto *uvEntry = static_cast(work->data); - { - std::unique_lock lock(uvEntry->mutex); - if (uvEntry->condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [uvEntry] { return uvEntry->done; })) { - LOG_INFO("Wait uv_queue_work timeout."); - } - CheckFuncAndExec(uvEntry->retFunc); - if (!uvEntry->done && !uv_cancel((uv_req_t*)&work)) { - LOG_ERROR("%{public}s uv_cancel failed.", __func__); - uvEntry->purge = true; - noNeedPurge = true; - } - } - - if (!noNeedPurge) { - DataShareUvQueue::Purge(work); - } - LOG_INFO("end."); -} - -void DataShareUvQueue::Purge(uv_work_t* work) -{ - LOG_INFO("begin."); - if (work == nullptr || work->data == nullptr) { - LOG_ERROR("%{public}s invalid work or work->data.", __func__); - return; - } - - auto *entry = static_cast(work->data); - std::unique_lock lock(entry->mutex); - - delete entry; - entry = nullptr; - - delete work; - work = nullptr; - LOG_INFO("end."); -} - -void DataShareUvQueue::CheckFuncAndExec(NapiBoolFunc retFunc) -{ - if (retFunc) { - int tryTimes = TRY_TIMES; - while (retFunc() != true && tryTimes > 0) { - LOG_DEBUG("tryTimes : %{public}d.", tryTimes); - std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); - tryTimes--; - } - } -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp b/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp deleted file mode 100644 index a5cc614a4..000000000 --- a/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp +++ /dev/null @@ -1,831 +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 "js_datashare_ext_ability.h" - -#include "ability_info.h" -#include "accesstoken_kit.h" -#include "dataobs_mgr_client.h" -#include "datashare_stub_impl.h" -#include "datashare_log.h" -#include "ipc_skeleton.h" -#include "js_datashare_ext_ability_context.h" -#include "js_runtime.h" -#include "js_runtime_utils.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#include "napi_common_util.h" -#include "napi_common_want.h" -#include "napi_remote_object.h" - -#include "napi_datashare_values_bucket.h" -#include "datashare_predicates_proxy.h" - -namespace OHOS { -namespace DataShare { -using namespace AbilityRuntime; -namespace { -constexpr size_t ARGC_ONE = 1; -constexpr size_t ARGC_TWO = 2; -constexpr size_t ARGC_THREE = 3; -constexpr int INVALID_VALUE = -1; -const std::string ASYNC_CALLBACK_NAME = "AsyncCallback"; -} - -bool MakeNapiColumn(napi_env env, napi_value &napiColumns, const std::vector &columns); - -using namespace OHOS::AppExecFwk; -using OHOS::Security::AccessToken::AccessTokenKit; -using DataObsMgrClient = OHOS::AAFwk::DataObsMgrClient; - -JsDataShareExtAbility* JsDataShareExtAbility::Create(const std::unique_ptr& runtime) -{ - return new JsDataShareExtAbility(static_cast(*runtime)); -} - -JsDataShareExtAbility::JsDataShareExtAbility(JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} - -JsDataShareExtAbility::~JsDataShareExtAbility() {} - -void JsDataShareExtAbility::Init(const std::shared_ptr &record, - const std::shared_ptr &application, std::shared_ptr &handler, - const sptr &token) -{ - DataShareExtAbility::Init(record, application, handler, token); - std::string srcPath = ""; - GetSrcPath(srcPath); - if (srcPath.empty()) { - LOG_ERROR("Failed to get srcPath"); - return; - } - - std::string moduleName(Extension::abilityInfo_->moduleName); - moduleName.append("::").append(abilityInfo_->name); - LOG_INFO("module:%{public}s, srcPath:%{public}s.", moduleName.c_str(), srcPath.c_str()); - HandleScope handleScope(jsRuntime_); - auto& engine = jsRuntime_.GetNativeEngine(); - - jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath); - if (jsObj_ == nullptr) { - LOG_ERROR("Failed to get jsObj_"); - return; - } - LOG_INFO("JsDataShareExtAbility::Init ConvertNativeValueTo."); - NativeObject* obj = ConvertNativeValueTo(jsObj_->Get()); - if (obj == nullptr) { - LOG_ERROR("Failed to get JsDataShareExtAbility object"); - return; - } - - auto context = GetContext(); - if (context == nullptr) { - LOG_ERROR("Failed to get context"); - return; - } - LOG_INFO("JsDataShareExtAbility::Init CreateJsDataShareExtAbilityContext."); - NativeValue* contextObj = CreateJsDataShareExtAbilityContext(engine, context); - auto contextRef = jsRuntime_.LoadSystemModule("application.DataShareExtensionAbilityContext", - &contextObj, ARGC_ONE); - contextObj = contextRef->Get(); - LOG_INFO("JsDataShareExtAbility::Init Bind."); - context->Bind(jsRuntime_, contextRef.release()); - LOG_INFO("JsDataShareExtAbility::SetProperty."); - obj->SetProperty("context", contextObj); - - auto nativeObj = ConvertNativeValueTo(contextObj); - if (nativeObj == nullptr) { - LOG_ERROR("Failed to get datashare extension ability native object"); - return; - } - - LOG_INFO("Set datashare extension ability context pointer is nullptr: %{public}d", context.get() == nullptr); - - nativeObj->SetNativePointer(new std::weak_ptr(context), - [](NativeEngine*, void* data, void*) { - LOG_INFO("Finalizer for weak_ptr datashare extension ability context is called"); - delete static_cast*>(data); - }, nullptr); - - LOG_INFO("JsDataShareExtAbility::Init end."); -} - -void JsDataShareExtAbility::OnStart(const AAFwk::Want &want) -{ - LOG_INFO("begin."); - Extension::OnStart(want); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); - NativeValue* nativeWant = reinterpret_cast(napiWant); - NativeValue* argv[] = {nativeWant}; - CallObjectMethod("onCreate", argv, ARGC_ONE); - LOG_INFO("end."); -} - -sptr JsDataShareExtAbility::OnConnect(const AAFwk::Want &want) -{ - LOG_INFO("begin."); - Extension::OnConnect(want); - sptr remoteObject = new (std::nothrow) DataShareStubImpl( - std::static_pointer_cast(shared_from_this()), - reinterpret_cast(&jsRuntime_.GetNativeEngine())); - if (remoteObject == nullptr) { - LOG_ERROR("%{public}s No memory allocated for DataShareStubImpl", __func__); - return nullptr; - } - LOG_INFO("end."); - return remoteObject->AsObject(); -} - -void JsDataShareExtAbility::CheckAndSetAsyncResult(NativeEngine* engine) -{ - auto result = GetAsyncResult(); - auto type = result->TypeOf(); - LOG_DEBUG("type : %{public}d", type); - if (type == NATIVE_NUMBER) { - int32_t value = OHOS::AppExecFwk::UnwrapInt32FromJS(reinterpret_cast(engine), - reinterpret_cast(result)); - SetResult(value); - } else if (type == NATIVE_STRING) { - std::string value = OHOS::AppExecFwk::UnwrapStringFromJS(reinterpret_cast(engine), - reinterpret_cast(result)); - SetResult(value); - } else if (type == NATIVE_OBJECT) { - ResultSetBridge::Creator *proxy = nullptr; - napi_unwrap(reinterpret_cast(engine), reinterpret_cast(result), - reinterpret_cast(&proxy)); - if (proxy == nullptr) { - LOG_DEBUG("proxy == nullptr. STRARR."); - std::vector value; - OHOS::AppExecFwk::UnwrapArrayStringFromJS(reinterpret_cast(engine), - reinterpret_cast(result), value); - SetResult(value); - } else { - std::shared_ptr value = proxy->Create(); - std::shared_ptr resultSet = std::make_shared(value); - SetResult(resultSet); - } - } else { - callbackResultNumber_ = -1; - callbackResultString_ = ""; - callbackResultStringArr_ = {}; - callbackResultObject_ = nullptr; - } -} - -NativeValue* JsDataShareExtAbility::AsyncCallback(NativeEngine* engine, NativeCallbackInfo* info) -{ - LOG_INFO("engine == nullptr : %{public}d, info == nullptr : %{public}d.", engine == nullptr, info == nullptr); - if (engine == nullptr || info == nullptr) { - LOG_ERROR("%{public}s invalid param.", __func__); - return nullptr; - } - if (info->argc < ARGC_TWO || info->argv[0] == nullptr || info->argv[1] == nullptr) { - LOG_ERROR("%{public}s invalid args.", __func__); - return engine->CreateUndefined(); - } - - int32_t value = -1; - if ((info->argv[0])->TypeOf() == NATIVE_NUMBER) { - value = OHOS::AppExecFwk::UnwrapInt32FromJS(reinterpret_cast(engine), - reinterpret_cast(info->argv[0])); - LOG_INFO("%{public}s value_number : %{public}d.", __func__, value); - } - - if (info->functionInfo == nullptr || info->functionInfo->data == nullptr) { - LOG_ERROR("%{public}s invalid object.", __func__); - return engine->CreateUndefined(); - } - - JsDataShareExtAbility* instance = static_cast(info->functionInfo->data); - if (instance != nullptr) { - instance->SetBlockWaiting(true); - instance->SetAsyncResult(info->argv[1]); - instance->CheckAndSetAsyncResult(engine); - } - - LOG_INFO("%{public}s end.", __func__); - return engine->CreateUndefined(); -} - -NativeValue* JsDataShareExtAbility::CallObjectMethod(const char* name, NativeValue* const* argv, size_t argc, - bool isAsync) -{ - LOG_INFO("JsDataShareExtAbility::CallObjectMethod(%{public}s), begin", name); - - if (!jsObj_) { - LOG_WARN("Not found DataShareExtAbility.js"); - return nullptr; - } - - HandleScope handleScope(jsRuntime_); - auto& nativeEngine = jsRuntime_.GetNativeEngine(); - - NativeValue* value = jsObj_->Get(); - NativeObject* obj = ConvertNativeValueTo(value); - if (obj == nullptr) { - LOG_ERROR("Failed to get DataShareExtAbility object"); - return nullptr; - } - - NativeValue* method = obj->GetProperty(name); - if (method == nullptr) { - LOG_ERROR("Failed to get '%{public}s' from DataShareExtAbility object", name); - return nullptr; - } - - size_t count = argc + 1; - NativeValue **args = new NativeValue *[count]; - for (size_t i = 0; i < argc; i++) { - args[i] = argv[i]; - } - - if (isAsync) { - callbackResultNumber_ = -1; - callbackResultString_ = ""; - callbackResultStringArr_ = {}; - callbackResultObject_ = nullptr; - args[argc] = nativeEngine.CreateFunction(ASYNC_CALLBACK_NAME.c_str(), - ASYNC_CALLBACK_NAME.length(), JsDataShareExtAbility::AsyncCallback, this); - LOG_INFO("AsyncType::ASYNC_COMMON."); - } else { - args[argc] = nullptr; - } - - SetBlockWaiting(false); - LOG_INFO("%{public}s(%{public}s) end", __func__, name); - return handleScope.Escape(nativeEngine.CallFunction(value, method, args, count)); -} - -void JsDataShareExtAbility::GetSrcPath(std::string &srcPath) -{ - if (!Extension::abilityInfo_->isStageBasedModel) { - /* temporary compatibility api8 + config.json */ - srcPath.append(Extension::abilityInfo_->package); - srcPath.append("/assets/js/"); - if (!Extension::abilityInfo_->srcPath.empty()) { - srcPath.append(Extension::abilityInfo_->srcPath); - } - srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc"); - return; - } - - if (!Extension::abilityInfo_->srcEntrance.empty()) { - srcPath.append(Extension::abilityInfo_->moduleName + "/"); - srcPath.append(Extension::abilityInfo_->srcEntrance); - srcPath.erase(srcPath.rfind('.')); - srcPath.append(".abc"); - } -} - -std::vector JsDataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - LOG_INFO("begin."); - auto ret = DataShareExtAbility::GetFileTypes(uri, mimeTypeFilter); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - napi_value napiMimeTypeFilter = nullptr; - status = napi_create_string_utf8(env, mimeTypeFilter.c_str(), NAPI_AUTO_LENGTH, &napiMimeTypeFilter); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeMimeTypeFilter = reinterpret_cast(napiMimeTypeFilter); - NativeValue* argv[] = {nativeUri, nativeMimeTypeFilter}; - NativeValue* nativeResult = CallObjectMethod("getFileTypes", argv, ARGC_TWO); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call getFileTypes with return null.", __func__); - return ret; - } - - if (!OHOS::AppExecFwk::UnwrapArrayStringFromJS(env, reinterpret_cast(nativeResult), ret)) { - LOG_ERROR("%{public}s call UnwrapArrayStringFromJS failed", __func__); - return ret; - } - - LOG_INFO("end."); - return ret; -} - -int JsDataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - auto ret = DataShareExtAbility::OpenFile(uri, mode); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - napi_value napiMode = nullptr; - status = napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeMode = reinterpret_cast(napiMode); - NativeValue* argv[] = {nativeUri, nativeMode}; - NativeValue* nativeResult = CallObjectMethod("openFile", argv, ARGC_TWO); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call openFile with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - LOG_INFO("end."); - return ret; -} - -int JsDataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode) -{ - LOG_INFO("begin."); - auto ret = DataShareExtAbility::OpenRawFile(uri, mode); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - napi_value napiMode = nullptr; - status = napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeMode = reinterpret_cast(napiMode); - NativeValue* argv[] = {nativeUri, nativeMode}; - NativeValue* nativeResult = CallObjectMethod("openRawFile", argv, ARGC_TWO, false); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call openRawFile with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - LOG_INFO("end."); - return ret; -} - -int JsDataShareExtAbility::Insert(const Uri &uri, const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - LOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Insert(uri, value); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - napi_value napiValue = DataShareValueBucketNewInstance(env, const_cast(value)); - if (napiValue == nullptr) { - LOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeValue = reinterpret_cast(napiValue); - NativeValue* argv[] = {nativeUri, nativeValue}; - NativeValue* nativeResult = CallObjectMethod("insert", argv, ARGC_TWO); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call insert with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - LOG_INFO("end."); - return ret; -} - -int JsDataShareExtAbility::Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) -{ - LOG_INFO("begin."); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - LOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Update(uri, predicates, value); - - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - - napi_value napiPredicates = MakePredicates(env, predicates); - if (napiPredicates == nullptr) { - LOG_DEBUG("%{public}s failed to make new instance of dataSharePredicates.", __func__); - return ret; - } - - napi_value napiValue = DataShareValueBucketNewInstance(env, const_cast(value)); - if (napiValue == nullptr) { - LOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativePredicates = reinterpret_cast(napiPredicates); - NativeValue* nativeValue = reinterpret_cast(napiValue); - NativeValue* argv[] = {nativeUri, nativePredicates, nativeValue}; - NativeValue* nativeResult = CallObjectMethod("update", argv, ARGC_THREE); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call update with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - LOG_INFO("end."); - return ret; -} - -int JsDataShareExtAbility::Delete(const Uri &uri, const DataSharePredicates &predicates) -{ - LOG_INFO("begin."); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - LOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Delete(uri, predicates); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - - napi_value napiPredicates = MakePredicates(env, predicates); - if (napiPredicates == nullptr) { - LOG_DEBUG("%{public}s failed to make new instance of dataSharePredicates.", __func__); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativePredicates = reinterpret_cast(napiPredicates); - NativeValue* argv[] = {nativeUri, nativePredicates}; - NativeValue* nativeResult = CallObjectMethod("delete", argv, ARGC_TWO); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call delete with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - LOG_INFO("end."); - return ret; -} - -std::shared_ptr JsDataShareExtAbility::Query(const Uri &uri, - const DataSharePredicates &predicates, std::vector &columns) -{ - LOG_INFO("begin."); - std::shared_ptr ret; - if (!CheckCallingPermission(abilityInfo_->readPermission)) { - LOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::Query(uri, predicates, columns); - - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - - napi_value napiPredicates = MakePredicates(env, predicates); - if (napiPredicates == nullptr) { - LOG_DEBUG("%{public}s failed to make new instance of dataSharePredicates.", __func__); - return ret; - } - - napi_value napiColumns = nullptr; - if (!MakeNapiColumn(env, napiColumns, columns)) { - LOG_ERROR("MakeNapiColumn failed"); - return ret; - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativePredicates = reinterpret_cast(napiPredicates); - NativeValue* nativeColumns = reinterpret_cast(napiColumns); - NativeValue* argv[] = {nativeUri, nativePredicates, nativeColumns}; - NativeValue* nativeResult = CallObjectMethod("query", argv, ARGC_THREE); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call query with return null.", __func__); - return ret; - } - - ResultSetBridge::Creator *proxy = nullptr; - napi_unwrap(env, reinterpret_cast(nativeResult), reinterpret_cast(&proxy)); - if (proxy == nullptr) { - LOG_ERROR("unwrap ResultSetBridge::Creator proxy is null."); - return nullptr; - } - - std::shared_ptr bridge = proxy->Create(); - LOG_INFO("ret == nullptr : %{public}d.", bridge == nullptr); - std::shared_ptr resultSet = std::make_shared(bridge); - return resultSet; -} - -std::string JsDataShareExtAbility::GetType(const Uri &uri) -{ - LOG_INFO("begin."); - auto ret = DataShareExtAbility::GetType(uri); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* argv[] = {nativeUri}; - NativeValue* nativeResult = CallObjectMethod("getType", argv, ARGC_ONE); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call getType with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult)); - LOG_INFO("end."); - return ret; -} - -int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector &values) -{ - LOG_INFO("begin."); - int ret = INVALID_VALUE; - if (!CheckCallingPermission(abilityInfo_->writePermission)) { - LOG_ERROR("%{public}s Check calling permission failed.", __func__); - return ret; - } - - ret = DataShareExtAbility::BatchInsert(uri, values); - - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - - napi_value napiValues = nullptr; - status = napi_create_array(env, &napiValues); - if (status != napi_ok) { - LOG_ERROR("napi_create_array status : %{public}d", status); - return ret; - } - bool isArray = false; - if (napi_is_array(env, napiValues, &isArray) != napi_ok || !isArray) { - LOG_ERROR("JsDataShareExtAbility create array failed"); - return ret; - } - int32_t index = 0; - for (const auto &value : values) { - napi_value result = DataShareValueBucketNewInstance(env, const_cast(value)); - if (result == nullptr) { - LOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } - napi_set_element(env, napiValues, index++, result); - } - - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* nativeValues = reinterpret_cast(napiValues); - NativeValue* argv[] = {nativeUri, nativeValues}; - NativeValue* nativeResult = CallObjectMethod("batchInsert", argv, ARGC_TWO); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call batchInsert with return null.", __func__); - return ret; - } - - ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast(nativeResult)); - LOG_INFO("end."); - return ret; -} - -bool JsDataShareExtAbility::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - DataShareExtAbility::RegisterObserver(uri, dataObserver); - auto obsMgrClient = DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - LOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); - return false; - } - - ErrCode ret = obsMgrClient->RegisterObserver(uri, dataObserver); - if (ret != ERR_OK) { - LOG_ERROR("%{public}s obsMgrClient->RegisterObserver error return %{public}d", __func__, ret); - return false; - } - LOG_INFO("end."); - return true; -} - -bool JsDataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("begin."); - DataShareExtAbility::UnregisterObserver(uri, dataObserver); - auto obsMgrClient = DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - LOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); - return false; - } - - ErrCode ret = obsMgrClient->UnregisterObserver(uri, dataObserver); - if (ret != ERR_OK) { - LOG_ERROR("%{public}s obsMgrClient->UnregisterObserver error return %{public}d", __func__, ret); - return false; - } - LOG_INFO("end."); - return true; -} - -bool JsDataShareExtAbility::NotifyChange(const Uri &uri) -{ - LOG_INFO("begin."); - DataShareExtAbility::NotifyChange(uri); - auto obsMgrClient = DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - LOG_ERROR("%{public}s obsMgrClient is nullptr", __func__); - return false; - } - - ErrCode ret = obsMgrClient->NotifyChange(uri); - if (ret != ERR_OK) { - LOG_ERROR("%{public}s obsMgrClient->NotifyChange error return %{public}d", __func__, ret); - return false; - } - LOG_INFO("end."); - return true; -} - -Uri JsDataShareExtAbility::NormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - auto ret = DataShareExtAbility::NormalizeUri(uri); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* argv[] = {nativeUri}; - NativeValue* nativeResult = CallObjectMethod("normalizeUri", argv, ARGC_ONE); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call normalizeUri with return null.", __func__); - return ret; - } - - ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult))); - LOG_INFO("end."); - return ret; -} - -Uri JsDataShareExtAbility::DenormalizeUri(const Uri &uri) -{ - LOG_INFO("begin."); - auto ret = DataShareExtAbility::DenormalizeUri(uri); - HandleScope handleScope(jsRuntime_); - napi_env env = reinterpret_cast(&jsRuntime_.GetNativeEngine()); - - napi_value napiUri = nullptr; - napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); - if (status != napi_ok) { - LOG_ERROR("napi_create_string_utf8 status : %{public}d", status); - return ret; - } - NativeValue* nativeUri = reinterpret_cast(napiUri); - NativeValue* argv[] = {nativeUri}; - NativeValue* nativeResult = CallObjectMethod("denormalizeUri", argv, ARGC_ONE); - if (nativeResult == nullptr) { - LOG_ERROR("%{public}s call denormalizeUri with return null.", __func__); - return ret; - } - - ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast(nativeResult))); - LOG_INFO("end."); - return ret; -} - -std::vector> JsDataShareExtAbility::ExecuteBatch( - const std::vector> &operations) -{ - LOG_INFO("begin."); - auto ret = DataShareExtAbility::ExecuteBatch(operations); - LOG_INFO("end."); - return ret; -} - -bool JsDataShareExtAbility::CheckCallingPermission(const std::string &permission) -{ - LOG_INFO("begin, permission:%{public}s", permission.c_str()); - if (!permission.empty() && AccessTokenKit::VerifyAccessToken(IPCSkeleton::GetCallingTokenID(), permission) - != AppExecFwk::Constants::PERMISSION_GRANTED) { - LOG_ERROR("%{public}s permission not granted.", __func__); - return false; - } - LOG_INFO("end."); - return true; -} - -napi_value JsDataShareExtAbility::MakePredicates(napi_env env, const DataSharePredicates &predicates) -{ - LOG_INFO("begin."); - std::shared_ptr predicatesPtr = std::make_shared(predicates); - if (predicatesPtr == nullptr) { - LOG_ERROR("%{public}s No memory allocated for predicates", __func__); - return nullptr; - } - napi_value napiPredicates = GetNapiObject(env, predicatesPtr); - if (napiPredicates == nullptr) { - LOG_ERROR("%{public}s failed to make new instance of DataSharePredicates.", __func__); - } - LOG_INFO("end."); - return napiPredicates; -} - -bool MakeNapiColumn(napi_env env, napi_value &napiColumns, const std::vector &columns) -{ - napi_status status = napi_create_array(env, &napiColumns); - if (status != napi_ok) { - LOG_ERROR("napi_create_array status : %{public}d", status); - return false; - } - - bool isArray = false; - if (napi_is_array(env, napiColumns, &isArray) != napi_ok || !isArray) { - LOG_ERROR("JsDataShareExtAbility create array failed"); - return false; - } - - int32_t index = 0; - for (const auto &column : columns) { - napi_value result = nullptr; - napi_create_string_utf8(env, column.c_str(), column.length(), &result); - napi_set_element(env, napiColumns, index++, result); - } - - return true; -} -} // namespace DataShare -} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp b/data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp deleted file mode 100644 index fa1a9648c..000000000 --- a/data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp +++ /dev/null @@ -1,62 +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 "js_datashare_ext_ability_context.h" - -#include - -#include "datashare_log.h" -#include "js_extension_context.h" -#include "js_runtime.h" -#include "js_runtime_utils.h" -#include "napi/native_api.h" -#include "napi_common_want.h" -#include "napi_remote_object.h" -#include "napi_common_start_options.h" -#include "start_options.h" - -namespace OHOS { -namespace DataShare { -using namespace AbilityRuntime; -namespace { -class JsDataShareExtAbilityContext final { -public: - explicit JsDataShareExtAbilityContext(const std::shared_ptr& context) - : context_(context) {} - ~JsDataShareExtAbilityContext() = default; - - static void Finalizer(NativeEngine* engine, void* data, void* hint) - { - LOG_INFO("JsAbilityContext::Finalizer is called"); - std::unique_ptr(static_cast(data)); - } -private: - std::weak_ptr context_; -}; -} // namespace - -NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine, - std::shared_ptr context) -{ - LOG_INFO("CreateJsDataShareExtAbilityContext begin"); - NativeValue* objValue = CreateJsExtensionContext(engine, context); - NativeObject* object = ConvertNativeValueTo(objValue); - - std::unique_ptr jsContext = std::make_unique(context); - object->SetNativePointer(jsContext.release(), JsDataShareExtAbilityContext::Finalizer, nullptr); - return objValue; -} -} // namespace DataShare -} // namespace OHOS diff --git a/data_share/interfaces/inner_api/BUILD.gn b/data_share/interfaces/inner_api/BUILD.gn deleted file mode 100644 index 670cfa52f..000000000 --- a/data_share/interfaces/inner_api/BUILD.gn +++ /dev/null @@ -1,126 +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("//build/ohos.gni") -import("//foundation/distributeddatamgr/data_share/datashare.gni") -import("//foundation/distributeddatamgr/relational_store/relational_store.gni") - -config("ability_config") { - visibility = [ ":*" ] - include_dirs = [ - "common/include", - "consumer/include", - "provider/include", - "${ability_runtime_services_path}/common/include", - "${datashare_native_consumer_path}/include", - "${datashare_native_provider_path}/include", - "${ability_runtime_napi_path}/inner/napi_common", - "${relational_store_innerapi_path}/rdb/include", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/include", - ] - - cflags = [] - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } -} - -config("ability_public_config") { - visibility = [ ":*" ] - include_dirs = [ - "common/include", - "consumer/include", - "provider/include", - "${datashare_common_napi_path}/include", - "${datashare_common_native_path}/include", - "${datashare_native_consumer_path}/include", - "${datashare_native_provider_path}/include", - "//foundation/window/window_manager/interfaces/innerkits/wm", - ] -} - -ohos_shared_library("datashare_abilitykit") { - include_dirs = [] - - sources = [ - "${datashare_native_consumer_path}/src/datashare_connection.cpp", - "${datashare_native_consumer_path}/src/datashare_helper.cpp", - "${datashare_native_consumer_path}/src/datashare_proxy.cpp", - "${datashare_native_provider_path}/src/datashare_ext_ability.cpp", - "${datashare_native_provider_path}/src/datashare_ext_ability_context.cpp", - "${datashare_native_provider_path}/src/datashare_stub.cpp", - "${datashare_native_provider_path}/src/datashare_stub_impl.cpp", - "${datashare_native_provider_path}/src/datashare_uv_queue.cpp", - "${datashare_native_provider_path}/src/js_datashare_ext_ability.cpp", - "${datashare_native_provider_path}/src/js_datashare_ext_ability_context.cpp", - ] - configs = [ ":ability_config" ] - public_configs = [ ":ability_public_config" ] - - deps = [ - "${ability_runtime_inner_api_path}/dataobs_manager:dataobs_manager", - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "${ability_runtime_path}/frameworks/native/appkit:app_context", - "${datashare_innerapi_path}/common:datashare_common", - ] - - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "ability_runtime:ability_context_native", - "ability_runtime:ability_manager", - "ability_runtime:runtime", - "access_token:libaccesstoken_sdk", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "ipc:ipc_core", - "ipc_js:rpc", - "relational_store:native_dataability", - "relational_store:native_rdb", - ] - - public_deps = [ - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/arkui/napi:ace_napi", - ] - - subsystem_name = "distributeddatamgr" - part_name = "data_share" -} - -ohos_shared_library("datashare_ext_ability_module") { - include_dirs = [ "${datashare_native_provider_path}/include" ] - - sources = [ "${datashare_native_provider_path}/src/datashare_ext_ability_module_loader.cpp" ] - - configs = [ ":ability_config" ] - public_configs = [ ":ability_public_config" ] - - deps = [ - ":datashare_abilitykit", - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "//foundation/bundlemanager/bundle_framework/common:libappexecfwk_common", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:runtime", - "c_utils:utils", - "hiviewdfx_hilog_native:libhilog", - "relational_store:native_appdatafwk", - ] - - 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 deleted file mode 100644 index 222702ea6..000000000 --- a/data_share/interfaces/inner_api/common/BUILD.gn +++ /dev/null @@ -1,73 +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("//build/ohos.gni") -import("//foundation/distributeddatamgr/data_share/datashare.gni") - -config("ability_config") { - visibility = [ ":*" ] - - cflags = [] - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } -} - -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", - ] - - sources = [ - "${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_operation.cpp", - "${datashare_common_native_path}/src/datashare_operation_builder.cpp", - "${datashare_common_native_path}/src/datashare_predicates.cpp", - "${datashare_common_native_path}/src/datashare_predicates_object.cpp", - "${datashare_common_native_path}/src/datashare_result.cpp", - "${datashare_common_native_path}/src/datashare_result_set.cpp", - "${datashare_common_native_path}/src/datashare_value_object.cpp", - "${datashare_common_native_path}/src/datashare_values_bucket.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", - ] - - configs = [ ":ability_config" ] - - deps = [ - "//foundation/bundlemanager/bundle_framework/common:libappexecfwk_common", - ] - - external_deps = [ - "ability_base:zuri", - "bundle_framework:appexecfwk_base", - "c_utils:utils", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "napi:ace_napi", - "relational_store:native_appdatafwk", - ] - - subsystem_name = "distributeddatamgr" - part_name = "data_share" -} diff --git a/data_share/interfaces/inner_api/common/include/datashare_abs_predicates.h b/data_share/interfaces/inner_api/common/include/datashare_abs_predicates.h deleted file mode 100644 index 8a73a1a22..000000000 --- a/data_share/interfaces/inner_api/common/include/datashare_abs_predicates.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_ABSPREDICATES_H -#define DATASHARE_ABSPREDICATES_H - -#include -#include -#include -#include "datashare_predicates_def.h" - -namespace OHOS { -namespace DataShare { -class DataShareAbsPredicates { -public: - virtual ~DataShareAbsPredicates() {} - virtual DataShareAbsPredicates *EqualTo(const std::string &field, const DataSharePredicatesObject &value) = 0; - virtual DataShareAbsPredicates *NotEqualTo(const std::string &field, const DataSharePredicatesObject &value) = 0; - virtual DataShareAbsPredicates *GreaterThan(const std::string &field, const DataSharePredicatesObject &value) = 0; - virtual DataShareAbsPredicates *LessThan(const std::string &field, const DataSharePredicatesObject &value) = 0; - virtual DataShareAbsPredicates *GreaterThanOrEqualTo(const std::string &field, - const DataSharePredicatesObject &value) = 0; - virtual DataShareAbsPredicates *LessThanOrEqualTo(const std::string &field, - const DataSharePredicatesObject & value) = 0; - virtual DataShareAbsPredicates *In(const std::string &field, const DataSharePredicatesObject &value) = 0; - virtual DataShareAbsPredicates *NotIn(const std::string &field, const DataSharePredicatesObject &value) = 0; - virtual DataShareAbsPredicates *BeginWrap() = 0; - virtual DataShareAbsPredicates *EndWrap() = 0; - virtual DataShareAbsPredicates *Or() = 0; - virtual DataShareAbsPredicates *And() = 0; - virtual DataShareAbsPredicates *Contains(const std::string &field, const std::string &value) = 0; - virtual DataShareAbsPredicates *BeginsWith(const std::string &field, const std::string &value) = 0; - virtual DataShareAbsPredicates *EndsWith(const std::string &field, const std::string &value) = 0; - virtual DataShareAbsPredicates *IsNull(const std::string &field) = 0; - virtual DataShareAbsPredicates *IsNotNull(const std::string &field) = 0; - virtual DataShareAbsPredicates *Like(const std::string &field, const std::string &value) = 0; - virtual DataShareAbsPredicates *Glob(const std::string &field, const std::string &value) = 0; - virtual DataShareAbsPredicates *Between(const std::string &field, - const std::string &low, const std::string &high) = 0; - virtual DataShareAbsPredicates *NotBetween(const std::string &field, - const std::string &low, const std::string &high) = 0; - virtual DataShareAbsPredicates *OrderByAsc(const std::string &field) = 0; - virtual DataShareAbsPredicates *OrderByDesc(const std::string &field) = 0; - virtual DataShareAbsPredicates *Distinct() = 0; - virtual DataShareAbsPredicates *Limit(const int number, const int offset) = 0; - virtual DataShareAbsPredicates *GroupBy(const std::vector &fields) = 0; - virtual DataShareAbsPredicates *IndexedBy(const std::string &indexName) = 0; - virtual DataShareAbsPredicates *KeyPrefix(const std::string &prefix) = 0; - virtual DataShareAbsPredicates *InKeys(const std::vector &keys) = 0; - virtual const std::list& GetOperationList() const = 0; - virtual std::string GetWhereClause() const = 0; - virtual int SetWhereClause(const std::string &whereClause) = 0; - virtual std::vector GetWhereArgs() const = 0; - virtual int SetWhereArgs(const std::vector &whereArgs) = 0; - virtual std::string GetOrder() const = 0; - virtual int SetOrder(const std::string &order) = 0; - virtual SettingMode GetSettingMode() const = 0; -}; -} // namespace DataShare -} // namespace OHOS - -#endif \ No newline at end of file diff --git a/data_share/interfaces/inner_api/common/include/datashare_errno.h b/data_share/interfaces/inner_api/common/include/datashare_errno.h deleted file mode 100644 index a75cc37f1..000000000 --- a/data_share/interfaces/inner_api/common/include/datashare_errno.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_ERRNO_H -#define DATASHARE_ERRNO_H - -namespace OHOS { -namespace DataShare { -constexpr int E_OK = 0; -constexpr int E_BASE = 1000; -constexpr int E_ERROR = (E_BASE + 1); -constexpr int E_CANNOT_UPDATE_READONLY = (E_BASE + 2); -constexpr int E_REMOVE_FILE = (E_BASE + 3); -constexpr int E_EMPTY_FILE_NAME = (E_BASE + 4); -constexpr int E_EMPTY_TABLE_NAME = (E_BASE + 5); -constexpr int E_EMPTY_VALUES_BUCKET = (E_BASE + 6); -constexpr int E_INVALID_STATEMENT = (E_BASE + 7); -constexpr int E_INVALID_COLUMN_INDEX = (E_BASE + 8); -constexpr int E_INVALID_COLUMN_TYPE = (E_BASE + 9); -constexpr int E_INVALID_COLUMN_NAME = (E_BASE + 10); -constexpr int E_QUERY_IN_EXECUTE = (E_BASE + 11); -constexpr int E_TRANSACTION_IN_EXECUTE = (E_BASE + 12); -constexpr int E_EXECUTE_IN_STEP_QUERY = (E_BASE + 13); -constexpr int E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14); -constexpr int E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15); -constexpr int E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16); -constexpr int E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17); -constexpr int E_NO_ROW_IN_QUERY = (E_BASE + 18); -constexpr int E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19); -constexpr int E_INVALID_OBJECT_TYPE = (E_BASE + 20); -constexpr int E_INVALID_CONFLICT_FLAG = (E_BASE + 21); -constexpr int E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22); -constexpr int E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23); -constexpr int E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24); -constexpr int E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25); -constexpr int E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26); -constexpr int E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27); -constexpr int E_STATEMENT_NOT_PREPARED = (E_BASE + 28); -constexpr int E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29); -constexpr int E_STEP_RESULT_CLOSED = (E_BASE + 30); -constexpr int E_RELATIVE_PATH = (E_BASE + 31); -constexpr int E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32); -constexpr int E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33); -constexpr int E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34); -constexpr int E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35); -constexpr int E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36); -constexpr int E_CREATE_FOLDER_FAIL = (E_BASE + 37); -constexpr int E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38); -constexpr int E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39); -constexpr int E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40); -constexpr int E_NOT_SUPPORT = (E_BASE + 41); -constexpr int E_INVALID_PARCEL = (E_BASE + 42); -constexpr int E_INVALID_FILE_PATH = (E_BASE + 43); -constexpr int E_SET_PERSIST_WAL = (E_BASE + 44); -} // namespace DataShare -} // namespace OHOS - -#endif diff --git a/data_share/interfaces/inner_api/common/include/datashare_predicates.h b/data_share/interfaces/inner_api/common/include/datashare_predicates.h deleted file mode 100644 index 55398a420..000000000 --- a/data_share/interfaces/inner_api/common/include/datashare_predicates.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_PREDICATES_H -#define DATASHARE_PREDICATES_H - -#include "datashare_abs_predicates.h" - -#include -#include - -#include "datashare_predicates_object.h" - -namespace OHOS { -namespace DataShare { -class DataSharePredicates : public virtual DataShareAbsPredicates, public virtual OHOS::Parcelable { -public: - DataSharePredicates(); - explicit DataSharePredicates(Predicates &predicates); - ~DataSharePredicates(); - DataSharePredicates *EqualTo(const std::string &field, const DataSharePredicatesObject &value)override; - DataSharePredicates *NotEqualTo(const std::string &field, const DataSharePredicatesObject &value)override; - DataSharePredicates *GreaterThan(const std::string &field, const DataSharePredicatesObject &value)override; - DataSharePredicates *LessThan(const std::string &field, const DataSharePredicatesObject &value)override; - DataSharePredicates *GreaterThanOrEqualTo(const std::string &field, const DataSharePredicatesObject &value)override; - DataSharePredicates *LessThanOrEqualTo(const std::string &field, const DataSharePredicatesObject &value)override; - DataSharePredicates *In(const std::string &field, const DataSharePredicatesObject &values)override; - DataSharePredicates *NotIn(const std::string &field, const DataSharePredicatesObject &values)override; - DataSharePredicates *BeginWrap()override; - DataSharePredicates *EndWrap()override; - DataSharePredicates *Or()override; - DataSharePredicates *And()override; - DataSharePredicates *Contains(const std::string &field, const std::string &value)override; - DataSharePredicates *BeginsWith(const std::string &field, const std::string &value)override; - DataSharePredicates *EndsWith(const std::string &field, const std::string &value)override; - DataSharePredicates *IsNull(const std::string &field)override; - DataSharePredicates *IsNotNull(const std::string &field)override; - DataSharePredicates *Like(const std::string &field, const std::string &value)override; - DataSharePredicates *Unlike(const std::string &field, const std::string &value); - DataSharePredicates *Glob(const std::string &field, const std::string &value)override; - DataSharePredicates *Between(const std::string &field, const std::string &low, const std::string &high)override; - DataSharePredicates *NotBetween(const std::string &field, const std::string &low, const std::string &high)override; - DataSharePredicates *OrderByAsc(const std::string &field)override; - DataSharePredicates *OrderByDesc(const std::string &field)override; - DataSharePredicates *Distinct()override; - DataSharePredicates *Limit(const int number, const int offset)override; - DataSharePredicates *GroupBy(const std::vector &fields)override; - DataSharePredicates *IndexedBy(const std::string &indexName)override; - DataSharePredicates *KeyPrefix(const std::string &prefix)override; - DataSharePredicates *InKeys(const std::vector &keys)override; - const std::list& GetOperationList() const override; - std::string GetWhereClause() const override; - int SetWhereClause(const std::string &whereClause)override; - std::vector GetWhereArgs() const override; - int SetWhereArgs(const std::vector &whereArgs)override; - std::string GetOrder() const override; - int SetOrder(const std::string &order)override; - SettingMode GetSettingMode() const override; - bool Marshalling(OHOS::Parcel &parcel) const override; - static DataSharePredicates *Unmarshalling(OHOS::Parcel &parcel); - std::string GetTableName() const; - -private: - void SetOperationList(OperationType operationType, const DataSharePredicatesObject ¶1, - const DataSharePredicatesObject ¶2, const DataSharePredicatesObject ¶3, ParameterCount parameterCount); - void ClearQueryLanguage(); - void SetSettingMode(const SettingMode &settingMode); - Predicates predicates_; - std::string whereClause_; - std::vector whereArgs_; - std::string order_; - SettingMode settingMode_ = {}; -}; -} // namespace DataShare -} // namespace OHOS -#endif \ No newline at end of file diff --git a/data_share/interfaces/inner_api/common/include/datashare_predicates_def.h b/data_share/interfaces/inner_api/common/include/datashare_predicates_def.h deleted file mode 100644 index 6ff012b03..000000000 --- a/data_share/interfaces/inner_api/common/include/datashare_predicates_def.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef DATASHARE_PREDICATES_DEF_H -#define DATASHARE_PREDICATES_DEF_H - -#include -#include -#include "datashare_predicates_object.h" -namespace OHOS { -namespace DataShare { -typedef enum { - ZERO_COUNT = 0x0, - ONE_COUNT, - TWO_COUNT, - THREE_COUNT, - INVALID_COUNT, -} ParameterCount; - -typedef enum { - INVALID_OPERATION = 0x0, - EQUAL_TO, - NOT_EQUAL_TO, - GREATER_THAN, - LESS_THAN, - GREATER_THAN_OR_EQUAL_TO, - LESS_THAN_OR_EQUAL_TO, - AND, - OR, - IS_NULL, - IS_NOT_NULL, - IN, - NOT_IN, - LIKE, - UNLIKE, - ORDER_BY_ASC, - ORDER_BY_DESC, - LIMIT, - OFFSET, - BEGIN_WARP, - END_WARP, - BEGIN_WITH, - END_WITH, - IN_KEY, - DISTINCT, - GROUP_BY, - INDEXED_BY, - CONTAINS, - GLOB, - BETWEEN, - NOTBETWEEN, - KEY_PREFIX, - LAST_TYPE -} OperationType; - -typedef struct { - OperationType operation; - DataSharePredicatesObject para1; - DataSharePredicatesObject para2; - DataSharePredicatesObject para3; - ParameterCount parameterCount; -} OperationItem; - -typedef struct { - std::string tableName; - std::list operationList; -} Predicates; - -typedef enum { - INVALID_MODE, - QUERY_LANGUAGE, - PREDICATES_METHOD -} SettingMode; -} // namespace DataShare -} // namespace OHOS - -#endif diff --git a/data_share/interfaces/inner_api/common/include/datashare_predicates_object.h b/data_share/interfaces/inner_api/common/include/datashare_predicates_object.h deleted file mode 100644 index a46cf2106..000000000 --- a/data_share/interfaces/inner_api/common/include/datashare_predicates_object.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_PREDICATES_OBJECT_H -#define DATASHARE_PREDICATES_OBJECT_H - -#include -#include -#include -#include - -namespace OHOS { -namespace DataShare { -enum class DataSharePredicatesObjectType { - TYPE_NULL = 0, - TYPE_INT, - TYPE_DOUBLE, - TYPE_STRING, - TYPE_BOOL, - TYPE_LONG, - TYPE_INT_VECTOR, - TYPE_LONG_VECTOR, - TYPE_DOUBLE_VECTOR, - TYPE_STRING_VECTOR, -}; - -class DataSharePredicatesObject : public virtual OHOS::Parcelable { -public: - DataSharePredicatesObject(); - ~DataSharePredicatesObject(); - DataSharePredicatesObject(DataSharePredicatesObject &&DataSharePredicatesObject) noexcept; - DataSharePredicatesObject(const DataSharePredicatesObject &DataSharePredicatesObject); - DataSharePredicatesObject &operator=(DataSharePredicatesObject &&DataSharePredicatesObject) noexcept; - DataSharePredicatesObject &operator=(const DataSharePredicatesObject &DataSharePredicatesObject); - DataSharePredicatesObject(int val); - DataSharePredicatesObject(int64_t val); - DataSharePredicatesObject(double val); - DataSharePredicatesObject(bool val); - DataSharePredicatesObject(const std::string &val); - DataSharePredicatesObject(const std::vector &val); - DataSharePredicatesObject(const std::vector &val); - DataSharePredicatesObject(const std::vector &val); - DataSharePredicatesObject(const std::vector &val); - - DataSharePredicatesObjectType GetType() const; - int GetInt(int &val) const; - int GetLong(int64_t &val) const; - int GetDouble(double &val) const; - int GetBool(bool &val) const; - int GetString(std::string &val) const; - int GetIntVector(std::vector &val) const; - int GetLongVector(std::vector &val) const; - int GetDoubleVector(std::vector &val) const; - int GetStringVector(std::vector &val) const; - bool Marshalling(Parcel &parcel) const override; - static DataSharePredicatesObject *Unmarshalling(Parcel &parcel); - DataSharePredicatesObjectType type; - std::variant, std::vector, - std::vector, std::vector> value; - - operator int () const - { - return std::get(value); - } - operator int64_t () const - { - return std::get(value); - } - operator double () const - { - return std::get(value); - } - operator bool () const - { - return std::get(value); - } - operator std::string () const - { - return std::get(value); - } - operator std::vector () const - { - return std::get>(value); - } - operator std::vector () const - { - return std::get>(value); - } - operator std::vector () const - { - return std::get>(value); - } - operator std::vector () const - { - return std::get>(value); - } - -private: - void MarshallingVector(Parcel &parcel) const; - static void UnmarshallingVector(DataSharePredicatesObjectType type, DataSharePredicatesObject *pValueObject, - Parcel &parcel); -}; -} // namespace DataShare -} // namespace OHOS -#endif diff --git a/data_share/interfaces/inner_api/common/include/datashare_value_object.h b/data_share/interfaces/inner_api/common/include/datashare_value_object.h deleted file mode 100644 index 8d4fcb97b..000000000 --- a/data_share/interfaces/inner_api/common/include/datashare_value_object.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_VALUE_OBJECT_H -#define DATASHARE_VALUE_OBJECT_H - -#include -#include -#include -#include - -namespace OHOS { -namespace DataShare { -enum DataShareValueObjectType : int32_t { - TYPE_NULL = 0, - TYPE_INT, - TYPE_DOUBLE, - TYPE_STRING, - TYPE_BOOL, - TYPE_BLOB, -}; - -class DataShareValueObject { -public: - DataShareValueObject() : type(TYPE_NULL){}; - ~DataShareValueObject() = default; - DataShareValueObject(DataShareValueObject &&object) noexcept : type(object.type), value(std::move(object.value)){}; - DataShareValueObject(const DataShareValueObject &object) : type(object.type), value(object.value){}; - DataShareValueObject(int val) : DataShareValueObject(static_cast(val)) {}; - DataShareValueObject(int64_t val) : type(TYPE_INT), value(val){}; - DataShareValueObject(double val) : type(TYPE_DOUBLE), value(val){}; - DataShareValueObject(bool val) : type(TYPE_BOOL), value(val){}; - DataShareValueObject(const std::string &val) : type(TYPE_STRING), value(val){}; - DataShareValueObject(const char *val) : DataShareValueObject(std::string(val)){}; - DataShareValueObject(std::vector blob) : type(TYPE_BLOB), value(std::move(blob)){}; - DataShareValueObject &operator=(DataShareValueObject &&object) noexcept - { - if (this == &object) { - return *this; - } - type = object.type; - value = std::move(object.value); - object.type = TYPE_NULL; - return *this; - }; - DataShareValueObject &operator=(const DataShareValueObject &object) - { - if (this == &object) { - return *this; - } - type = object.type; - value = object.value; - return *this; - } - - DataShareValueObjectType GetType() const; - int GetInt(int &val) const; - int GetLong(int64_t &val) const; - int GetDouble(double &val) const; - int GetBool(bool &val) const; - int GetString(std::string &val) const; - int GetBlob(std::vector &val) const; - static bool Marshalling(const DataShareValueObject &valueObject, Parcel &parcel); - static DataShareValueObject *Unmarshalling(Parcel &parcel); - - operator int () const - { - return static_cast(std::get(value)); - } - operator int64_t () const - { - return std::get(value); - } - operator double () const - { - return std::get(value); - } - operator bool () const - { - return std::get(value); - } - operator std::string () const - { - return std::get(value); - } - operator std::vector () const - { - return std::get>(value); - } - DataShareValueObjectType type; - std::variant> value; -}; -} // namespace DataShare -} // namespace OHOS -#endif diff --git a/data_share/interfaces/inner_api/common/include/datashare_values_bucket.h b/data_share/interfaces/inner_api/common/include/datashare_values_bucket.h deleted file mode 100644 index 53032ba9a..000000000 --- a/data_share/interfaces/inner_api/common/include/datashare_values_bucket.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_VALUES_BUCKET_H -#define DATASHARE_VALUES_BUCKET_H - -#include "datashare_value_object.h" - -#include -#include -#include - -namespace OHOS { -namespace DataShare { -class DataShareValuesBucket { -public: - DataShareValuesBucket() = default; - explicit DataShareValuesBucket(std::map &values) : valuesMap(values){}; - ~DataShareValuesBucket() = default; - void Put(const std::string &columnName, const DataShareValueObject &value = {}) - { - valuesMap.insert(std::make_pair(columnName, value)); - } - void PutString(const std::string &columnName, const std::string &value); - void PutInt(const std::string &columnName, int value); - void PutLong(const std::string &columnName, int64_t value); - void PutDouble(const std::string &columnName, double value); - void PutBool(const std::string &columnName, bool value); - void PutBlob(const std::string &columnName, const std::vector &value); - void PutNull(const std::string &columnName); - void Delete(const std::string &columnName); - void Clear(); - int Size() const; - bool IsEmpty() const; - bool HasColumn(const std::string &columnName) const; - bool GetObject(const std::string &columnName, DataShareValueObject &value) const; - void GetAll(std::map &valuesMap) const; - - static bool Marshalling(const DataShareValuesBucket &valuesBucket, Parcel &parcel); - static DataShareValuesBucket *Unmarshalling(Parcel &parcel); - - std::map valuesMap; -}; -} // namespace DataShare -} // namespace OHOS -#endif diff --git a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h deleted file mode 100644 index 125ab1603..000000000 --- a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_HELPER_H -#define DATASHARE_HELPER_H - -#include -#include -#include - -#include "context.h" -#include "datashare_connection.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" -#include "idatashare.h" -#include "uri.h" -#include "datashare_operation.h" - -using Uri = OHOS::Uri; - -namespace OHOS { -namespace AppExecFwk { -class PacMap; -class IDataAbilityObserver; -} - -namespace DataShare { -using string = std::string; -class DataShareHelper final : public std::enable_shared_from_this { -public: - ~DataShareHelper(); - - /** - * @brief Creates a DataShareHelper instance with the Uri specified based on the given Context. - * - * @param context Indicates the Context object on OHOS. - * @param strUri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance with a specified Uri. - */ - static std::shared_ptr Creator(const std::shared_ptr &context, - const std::string &strUri); - - /** - * @brief Creates a DataShareHelper instance with the Uri specified based on the given Context. - * - * @param context Indicates the Context object on OHOS. - * @param StrUri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance with a specified Uri. - */ - static std::shared_ptr Creator(const std::shared_ptr &context, - const std::string &strUri); - - /** - * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship - * between the ability using the Data template (data share for short) and the associated client process in - * a DataShareHelper instance. - * - * @param token Indicates the System token. - * @param strUri Indicates the database table or disk file to operate. - * - * @return Returns the created DataShareHelper instance. - */ - static std::shared_ptr Creator(const sptr &token, const std::string &strUri); - - /** - * @brief Releases the client resource of the Data share. - * You should call this method to releases client resource after the data operations are complete. - * - * @return Returns true if the resource is successfully released; returns false otherwise. - */ - bool Release(); - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - std::vector GetFileTypes(Uri &uri, const std::string &mimeTypeFilter); - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - int OpenFile(Uri &uri, const std::string &mode); - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - int OpenRawFile(Uri &uri, const std::string &mode); - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - int Insert(Uri &uri, const DataShareValuesBucket &value); - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param value Indicates the data to update. This parameter can be null. - * - * @return Returns the number of data records updated. - */ - int Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - int Delete(Uri &uri, const DataSharePredicates &predicates); - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * - * @return Returns the query result. - */ - std::shared_ptr Query( - Uri &uri, const DataSharePredicates &predicates, std::vector &columns); - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data share. This method should be - * implemented by a Data share. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - std::string GetType(Uri &uri); - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - int BatchInsert(Uri &uri, const std::vector &values); - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - void RegisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - void UnregisterObserver(const Uri &uri, const sptr &dataObserver); - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - */ - void NotifyChange(const Uri &uri); - - /** - * @brief Converts the given uri that refer to the Data share into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data share even if the - * context has changed. If you implement URI normalization for a Data share, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data share must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data share does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data share supports URI normalization; returns null otherwise. - */ - Uri NormalizeUri(Uri &uri); - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed - * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found - * in the current environment. - */ - Uri DenormalizeUri(Uri &uri); - -private: - DataShareHelper(const sptr &token, const Uri &uri, const sptr &dataShareProxy, - const sptr dataShareConnection); - void AddDataShareDeathRecipient(const sptr &token); - void OnSchedulerDied(const wptr &remote); - bool CheckUriParam(const Uri &uri); - bool CheckOhosUri(const Uri &uri); - - sptr token_ = {}; - Uri uri_ = Uri(""); - sptr dataShareProxy_ = nullptr; - static std::mutex oplock_; - sptr callerDeathRecipient_ = nullptr; - std::map, sptr> registerMap_; - std::map, std::string> uriMap_; - sptr dataShareConnection_ = nullptr; -}; - -class DataShareDeathRecipient : public IRemoteObject::DeathRecipient { -public: - using RemoteDiedHandler = std::function &)>; - - explicit DataShareDeathRecipient(RemoteDiedHandler handler); - - virtual ~DataShareDeathRecipient(); - - virtual void OnRemoteDied(const wptr &remote); - -private: - RemoteDiedHandler handler_; -}; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_HELPER_H diff --git a/data_share/interfaces/inner_api/consumer/include/datashare_result_set.h b/data_share/interfaces/inner_api/consumer/include/datashare_result_set.h deleted file mode 100644 index 988e32cb2..000000000 --- a/data_share/interfaces/inner_api/consumer/include/datashare_result_set.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_RESULT_SET_H -#define DATASHARE_RESULT_SET_H - -#include -#include -#include -#include - -#include "datashare_abs_result_set.h" -#include "message_parcel.h" -#include "parcel.h" -#include "shared_block.h" -#include "datashare_shared_result_set.h" -#include "result_set_bridge.h" -#include "datashare_block_writer_impl.h" - -namespace OHOS { -namespace DataShare { -class DataShareResultSet : public DataShareAbsResultSet, public DataShareSharedResultSet { -public: - DataShareResultSet(); - explicit DataShareResultSet(std::shared_ptr &bridge); - virtual ~DataShareResultSet(); - int GetBlob(int columnIndex, std::vector &blob) override; - int GetString(int columnIndex, std::string &value) override; - int GetInt(int columnIndex, int &value) override; - int GetLong(int columnIndex, int64_t &value) override; - int GetDouble(int columnIndex, double &value) override; - int IsColumnNull(int columnIndex, bool &isNull) override; - int GetDataType(int columnIndex, DataType &dataType) override; - int GoToRow(int position) override; - int GetAllColumnNames(std::vector &columnNames) override; - int GetRowCount(int &count) override; - AppDataFwk::SharedBlock *GetBlock() const override; - bool OnGo(int startRowIndex, int targetRowIndex) override; - void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) override; - virtual void SetBlock(AppDataFwk::SharedBlock *block); - int Close() override; - bool HasBlock() const; - -protected: - int CheckState(int columnIndex); - void ClearBlock(); - void ClosedBlock(); - virtual void Finalize(); - - friend class ISharedResultSetStub; - friend class ISharedResultSetProxy; - bool Unmarshalling(MessageParcel &parcel); - bool Marshalling(MessageParcel &parcel); - -private: - static int blockId_; - // The actual position of the first row of data in the shareblock - int startRowPos_ = -1; - // The actual position of the last row of data in the shareblock - int endRowPos_ = -1; - // The SharedBlock owned by this DataShareResultSet - AppDataFwk::SharedBlock *sharedBlock_ = nullptr; - std::shared_ptr blockWriter_ = nullptr; - std::shared_ptr bridge_ = nullptr; -}; -} // namespace DataShare -} // namespace OHOS - -#endif // DATASHARE_RESULT_SET_H \ No newline at end of file diff --git a/data_share/interfaces/inner_api/provider/include/result_set_bridge.h b/data_share/interfaces/inner_api/provider/include/result_set_bridge.h deleted file mode 100644 index 3db71cc46..000000000 --- a/data_share/interfaces/inner_api/provider/include/result_set_bridge.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_RESULT_SET_BRIDGE_H -#define DATASHARE_RESULT_SET_BRIDGE_H - -#include -namespace OHOS { -namespace DataShare { -// build the bridge between the database's ResultSet and DataShare's ResultSet -class ResultSetBridge { -public: - class Creator { - public: - virtual std::shared_ptr Create() = 0; - }; - class Writer { - public: - /** - * Allocate a row unit and its directory. - */ - virtual int AllocRow() = 0; - - /** - * Write Null data to the shared block. - */ - virtual int Write(uint32_t column) = 0; - - /** - * Write long data to the shared block. - */ - virtual int Write(uint32_t column, int64_t value) = 0; - - /** - * Write Double data to the shared block. - */ - virtual int Write(uint32_t column, double value) = 0; - - /** - * Write blob data to the shared block. - */ - virtual int Write(uint32_t column, const uint8_t *value, size_t size) = 0; - - /** - * Write string data to the shared block. - */ - virtual int Write(uint32_t column, const char *value, size_t size) = 0; - }; - - virtual ~ResultSetBridge() {} - - /** - * Return a string array holding the names of all of the columns in the - * result set. - * - * return the names of the columns contains in this query result. - */ - virtual int GetAllColumnNames(std::vector &columnNames) = 0; - - /** - * Return the numbers of rows in the result set. - */ - virtual int GetRowCount(int32_t &count) = 0; - - /** - * Called when the position of the result set changes - */ - virtual bool OnGo(int32_t startRowIndex, int32_t targetRowIndex, Writer &writer) = 0; -}; -} // namespace DataShare -} // namespace OHOS -#endif diff --git a/relational_store/figures/en-us_How_RDB_works.png b/figures/en-us_How_RDB_works.png similarity index 100% rename from relational_store/figures/en-us_How_RDB_works.png rename to figures/en-us_How_RDB_works.png diff --git a/relational_store/figures/zh-cn_关系型数据库运作机制.png b/figures/zh-cn_关系型数据库运作机制.png similarity index 100% rename from relational_store/figures/zh-cn_关系型数据库运作机制.png rename to figures/zh-cn_关系型数据库运作机制.png diff --git a/relational_store/frameworks/js/napi/common/include/js_ability.h b/frameworks/js/napi/common/include/js_ability.h similarity index 100% rename from relational_store/frameworks/js/napi/common/include/js_ability.h rename to frameworks/js/napi/common/include/js_ability.h diff --git a/relational_store/frameworks/js/napi/common/include/js_logger.h b/frameworks/js/napi/common/include/js_logger.h similarity index 100% rename from relational_store/frameworks/js/napi/common/include/js_logger.h rename to frameworks/js/napi/common/include/js_logger.h diff --git a/relational_store/frameworks/js/napi/common/include/js_utils.h b/frameworks/js/napi/common/include/js_utils.h similarity index 100% rename from relational_store/frameworks/js/napi/common/include/js_utils.h rename to frameworks/js/napi/common/include/js_utils.h diff --git a/relational_store/frameworks/js/napi/common/include/napi_async_proxy.h b/frameworks/js/napi/common/include/napi_async_proxy.h similarity index 100% rename from relational_store/frameworks/js/napi/common/include/napi_async_proxy.h rename to frameworks/js/napi/common/include/napi_async_proxy.h diff --git a/relational_store/frameworks/js/napi/common/src/js_ability.cpp b/frameworks/js/napi/common/src/js_ability.cpp similarity index 100% rename from relational_store/frameworks/js/napi/common/src/js_ability.cpp rename to frameworks/js/napi/common/src/js_ability.cpp diff --git a/relational_store/frameworks/js/napi/common/src/js_utils.cpp b/frameworks/js/napi/common/src/js_utils.cpp similarity index 100% rename from relational_store/frameworks/js/napi/common/src/js_utils.cpp rename to frameworks/js/napi/common/src/js_utils.cpp diff --git a/relational_store/frameworks/js/napi/dataability/BUILD.gn b/frameworks/js/napi/dataability/BUILD.gn similarity index 100% rename from relational_store/frameworks/js/napi/dataability/BUILD.gn rename to frameworks/js/napi/dataability/BUILD.gn diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h b/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h similarity index 100% rename from relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h rename to frameworks/js/napi/dataability/include/napi_data_ability_predicates.h diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h b/frameworks/js/napi/dataability/include/napi_predicates_utils.h similarity index 100% rename from relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h rename to frameworks/js/napi/dataability/include/napi_predicates_utils.h diff --git a/relational_store/frameworks/js/napi/dataability/src/entry_point.cpp b/frameworks/js/napi/dataability/src/entry_point.cpp similarity index 100% rename from relational_store/frameworks/js/napi/dataability/src/entry_point.cpp rename to frameworks/js/napi/dataability/src/entry_point.cpp diff --git a/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp b/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp similarity index 100% rename from relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp rename to frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp diff --git a/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp b/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp similarity index 100% rename from relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp rename to frameworks/js/napi/dataability/src/napi_predicates_utils.cpp diff --git a/relational_store/frameworks/js/napi/rdb/BUILD.gn b/frameworks/js/napi/rdb/BUILD.gn similarity index 100% rename from relational_store/frameworks/js/napi/rdb/BUILD.gn rename to frameworks/js/napi/rdb/BUILD.gn diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h b/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h rename to frameworks/js/napi/rdb/include/napi_rdb_const_properties.h diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h b/frameworks/js/napi/rdb/include/napi_rdb_predicates.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h rename to frameworks/js/napi/rdb/include/napi_rdb_predicates.h diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h b/frameworks/js/napi/rdb/include/napi_rdb_store.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h rename to frameworks/js/napi/rdb/include/napi_rdb_store.h diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h b/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h rename to frameworks/js/napi/rdb/include/napi_rdb_store_helper.h diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_observer.h b/frameworks/js/napi/rdb/include/napi_rdb_store_observer.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_observer.h rename to frameworks/js/napi/rdb/include/napi_rdb_store_observer.h diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h b/frameworks/js/napi/rdb/include/napi_result_set.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_result_set.h rename to frameworks/js/napi/rdb/include/napi_result_set.h diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_uv_queue.h b/frameworks/js/napi/rdb/include/napi_uv_queue.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_uv_queue.h rename to frameworks/js/napi/rdb/include/napi_uv_queue.h diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_values_bucket.h b/frameworks/js/napi/rdb/include/napi_values_bucket.h similarity index 100% rename from relational_store/frameworks/js/napi/rdb/include/napi_values_bucket.h rename to frameworks/js/napi/rdb/include/napi_values_bucket.h diff --git a/relational_store/frameworks/js/napi/rdb/src/entry_point.cpp b/frameworks/js/napi/rdb/src/entry_point.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/entry_point.cpp rename to frameworks/js/napi/rdb/src/entry_point.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp b/frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp rename to frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp b/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp rename to frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp b/frameworks/js/napi/rdb/src/napi_rdb_store.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp rename to frameworks/js/napi/rdb/src/napi_rdb_store.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp b/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp rename to frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_observer.cpp b/frameworks/js/napi/rdb/src/napi_rdb_store_observer.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_observer.cpp rename to frameworks/js/napi/rdb/src/napi_rdb_store_observer.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp b/frameworks/js/napi/rdb/src/napi_result_set.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp rename to frameworks/js/napi/rdb/src/napi_result_set.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_uv_queue.cpp b/frameworks/js/napi/rdb/src/napi_uv_queue.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_uv_queue.cpp rename to frameworks/js/napi/rdb/src/napi_uv_queue.cpp diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp b/frameworks/js/napi/rdb/src/napi_values_bucket.cpp similarity index 100% rename from relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp rename to frameworks/js/napi/rdb/src/napi_values_bucket.cpp diff --git a/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp b/frameworks/native/appdatafwk/src/shared_block.cpp similarity index 100% rename from relational_store/frameworks/native/appdatafwk/src/shared_block.cpp rename to frameworks/native/appdatafwk/src/shared_block.cpp diff --git a/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp b/frameworks/native/dataability/src/data_ability_predicates.cpp similarity index 100% rename from relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp rename to frameworks/native/dataability/src/data_ability_predicates.cpp diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set.cpp b/frameworks/native/dataability/src/ishared_result_set.cpp similarity index 100% rename from relational_store/frameworks/native/dataability/src/ishared_result_set.cpp rename to frameworks/native/dataability/src/ishared_result_set.cpp diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.cpp b/frameworks/native/dataability/src/ishared_result_set_proxy.cpp similarity index 100% rename from relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.cpp rename to frameworks/native/dataability/src/ishared_result_set_proxy.cpp diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.h b/frameworks/native/dataability/src/ishared_result_set_proxy.h similarity index 100% rename from relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.h rename to frameworks/native/dataability/src/ishared_result_set_proxy.h diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.cpp b/frameworks/native/dataability/src/ishared_result_set_stub.cpp similarity index 100% rename from relational_store/frameworks/native/dataability/src/ishared_result_set_stub.cpp rename to frameworks/native/dataability/src/ishared_result_set_stub.cpp diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.h b/frameworks/native/dataability/src/ishared_result_set_stub.h similarity index 100% rename from relational_store/frameworks/native/dataability/src/ishared_result_set_stub.h rename to frameworks/native/dataability/src/ishared_result_set_stub.h diff --git a/relational_store/frameworks/native/dataability/src/logger.h b/frameworks/native/dataability/src/logger.h similarity index 100% rename from relational_store/frameworks/native/dataability/src/logger.h rename to frameworks/native/dataability/src/logger.h diff --git a/relational_store/frameworks/native/dataability/src/predicates_utils.cpp b/frameworks/native/dataability/src/predicates_utils.cpp similarity index 100% rename from relational_store/frameworks/native/dataability/src/predicates_utils.cpp rename to frameworks/native/dataability/src/predicates_utils.cpp diff --git a/relational_store/frameworks/native/rdb/include/base_transaction.h b/frameworks/native/rdb/include/base_transaction.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/base_transaction.h rename to frameworks/native/rdb/include/base_transaction.h diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h b/frameworks/native/rdb/include/rdb_store_impl.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/rdb_store_impl.h rename to frameworks/native/rdb/include/rdb_store_impl.h diff --git a/relational_store/frameworks/native/rdb/include/share_block.h b/frameworks/native/rdb/include/share_block.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/share_block.h rename to frameworks/native/rdb/include/share_block.h diff --git a/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h b/frameworks/native/rdb/include/shared_block_serializer_info.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h rename to frameworks/native/rdb/include/shared_block_serializer_info.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_config.h b/frameworks/native/rdb/include/sqlite_config.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_config.h rename to frameworks/native/rdb/include/sqlite_config.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_connection.h b/frameworks/native/rdb/include/sqlite_connection.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_connection.h rename to frameworks/native/rdb/include/sqlite_connection.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_connection_pool.h b/frameworks/native/rdb/include/sqlite_connection_pool.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_connection_pool.h rename to frameworks/native/rdb/include/sqlite_connection_pool.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_errno.h b/frameworks/native/rdb/include/sqlite_errno.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_errno.h rename to frameworks/native/rdb/include/sqlite_errno.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_global_config.h b/frameworks/native/rdb/include/sqlite_global_config.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_global_config.h rename to frameworks/native/rdb/include/sqlite_global_config.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h b/frameworks/native/rdb/include/sqlite_shared_result_set.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h rename to frameworks/native/rdb/include/sqlite_shared_result_set.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h b/frameworks/native/rdb/include/sqlite_sql_builder.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h rename to frameworks/native/rdb/include/sqlite_sql_builder.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_statement.h b/frameworks/native/rdb/include/sqlite_statement.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_statement.h rename to frameworks/native/rdb/include/sqlite_statement.h diff --git a/relational_store/frameworks/native/rdb/include/sqlite_utils.h b/frameworks/native/rdb/include/sqlite_utils.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/sqlite_utils.h rename to frameworks/native/rdb/include/sqlite_utils.h diff --git a/relational_store/frameworks/native/rdb/include/step_result_set.h b/frameworks/native/rdb/include/step_result_set.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/step_result_set.h rename to frameworks/native/rdb/include/step_result_set.h diff --git a/relational_store/frameworks/native/rdb/include/store_session.h b/frameworks/native/rdb/include/store_session.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/store_session.h rename to frameworks/native/rdb/include/store_session.h diff --git a/relational_store/frameworks/native/rdb/include/string_utils.h b/frameworks/native/rdb/include/string_utils.h similarity index 100% rename from relational_store/frameworks/native/rdb/include/string_utils.h rename to frameworks/native/rdb/include/string_utils.h diff --git a/relational_store/frameworks/native/rdb/src/abs_predicates.cpp b/frameworks/native/rdb/src/abs_predicates.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/abs_predicates.cpp rename to frameworks/native/rdb/src/abs_predicates.cpp diff --git a/relational_store/frameworks/native/rdb/src/abs_rdb_predicates.cpp b/frameworks/native/rdb/src/abs_rdb_predicates.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/abs_rdb_predicates.cpp rename to frameworks/native/rdb/src/abs_rdb_predicates.cpp diff --git a/relational_store/frameworks/native/rdb/src/abs_result_set.cpp b/frameworks/native/rdb/src/abs_result_set.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/abs_result_set.cpp rename to frameworks/native/rdb/src/abs_result_set.cpp diff --git a/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp b/frameworks/native/rdb/src/abs_shared_result_set.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp rename to frameworks/native/rdb/src/abs_shared_result_set.cpp diff --git a/relational_store/frameworks/native/rdb/src/base_transaction.cpp b/frameworks/native/rdb/src/base_transaction.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/base_transaction.cpp rename to frameworks/native/rdb/src/base_transaction.cpp diff --git a/relational_store/frameworks/native/rdb/src/logger.h b/frameworks/native/rdb/src/logger.h similarity index 100% rename from relational_store/frameworks/native/rdb/src/logger.h rename to frameworks/native/rdb/src/logger.h diff --git a/relational_store/frameworks/native/rdb/src/rdb_helper.cpp b/frameworks/native/rdb/src/rdb_helper.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/rdb_helper.cpp rename to frameworks/native/rdb/src/rdb_helper.cpp diff --git a/relational_store/frameworks/native/rdb/src/rdb_predicates.cpp b/frameworks/native/rdb/src/rdb_predicates.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/rdb_predicates.cpp rename to frameworks/native/rdb/src/rdb_predicates.cpp diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp b/frameworks/native/rdb/src/rdb_store_config.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/rdb_store_config.cpp rename to frameworks/native/rdb/src/rdb_store_config.cpp diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp b/frameworks/native/rdb/src/rdb_store_impl.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp rename to frameworks/native/rdb/src/rdb_store_impl.cpp diff --git a/relational_store/frameworks/native/rdb/src/share_block.cpp b/frameworks/native/rdb/src/share_block.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/share_block.cpp rename to frameworks/native/rdb/src/share_block.cpp diff --git a/relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp b/frameworks/native/rdb/src/shared_block_serializer_info.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/shared_block_serializer_info.cpp rename to frameworks/native/rdb/src/shared_block_serializer_info.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_config.cpp b/frameworks/native/rdb/src/sqlite_config.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_config.cpp rename to frameworks/native/rdb/src/sqlite_config.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp b/frameworks/native/rdb/src/sqlite_connection.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_connection.cpp rename to frameworks/native/rdb/src/sqlite_connection.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_connection_pool.cpp b/frameworks/native/rdb/src/sqlite_connection_pool.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_connection_pool.cpp rename to frameworks/native/rdb/src/sqlite_connection_pool.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_database_utils.cpp b/frameworks/native/rdb/src/sqlite_database_utils.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_database_utils.cpp rename to frameworks/native/rdb/src/sqlite_database_utils.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_global_config.cpp b/frameworks/native/rdb/src/sqlite_global_config.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_global_config.cpp rename to frameworks/native/rdb/src/sqlite_global_config.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_shared_result_set.cpp b/frameworks/native/rdb/src/sqlite_shared_result_set.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_shared_result_set.cpp rename to frameworks/native/rdb/src/sqlite_shared_result_set.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_sql_builder.cpp b/frameworks/native/rdb/src/sqlite_sql_builder.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_sql_builder.cpp rename to frameworks/native/rdb/src/sqlite_sql_builder.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp b/frameworks/native/rdb/src/sqlite_statement.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_statement.cpp rename to frameworks/native/rdb/src/sqlite_statement.cpp diff --git a/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp b/frameworks/native/rdb/src/sqlite_utils.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/sqlite_utils.cpp rename to frameworks/native/rdb/src/sqlite_utils.cpp diff --git a/relational_store/frameworks/native/rdb/src/step_result_set.cpp b/frameworks/native/rdb/src/step_result_set.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/step_result_set.cpp rename to frameworks/native/rdb/src/step_result_set.cpp diff --git a/relational_store/frameworks/native/rdb/src/store_session.cpp b/frameworks/native/rdb/src/store_session.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/store_session.cpp rename to frameworks/native/rdb/src/store_session.cpp diff --git a/relational_store/frameworks/native/rdb/src/string_utils.cpp b/frameworks/native/rdb/src/string_utils.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/string_utils.cpp rename to frameworks/native/rdb/src/string_utils.cpp diff --git a/relational_store/frameworks/native/rdb/src/value_object.cpp b/frameworks/native/rdb/src/value_object.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/value_object.cpp rename to frameworks/native/rdb/src/value_object.cpp diff --git a/relational_store/frameworks/native/rdb/src/values_bucket.cpp b/frameworks/native/rdb/src/values_bucket.cpp similarity index 100% rename from relational_store/frameworks/native/rdb/src/values_bucket.cpp rename to frameworks/native/rdb/src/values_bucket.cpp diff --git a/relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_result_set_bridge.cpp b/frameworks/native/rdb_data_share_adapter/src/rdb_result_set_bridge.cpp similarity index 100% rename from relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_result_set_bridge.cpp rename to frameworks/native/rdb_data_share_adapter/src/rdb_result_set_bridge.cpp diff --git a/relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp b/frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp similarity index 100% rename from relational_store/frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp rename to frameworks/native/rdb_data_share_adapter/src/rdb_utils.cpp diff --git a/relational_store/interfaces/inner_api/appdatafwk/BUILD.gn b/interfaces/inner_api/appdatafwk/BUILD.gn similarity index 100% rename from relational_store/interfaces/inner_api/appdatafwk/BUILD.gn rename to interfaces/inner_api/appdatafwk/BUILD.gn diff --git a/relational_store/interfaces/inner_api/appdatafwk/include/logger.h b/interfaces/inner_api/appdatafwk/include/logger.h similarity index 100% rename from relational_store/interfaces/inner_api/appdatafwk/include/logger.h rename to interfaces/inner_api/appdatafwk/include/logger.h diff --git a/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h b/interfaces/inner_api/appdatafwk/include/shared_block.h similarity index 100% rename from relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h rename to interfaces/inner_api/appdatafwk/include/shared_block.h diff --git a/relational_store/interfaces/inner_api/dataability/BUILD.gn b/interfaces/inner_api/dataability/BUILD.gn similarity index 100% rename from relational_store/interfaces/inner_api/dataability/BUILD.gn rename to interfaces/inner_api/dataability/BUILD.gn diff --git a/relational_store/interfaces/inner_api/dataability/include/data_ability_predicates.h b/interfaces/inner_api/dataability/include/data_ability_predicates.h similarity index 100% rename from relational_store/interfaces/inner_api/dataability/include/data_ability_predicates.h rename to interfaces/inner_api/dataability/include/data_ability_predicates.h diff --git a/relational_store/interfaces/inner_api/dataability/include/ishared_result_set.h b/interfaces/inner_api/dataability/include/ishared_result_set.h similarity index 100% rename from relational_store/interfaces/inner_api/dataability/include/ishared_result_set.h rename to interfaces/inner_api/dataability/include/ishared_result_set.h diff --git a/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h b/interfaces/inner_api/dataability/include/predicates_utils.h similarity index 100% rename from relational_store/interfaces/inner_api/dataability/include/predicates_utils.h rename to interfaces/inner_api/dataability/include/predicates_utils.h diff --git a/relational_store/interfaces/inner_api/rdb/BUILD.gn b/interfaces/inner_api/rdb/BUILD.gn similarity index 100% rename from relational_store/interfaces/inner_api/rdb/BUILD.gn rename to interfaces/inner_api/rdb/BUILD.gn diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h b/interfaces/inner_api/rdb/include/abs_predicates.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/abs_predicates.h rename to interfaces/inner_api/rdb/include/abs_predicates.h diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h b/interfaces/inner_api/rdb/include/abs_rdb_predicates.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h rename to interfaces/inner_api/rdb/include/abs_rdb_predicates.h diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h b/interfaces/inner_api/rdb/include/abs_result_set.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/abs_result_set.h rename to interfaces/inner_api/rdb/include/abs_result_set.h diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h b/interfaces/inner_api/rdb/include/abs_shared_result_set.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h rename to interfaces/inner_api/rdb/include/abs_shared_result_set.h diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_errno.h b/interfaces/inner_api/rdb/include/rdb_errno.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/rdb_errno.h rename to interfaces/inner_api/rdb/include/rdb_errno.h diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_helper.h b/interfaces/inner_api/rdb/include/rdb_helper.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/rdb_helper.h rename to interfaces/inner_api/rdb/include/rdb_helper.h diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_open_callback.h b/interfaces/inner_api/rdb/include/rdb_open_callback.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/rdb_open_callback.h rename to interfaces/inner_api/rdb/include/rdb_open_callback.h diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_predicates.h b/interfaces/inner_api/rdb/include/rdb_predicates.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/rdb_predicates.h rename to interfaces/inner_api/rdb/include/rdb_predicates.h diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_store.h b/interfaces/inner_api/rdb/include/rdb_store.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/rdb_store.h rename to interfaces/inner_api/rdb/include/rdb_store.h diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_store_config.h b/interfaces/inner_api/rdb/include/rdb_store_config.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/rdb_store_config.h rename to interfaces/inner_api/rdb/include/rdb_store_config.h diff --git a/relational_store/interfaces/inner_api/rdb/include/result_set.h b/interfaces/inner_api/rdb/include/result_set.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/result_set.h rename to interfaces/inner_api/rdb/include/result_set.h diff --git a/relational_store/interfaces/inner_api/rdb/include/shared_result_set.h b/interfaces/inner_api/rdb/include/shared_result_set.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/shared_result_set.h rename to interfaces/inner_api/rdb/include/shared_result_set.h diff --git a/relational_store/interfaces/inner_api/rdb/include/sqlite_database_utils.h b/interfaces/inner_api/rdb/include/sqlite_database_utils.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/sqlite_database_utils.h rename to interfaces/inner_api/rdb/include/sqlite_database_utils.h diff --git a/relational_store/interfaces/inner_api/rdb/include/transaction_observer.h b/interfaces/inner_api/rdb/include/transaction_observer.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/transaction_observer.h rename to interfaces/inner_api/rdb/include/transaction_observer.h diff --git a/relational_store/interfaces/inner_api/rdb/include/value_object.h b/interfaces/inner_api/rdb/include/value_object.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/value_object.h rename to interfaces/inner_api/rdb/include/value_object.h diff --git a/relational_store/interfaces/inner_api/rdb/include/values_bucket.h b/interfaces/inner_api/rdb/include/values_bucket.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb/include/values_bucket.h rename to interfaces/inner_api/rdb/include/values_bucket.h diff --git a/relational_store/interfaces/inner_api/rdb_data_share_adapter/BUILD.gn b/interfaces/inner_api/rdb_data_share_adapter/BUILD.gn similarity index 100% rename from relational_store/interfaces/inner_api/rdb_data_share_adapter/BUILD.gn rename to interfaces/inner_api/rdb_data_share_adapter/BUILD.gn diff --git a/relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_logger.h b/interfaces/inner_api/rdb_data_share_adapter/include/rdb_logger.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_logger.h rename to interfaces/inner_api/rdb_data_share_adapter/include/rdb_logger.h diff --git a/relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h b/interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h rename to interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h diff --git a/relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_utils.h b/interfaces/inner_api/rdb_data_share_adapter/include/rdb_utils.h similarity index 100% rename from relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_utils.h rename to interfaces/inner_api/rdb_data_share_adapter/include/rdb_utils.h diff --git a/kv_store/README_zh.md b/kv_store/README_zh.md deleted file mode 100644 index 3a9f47e5a..000000000 --- a/kv_store/README_zh.md +++ /dev/null @@ -1,39 +0,0 @@ -# 轻量系统KV数据库(Lightweight KV store) - -## 简介 - -**轻量系统KV数据库(Lightweight KV store)** 依托当前公共基础库提供的KV存储能力开发,为轻量系统设备应用提供键值对数据管理能力。在有进程的平台上,KV存储提供的参数管理,供单进程访问不能被其他进程使用。在此类平台上,KV存储作为基础库加载在应用进程,以保障不被其他进程访问。 - -1. 当前先支持轻量键值(KV)本地数据存储能力,后续会逐步支持其他更丰富的数据类型。 -2. 轻量键值(KV)数据:数据有结构,文件轻量,具有简易事务性,单独提供一套专用的键值对接口 - -**目前,在轻量系统上默认关闭该特性,需要使用时请用户修改vendor_hisilicon仓配置以开启。** - -## 目录 - -``` -//foundation/distributeddatamgr/kv_store -├── frameworks # 框架层代码 -│ └── js # JS API的实现 -│ │ └── napi # napi代码实现 -│ └── native # 内部接口实现 -├── interfaces # 接口代码 - └── inner_api # 内部接口声明 -``` -## 约束 - -- KV大小及可存储条目数在平台可承受内可修改配置,轻量系统默认为小于Key(32byte),Value(512byte),通过修改编译宏修改; - -- 依赖平台具有正常的文件创建、读写删除修改、锁等能力,针对不同平台(如LiteOS-M内核、LiteOS-A内核等)尽可能表现接口语义功能的不变; - -- 由于平台能力差异数据库能力需要做相应裁剪,其中不同平台内部实现可能不同; - -- 对于指定路径仅支持创建数据库单例,不支持同一路径创建多数据库实例对象。 - -## 相关仓 - -- [分布式数据管理子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%88%86%E5%B8%83%E5%BC%8F%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md) - -- [**distributeddatamgr\_kv_store**](https://gitee.com/openharmony/distributeddatamgr_kv_store/blob/master/README_zh.md) - -- [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite) \ No newline at end of file diff --git a/kv_store/bundle.json b/kv_store/bundle.json deleted file mode 100644 index a0f798152..000000000 --- a/kv_store/bundle.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "@openharmony/kv_store", - "version": "3.1.0", - "license": "Apache License 2.0", - "description": "", - "publishAs": "code-segment", - "segment": { - "destPath": "foundation/distributeddatamgr/kv_store/interfaces/inner_api/kv_store" - }, - "dirs": {}, - "scripts": {}, - "component": { - "name": "kv_store", - "subsystem": "distributeddatamgr", - "features": [], - "adapted_system_type": [ - "mini", - "small" - ], - "rom": "13KB", - "ram": "80KB", - "deps": { - "thrid_party": [ "bounds_checking_function" ], - "kernel_special": {}, - "board_special": {}, - "components": [ - "utils_lite" - ] - }, - "build": { - "sub_component": [ "//foundation/distributeddatamgr/kv_store/interfaces/inner_api/kv_store" ], - "inner_kits": [], - "test": [] - } - } -} \ No newline at end of file diff --git a/kv_store/frameworks/native/dbm_kv_store/inc/dbm_def.h b/kv_store/frameworks/native/dbm_kv_store/inc/dbm_def.h deleted file mode 100644 index 46e79d485..000000000 --- a/kv_store/frameworks/native/dbm_kv_store/inc/dbm_def.h +++ /dev/null @@ -1,74 +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 DBM_DEF_H -#define DBM_DEF_H - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif /* __cplusplus */ - -/* default max len of KV */ -#define MAX_KEY_LEN 32 // the suffix is 7 bytes -#ifndef MAX_VALUE_LEN -#define MAX_VALUE_LEN 512 -#endif - -/* - * Defintion of macro using in KVStore. - */ - -#define DBM_SW_VERSION "1.0" -#define DBM_SW_VERSION_NUM 0x10 - -#define DBM_CTRL_SET_LOCK 0x0 /* set lock function control command */ -#define DBM_CTRL_SET_UNLOCK 0x1 /* set unlock function control command */ - -/* log function: default DBM_PRINT macro is printf */ -#ifndef DBM_PRINT -#define DBM_PRINT(...) printf(__VA_ARGS__) -#endif -#define DBM_LOG_PREFIX1() DBM_PRINT("[DataMgrKVDB]"DBM_LOG_TAG) -#define DBM_LOG_PREFIX2() DBM_PRINT(" ") -#define DBM_LOG_PREFIX() DBM_LOG_PREFIX1();DBM_LOG_PREFIX2() -#ifdef DBM_DEBUG_ENABLE -#define DBM_DEBUG(...) DBM_LOG_PREFIX();DBM_PRINT(__VA_ARGS__);DBM_PRINT("\n") -#else -#define DBM_DEBUG(...) -#endif - -#ifdef DBM_RUNTIME_LOG_ENABLE -/* routine print function. Must be implement by user. */ -#define DBM_INFO(...) DBM_LOG_PREFIX();DBM_PRINT(__VA_ARGS__);DBM_PRINT("\n") -#else -#define DBM_INFO(...) -#endif - -/* assert for developer */ -#define DBM_ASSERT(EXPR) \ -if (!(EXPR)) \ -{ \ - DBM_DEBUG("%s has assert failed at %s.", #EXPR, __FUNCTION__); \ - while (1); \ -} - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif /* __cplusplus */ - -#endif /* DBM_DEF_H */ diff --git a/kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_hal/dbm_kv_store.c b/kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_hal/dbm_kv_store.c deleted file mode 100644 index 962214ea0..000000000 --- a/kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_hal/dbm_kv_store.c +++ /dev/null @@ -1,1413 +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 "dbm_kv_store.h" - -#include - -#include "dbm_def.h" -#include "dbm_errno.h" -#include "dbm_kv_store_env.h" - -#include "utils_file.h" -#include "ohos_types.h" - -#ifdef DBM_DEBUG_ENABLE -#define DBM_LOG_TAG "[low_lvl][kv]" -#endif - -#define MAX_GET_VALUE_LEN 0x7FFFFFFF // max int -#define KV_SUM_FILE "KV_FILE_SUM" -#define KV_MAGIC "KVDB" -#define KV_MAGIC_SIZE 4 -#define KV_SUM_INDEX 4 -#define KV_SUM_BLOCK_SIZE 4 -#define KV_SUM_DATA_ITEM_SIZE 44 -#define MAX_KEY_PATH 256 -#define MAX_FILE_PATH 256 -#define SUM_FILE_HEADER_SIZE 20 -#define SUM_FILE_DEFAULT_HEADER "000\0"KV_MAGIC"\0\0\0\0"DBM_SW_VERSION"\0"KV_MAGIC - -/* -sum file struct -| 4 | 4 | 4 | 4 | 4 | 44 | repeat | -***********************************************************************************...*********** -| item sum num | KVDB magic | sum file flag | DB version | KVDB magic | Data Item | Data Item | -***********************************************************************************...*********** - -data item struct -| 4 | 4 | 32 | 4 | -*********************************************** -| item flag | key length | key | KVDB magic | -*********************************************** - -item sum num: means total number of entries in the current database -KVDB magic: Constant KVDB for verification -sum file flag: 1st byte means sum num valid, 2nd byte means db invalid -Data Item: key content and status - item flag: 1st byte constant 0, 2nd means item valid, 3rd means bak valid - key length: cur constant 0 - key: key content -*/ - -#define DB_LOCK(db) \ - do { \ - if (((DBHandle)(db))->lock != NULL) ((DBHandle)(db))->lock((DBHandle)(db)); \ - } while (0) - -#define DB_UNLOCK(db) \ - do { \ - if (((DBHandle)(db))->unlock != NULL) ((DBHandle)(db))->unlock((DBHandle)(db)); \ - } while (0) - -static boolean IsValidPath(const char* path) -{ - if ((path == NULL) || (strlen(path) >= MAX_FILE_PATH)) { - return FALSE; - } - return TRUE; -} - -typedef enum { - DBM_DB_TYPE_KV = 0, - DBM_DB_TYPE_KV_NO_DIR = 1, -} DBType; - -struct KVDBStatus { - boolean isNeedRecovery; - boolean isInvalid; - boolean kvSumIndexValid; -} KVDBStatus; - -/* database structure */ -typedef struct DBM *DBHandle; -struct DBM { - char magic[KV_MAGIC_SIZE + 1]; // it is a buff special identification db - const char* name; // database name - const char* dirPath; // directory path for saving database - DBType type; // database type - int kvItemSum; // database max kv item size. - boolean initOK; // database has been init ok - struct KVDBStatus sumFlag; // database status - int sumFileFd; // current index file object - void (*lock)(DBHandle db); // lock the database operate - void (*unlock)(DBHandle db); // unlock the database operate - int version; // database version -} DBM; - -// data item struct def -typedef enum { - BLOB, - STR, -} ValueType; - -struct ItemStatus { - boolean isValid; - boolean isBakValid; - ValueType valueType; -} ItemStatus; - -typedef struct KeyItem { - char key[MAX_KEY_LEN + 1]; - struct ItemStatus flag; - unsigned int len; - int index; // in sum file position of index -} KeyItem; - -static const char* ItemPathFormat(const DBHandle db) -{ - if (db->type == DBM_DB_TYPE_KV_NO_DIR) { - return "%s%s"; - } - return "%s/%s"; -} - -/* begin GetKVStore */ -static void DBMInitFinish(const DBHandle db, int ret) -{ - static boolean isLogShow = FALSE; - if (ret == DBM_OK) { - db->initOK = TRUE; - if (!isLogShow) { - DBM_INFO("DBM KV V%s is initialize success.", DBM_SW_VERSION); - isLogShow = TRUE; - } - } else { - DBM_INFO("Error: %s DB initialize fail (%d).", - (db->type == DBM_DB_TYPE_KV) || (db->type == DBM_DB_TYPE_KV_NO_DIR) ? "KVDB" : "OTHERS_TYPE", ret); - } -} - -static void ReleaseKVDBHandle(DBHandle db) -{ - if (db == NULL) { - return; - } - - if (db->sumFileFd >= 0) { - UtilsFileClose(db->sumFileFd); - db->sumFileFd = -1; - } - free(db); -} - -static DBHandle GetKVDBHandle(const char* path) -{ - DBHandle db = (DBHandle)malloc(sizeof(DBM)); - if (db == NULL) { - return NULL; - } - - int ret = memset_s(db, sizeof(DBM), 0, sizeof(DBM)); - if (ret != EOK) { - free(db); - return NULL; - } - - if (strcpy_s(db->magic, KV_MAGIC_SIZE + 1, KV_MAGIC) != EOK) { - free(db); - return NULL; - } - db->dirPath = path; - - db->kvItemSum = 0; - db->initOK = FALSE; - db->version = DBM_SW_VERSION_NUM; - db->sumFileFd = -1; - - db->type = (strlen(path) == 0) ? DBM_DB_TYPE_KV_NO_DIR : DBM_DB_TYPE_KV; - - ret = DBM_UserInit(); - DBMInitFinish(db, ret); - if (ret != 0) { - ReleaseKVDBHandle(db); - return NULL; - } - return db; -} - -static int FileReadCursor(int fd, int offset, unsigned int whence, char* buf, unsigned int cursorSize) -{ - int pos = UtilsFileSeek(fd, offset, whence); - if (pos < 0) { - return UtilsFileSeek(fd, 0, SEEK_END_FS); - } - - pos = UtilsFileRead(fd, buf, cursorSize); - if (pos < 0) { - return -1; - } - return pos; -} - -static int FileWriteCursor(int fd, int offset, unsigned int whence, const char* buf, unsigned int cursorSize) -{ - int pos = UtilsFileSeek(fd, offset, whence); - if (pos < 0) { - DBM_INFO("FileWriteCursor: seek file offset[%d] fail.", offset); - return -1; // Invalid position - } - - int ret = UtilsFileWrite(fd, buf, cursorSize); - if (ret < 0) { - DBM_INFO("FileWriteCursor: write buff to file fail. [%d]", ret); - return -1; - } - return ret; -} - -static boolean IsStrSame(const char* value, int len, const char* str) -{ - if ((unsigned int)len != strlen(str) + 1) { - return FALSE; - } - - for (int i = 0; i < len; ++i) { - if (*value++ != *str++) { - return FALSE; - } - } - return TRUE; -} - -// Is judge by magic num which save in sum file header -static boolean IsHeaderValid(const char* header) -{ - char magic[KV_MAGIC_SIZE + 1] = {0}; - if (memcpy_s(magic, KV_MAGIC_SIZE, header + KV_SUM_INDEX, KV_MAGIC_SIZE) != EOK && - !IsStrSame(magic, KV_MAGIC_SIZE + 1, KV_MAGIC)) { - return FALSE; - } - - // after 1st magic is block size flag - // magic is after 4 block - if (memcpy_s(magic, KV_MAGIC_SIZE, header + 4 * KV_SUM_BLOCK_SIZE, KV_MAGIC_SIZE) != EOK && - !IsStrSame(magic, KV_MAGIC_SIZE + 1, KV_MAGIC)) { - return FALSE; - } - return TRUE; -} - -static int GetSumFilePath(DBHandle db, char* sumFilePath, unsigned int len) -{ - if (!db) { - return DBM_ERROR; - } - - if (strlen(db->dirPath) == 0) { - if (strcpy_s(sumFilePath, sizeof(KV_SUM_FILE), KV_SUM_FILE) != EOK) { - return DBM_OK; - } - } - - if (sprintf_s(sumFilePath, len, ItemPathFormat(db), db->dirPath, KV_SUM_FILE) < 0) { - return DBM_INVALID_ARGS; - } - return DBM_OK; -} - -// return is fd, -1 means invalid -static int OpenSumFile(DBHandle db, unsigned int mode) -{ - char* sumFilePath = (char *)malloc(MAX_KEY_PATH + 1); - if (sumFilePath == NULL) { - return -1; // invalid fd - } - (void)memset_s(sumFilePath, MAX_FILE_PATH + 1, 0, MAX_FILE_PATH + 1); - - int ret = GetSumFilePath(db, sumFilePath, MAX_KEY_PATH + 1); - if (ret < 0) { - DBM_INFO("OpenSumFile: Get sum file path fail."); - free(sumFilePath); - return -1; - } - int fd = UtilsFileOpen(sumFilePath, mode, 0); - free(sumFilePath); - return fd; -} - -static int LoadDataItem(DBHandle db, int index, KeyItem* item) -{ - if (item == NULL) { - return DBM_INVALID_ARGS; - } - - char itemContent[KV_SUM_DATA_ITEM_SIZE + 1] = {0}; - int ret = FileReadCursor(db->sumFileFd, SUM_FILE_HEADER_SIZE + index * KV_SUM_DATA_ITEM_SIZE, - SEEK_SET_FS, itemContent, KV_SUM_DATA_ITEM_SIZE); - if (ret < 0) { - return DBM_ERROR; - } - - // check last tail magic num - if (!IsStrSame(itemContent + KV_SUM_DATA_ITEM_SIZE - KV_MAGIC_SIZE, KV_MAGIC_SIZE + 1, KV_MAGIC)) { - return DBM_OK; - } - - // 1st pos is default 0 - // 3 pos represented flag - item->flag.isValid = *(itemContent + 1); - item->flag.isBakValid = *(itemContent + 2); - item->flag.valueType = *(itemContent + 3); - - char keyLen[KV_SUM_BLOCK_SIZE] = {0}; // default key content len is 32 - ret = memcpy_s(keyLen, KV_SUM_BLOCK_SIZE, itemContent + KV_SUM_BLOCK_SIZE, KV_SUM_BLOCK_SIZE); - if (ret != EOK) { - return DBM_ERROR; - } - - int length = atoi(keyLen); - if (length < 0) { - return DBM_ERROR; - } - item->len = length; - - ret = memcpy_s(item->key, MAX_KEY_LEN, itemContent + 2 * KV_SUM_BLOCK_SIZE, MAX_KEY_LEN); // 2 block: index and len - if (ret != EOK) { - return DBM_ERROR; - } - item->key[MAX_KEY_LEN] = '\0'; // make sure key is a string - item->index = index; - return DBM_OK; -} - -static int DeleteValueFromFile(DBHandle db, const char* key) -{ - char keyPath[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, ItemPathFormat(db), db->dirPath, key) < 0) { - return DBM_ERROR; - } - int ret = UtilsFileDelete(keyPath); - if (ret < 0) { - DBM_INFO("%s delete value file failed ret[%d]", __func__, ret); - return DBM_ERROR; - } - return DBM_OK; -} - -static boolean IsNewItem(DBHandle db, const char* key) -{ - char keyPath[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, ItemPathFormat(db), db->dirPath, key) < 0) { - return FALSE; - } - int fd = UtilsFileOpen(keyPath, O_RDONLY_FS, 0); - if (fd < 0) { - return TRUE; - } - - int ret = UtilsFileClose(fd); - fd = -1; - if (ret < 0) { - DBM_INFO("Is new item close file fail."); - } - return FALSE; -} - -static inline int GetKeyItemOffset(int index) -{ - return SUM_FILE_HEADER_SIZE + index * KV_SUM_DATA_ITEM_SIZE; -} - -static int DelItem(DBHandle db, const KeyItem* item) -{ - if (!IsNewItem(db, item->key) && DeleteValueFromFile(db, item->key) != DBM_OK) { - return DBM_ERROR; - } - - char bakKey[MAX_KEY_LEN + 8] = {0}; // 8 is bak file suffix len - if (sprintf_s(bakKey, MAX_KEY_LEN + 8, "%s_dbm_kv", item->key) < 0) { - return DBM_INVALID_ARGS; - } - - if (!IsNewItem(db, bakKey) && DeleteValueFromFile(db, bakKey) != DBM_OK) { - return DBM_ERROR; - } - - char itemData[KV_SUM_DATA_ITEM_SIZE + 1] = {0}; - // erase all except magic num, means this item is useless but invalid - int ret = FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index), SEEK_SET_FS, - itemData, KV_SUM_DATA_ITEM_SIZE - KV_MAGIC_SIZE); - if (ret < 0) { - return DBM_ERROR; - } - return DBM_OK; -} - -static int CopyValueToFile(DBHandle db, const char* src, const char* dest) -{ - char srcPath[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(srcPath, MAX_KEY_PATH + 1, ItemPathFormat(db), db->dirPath, src) < 0) { - return DBM_ERROR; - } - - char destPath[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(destPath, MAX_KEY_PATH + 1, ItemPathFormat(db), db->dirPath, dest) < 0) { - return DBM_ERROR; - } - int ret = UtilsFileCopy(srcPath, destPath); - if (ret < 0) { - DBM_INFO("%s copy value file failed ret[%d]", __func__, ret); - return DBM_ERROR; - } - - return DBM_OK; -} - -// recover backup item -static int RecoverItem(DBHandle db, const KeyItem* item) -{ - if (!IsNewItem(db, item->key) && DeleteValueFromFile(db, item->key) != DBM_OK) { - return DBM_ERROR; - } - - char bakFile[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(bakFile, MAX_KEY_PATH + 1, "%s_dbm_kv", item->key) < 0) { - return DBM_INVALID_ARGS; - } - - if (CopyValueToFile(db, bakFile, item->key) != DBM_OK) { - return DBM_ERROR; - } - - char itemFlagByte[1] = {0}; - int ret = FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index) + 1, SEEK_SET_FS, itemFlagByte, 1); - if (ret < 0) { - DBM_INFO("%s update flag failed ret[%d]", __func__, ret); - return DBM_ERROR; - } - return DBM_OK; -} - -static int CheckPointItem(DBHandle db, const KeyItem* item) -{ - if (strlen(item->key) == 0) { - return DBM_OK; - } - if (db->sumFlag.isInvalid || !item->flag.isValid) { - DBM_DEBUG("CheckPointItem item DBinvalid[%d] itemValid[%d]", db->sumFlag.isInvalid, item->flag.isValid); - return DelItem(db, item); - } - - char bakFile[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(bakFile, MAX_KEY_PATH + 1, "%s_dbm_kv", item->key) < 0) { - return DBM_ERROR; - } - if (item->flag.isBakValid && IsNewItem(db, bakFile)) { - return DelItem(db, item); - } - - if (item->flag.isBakValid) { - DBM_DEBUG("CheckPointItem item bak valid[%d]", item->flag.isBakValid); - return RecoverItem(db, item); - } else { - if (!IsNewItem(db, bakFile) && DeleteValueFromFile(db, bakFile) != DBM_OK) { - DBM_INFO("CheckPointItem: delete old backup data fail."); - return DBM_ERROR; - } - } - return DBM_OK; -} - -// need check all item -static int VacuumStore(DBHandle db) -{ - int sumFileLen = UtilsFileSeek(db->sumFileFd, 0UL, SEEK_END_FS); - if ((sumFileLen < SUM_FILE_HEADER_SIZE) && (sumFileLen != 0)) { - DBM_INFO("sum file invalid length!"); - return DBM_ERROR; - } - - int ret = UtilsFileSeek(db->sumFileFd, 0UL, SEEK_SET_FS); - if (ret < 0) { - return DBM_ERROR; - } - // 20 is header len, 44 is per item size - int sumIndex = (sumFileLen - SUM_FILE_HEADER_SIZE) / KV_SUM_DATA_ITEM_SIZE; - if (sumIndex > DBM_MAX_KV_SUM) { - return DBM_ERROR; - } - if (!db->sumFlag.kvSumIndexValid) { - db->kvItemSum = 0; // need recalculate - } - - KeyItem* item = (KeyItem *)malloc(sizeof(KeyItem)); - if (item == NULL) { - return DBM_ERROR; - } - (void)memset_s(item, sizeof(KeyItem), 0, sizeof(KeyItem)); - for (int index = 0; index < sumIndex; ++index) { - ret = LoadDataItem(db, index, item); - if (ret != DBM_OK) { - DBM_DEBUG("VacuumStore: load data item fail!"); - continue; - } - ret = CheckPointItem(db, item); - if (ret != DBM_OK) { - DBM_INFO("VacuumStore: check point data item fail!"); - break; - } - - if (!db->sumFlag.kvSumIndexValid && item->flag.isValid && !db->sumFlag.isInvalid) { - db->kvItemSum++; - } - (void)memset_s(item, sizeof(KeyItem), 0, sizeof(KeyItem)); - } - free(item); - return ret; -} - -static int SetSumIndexToFile(DBHandle db, int sumIndex) -{ - db->sumFlag.kvSumIndexValid = FALSE; - // sum index in sum file pos(9) - int pos = FileWriteCursor(db->sumFileFd, KV_SUM_INDEX + KV_MAGIC_SIZE, SEEK_SET_FS, "\0", 1); - if (pos < 0) { - return DBM_ERROR; - } - - char value[KV_SUM_INDEX] = {0}; - if (sprintf_s(value, KV_SUM_INDEX, "%d", sumIndex) < 0) { - return DBM_ERROR; - } - - db->kvItemSum = sumIndex; - pos = FileWriteCursor(db->sumFileFd, 0, SEEK_SET_FS, value, KV_SUM_INDEX); - if (pos < 0) { - return DBM_ERROR; - } - - db->sumFlag.kvSumIndexValid = TRUE; - pos = FileWriteCursor(db->sumFileFd, KV_SUM_INDEX + KV_MAGIC_SIZE, SEEK_SET_FS, "\1", 1); - if (pos < 0) { - return DBM_ERROR; - } - return DBM_OK; -} - -static int SetSumIndex(DBHandle db) -{ - if (db->sumFlag.kvSumIndexValid) { - return DBM_OK; // has been refresh in load header - } - return SetSumIndexToFile(db, db->kvItemSum); -} - -static int CheckPoint(DBHandle db) -{ - if (!db->sumFlag.isNeedRecovery) { - return DBM_OK; - } - - int ret = VacuumStore(db); - if (ret != DBM_OK) { - return DBM_ERROR; - } - - ret = SetSumIndex(db); - if (ret != DBM_OK) { - return DBM_ERROR; - } - - char flag[KV_SUM_BLOCK_SIZE] = {0}; - ret = FileWriteCursor(db->sumFileFd, KV_SUM_INDEX + KV_SUM_BLOCK_SIZE, SEEK_SET_FS, flag, KV_SUM_BLOCK_SIZE); - if (ret < 0) { // ret is fd offset - return DBM_ERROR; - } - - (void)memset_s(&(db->sumFlag), sizeof(KVDBStatus), 0, sizeof(KVDBStatus)); - db->sumFlag.isNeedRecovery = FALSE; - return DBM_OK; -} - -static void SetSumFlag(DBHandle db, const char* headerFlag) -{ - db->sumFlag.kvSumIndexValid = *headerFlag; - db->sumFlag.isInvalid = *(headerFlag + 1); - db->sumFlag.isNeedRecovery = TRUE; -} - -static int LoadSumFileHeader(DBHandle db) -{ - char header[SUM_FILE_HEADER_SIZE + 1] = {0}; - int ret = FileReadCursor(db->sumFileFd, 0, SEEK_SET_FS, header, SUM_FILE_HEADER_SIZE); - if (ret < 0) { - return DBM_ERROR; - } - - char sumIndex[KV_SUM_INDEX + 1] = {0}; - if (memcpy_s(sumIndex, KV_SUM_INDEX, header, KV_SUM_INDEX) != EOK) { - return DBM_ERROR; - } - - char headerFlag[KV_SUM_BLOCK_SIZE + 1] = {0}; - if (memcpy_s(headerFlag, KV_SUM_INDEX, header + KV_MAGIC_SIZE + KV_SUM_INDEX, KV_SUM_INDEX) != EOK) { - return DBM_ERROR; - } - - if (!IsHeaderValid(header)) { - return DBM_ERROR; - } - - SetSumFlag(db, headerFlag); - if (db->sumFlag.kvSumIndexValid) { - db->kvItemSum = atoi(sumIndex); - } - return DBM_OK; -} - -static int InitKVStore(DBHandle db) -{ - db->sumFileFd = OpenSumFile(db, O_RDWR_FS | O_CREAT_FS); - if (db->sumFileFd < 0) { - return DBM_ERROR; - } - - int sumFileLen = UtilsFileSeek(db->sumFileFd, 0UL, SEEK_END_FS); - DBM_DEBUG("InitKVStore read sum file len [%d]", sumFileLen); - if (sumFileLen < 0) { - return DBM_ERROR; - } - - // Is need this version or corrupt - if ((sumFileLen < SUM_FILE_HEADER_SIZE) && (sumFileLen != 0) && (sumFileLen != KV_SUM_INDEX)) { - DBM_INFO("sum file invalid length!"); - sumFileLen = 0; - } - - int ret = UtilsFileSeek(db->sumFileFd, 0UL, SEEK_SET_FS); // reset pos to begin - if (ret < 0) { - return DBM_ERROR; - } - - // sumFileLen==0 means it's a new sum file - if (sumFileLen == 0) { - ret = UtilsFileWrite(db->sumFileFd, SUM_FILE_DEFAULT_HEADER, SUM_FILE_HEADER_SIZE); - if (ret < 0) { - return DBM_ERROR; - } - } - - if (sumFileLen > 0) { - ret = LoadSumFileHeader(db); - if (ret != DBM_OK) { - return DBM_ERROR; - } - - ret = CheckPoint(db); - if (ret != DBM_OK) { - return DBM_ERROR; - } - } - return DBM_OK; -} - -int DBM_GetKVStore(const char* storeFullPath, KVStoreHandle* kvStore) -{ - DBM_DEBUG("Limitation:key len[%d],value len[%d], keys sum[%d]", MAX_KEY_LEN, MAX_VALUE_LEN, DBM_MAX_KV_SUM); - if (kvStore == NULL) { - return DBM_INVALID_ARGS; - } - - if (!IsValidPath(storeFullPath)) { - DBM_INFO("Get KVStore invalid path."); - return DBM_INVALID_ARGS; - } - - DBHandle db = GetKVDBHandle(storeFullPath); - if (db == NULL) { - DBM_INFO("Get KVDBHandle fail."); - return DBM_ERROR; - } - - int ret = InitKVStore(db); - if (ret != DBM_OK) { - DBM_INFO("Get Init KV store fail."); - ReleaseKVDBHandle(db); - return DBM_ERROR; - } - - DBM_DEBUG("FInish Get KV store."); - *kvStore = db; - return DBM_OK; -} -/* Finish GetKVStore */ - -static boolean IsDataItemMatched(DBHandle db, const char* key, int index) -{ - if (index < 0) { - return FALSE; - } - char itemContent[KV_SUM_DATA_ITEM_SIZE + 1] = {0}; - int ret = FileReadCursor(db->sumFileFd, SUM_FILE_HEADER_SIZE + index * KV_SUM_DATA_ITEM_SIZE, - SEEK_SET_FS, itemContent, KV_SUM_DATA_ITEM_SIZE); - if (ret < 0) { - return FALSE; - } - return IsStrSame(itemContent + KV_MAGIC_SIZE + KV_SUM_BLOCK_SIZE, strlen(key) + 1, key); -} - -static int IsNeedTransferValue(DBHandle db, const char* key, const char* fileRead, unsigned int fileLen, boolean* isNeed) -{ - if (fileLen <= KV_SUM_BLOCK_SIZE) { // value size < index, means old version data - *isNeed = FALSE; - return DBM_OK; - } - - char keyIndex[KV_SUM_BLOCK_SIZE] = {0}; - int ret = memcpy_s(keyIndex, KV_SUM_BLOCK_SIZE - 1, fileRead, KV_SUM_BLOCK_SIZE - 1); - if (ret != EOK) { - return DBM_ERROR; - } - - // output refer to value version - *isNeed = IsDataItemMatched(db, key, atoi(keyIndex)); - return DBM_OK; -} - -static int FormatValueByFile(boolean isNeedTrans, char* value, unsigned int len, - const char* fileRead, unsigned int fileLen) -{ - unsigned int offset = isNeedTrans ? KV_SUM_BLOCK_SIZE : 0; - if (fileLen - offset > len) { - return -1; - } - - int ret = memcpy_s(value, len, fileRead + offset, fileLen - offset); - if (ret != EOK) { - return -1; - } - return fileLen - offset; -} - -static int GetValueByFile(DBHandle db, const char* key, const char* keyGet, char* value, unsigned int len) -{ - char keyPath[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, ItemPathFormat(db), db->dirPath, keyGet) < 0) { - return -1; - } - - unsigned int valueLen = 0; - if (UtilsFileStat(keyPath, &valueLen) < 0) { - return -1; - } - - if (valueLen > MAX_VALUE_LEN + KV_SUM_BLOCK_SIZE) { - return -1; - } - - char* valueRead = (char *)malloc(valueLen); - if (valueRead == NULL) { - return -1; - } - (void)memset_s(valueRead, valueLen, 0, valueLen); - - int fd = UtilsFileOpen(keyPath, O_RDONLY_FS, 0); - if (fd < 0) { - free(valueRead); - return -1; - } - - int valueReadLen = UtilsFileRead(fd, valueRead, valueLen); - UtilsFileClose(fd); - fd = -1; - if (valueReadLen < 0) { - free(valueRead); - return -1; - } - - boolean isNeedTrans = TRUE; - int ret = IsNeedTransferValue(db, key, valueRead, valueReadLen, &isNeedTrans); - if (ret != DBM_OK) { - free(valueRead); - return -1; - } - - ret = FormatValueByFile(isNeedTrans, value, len, valueRead, valueReadLen); - free(valueRead); - if (ret < 0) { - DBM_INFO("Format file value fail."); - } - return ret; -} - -static int Get(KVStoreHandle db, const char* key, void* value, unsigned int count, unsigned int* realValueLen) -{ - if (!IsValidKey(key) || (value == NULL) || (count > MAX_GET_VALUE_LEN)) { - return DBM_INVALID_ARGS; - } - - if (!db->initOK || !IsStrSame(db->magic, KV_MAGIC_SIZE + 1, KV_MAGIC)) { - return DBM_INVALID_ARGS; - } - - char bakFile[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(bakFile, MAX_KEY_PATH + 1, "%s_dbm_kv", key) < 0) { - return DBM_INVALID_ARGS; - } - - boolean isBakExist = !IsNewItem(db, bakFile); - if (db->sumFlag.isInvalid || (IsNewItem(db, key) && !isBakExist)) { - return DBM_NOT_FOUND; - } - - const char* keyGet = isBakExist ? bakFile : key; // bak existed means update fail - int ret = GetValueByFile(db, key, keyGet, value, count); - if (ret < 0) { - DBM_INFO("Get: get value from key path file fail."); - return DBM_ERROR; - } - *realValueLen = ret; - return DBM_OK; -} - -int DBM_Get(KVStoreHandle db, const char* key, void* value, unsigned int count, unsigned int* realValueLen) -{ - if (db == NULL) { - return DBM_INVALID_ARGS; - } - /* lock the KVDB */ - DB_LOCK(db); - int ret = Get(db, key, value, count, realValueLen); - DB_UNLOCK(db); - return ret; -} - -static int SetValueToFile(DBHandle db, const char* key, const char* buf, unsigned int len) -{ - char* keyPath = (char *)malloc(MAX_KEY_PATH + 1); - if (keyPath == NULL) { - return DBM_ERROR; - } - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, ItemPathFormat(db), db->dirPath, key) < 0) { - free(keyPath); - return DBM_ERROR; - } - - int fd = UtilsFileOpen(keyPath, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0); - free(keyPath); - if (fd < 0) { - DBM_INFO("SetValueToFile: open key path file fail. fd[%d]", fd); - return DBM_ERROR; - } - int ret = UtilsFileWrite(fd, buf, len); - UtilsFileClose(fd); - fd = -1; - if (ret < 0) { - DBM_INFO("SetValueToFile: write buff to file fail."); - return DBM_ERROR; - } - return DBM_OK; -} - -static int BackupItem(DBHandle db, const KeyItem* item) -{ - if (!item->flag.isValid) { - return DBM_OK; - } - - char bakFile[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(bakFile, MAX_KEY_PATH + 1, "%s_dbm_kv", item->key) < 0) { - return DBM_ERROR; - } - - if (!IsNewItem(db, bakFile) && DeleteValueFromFile(db, bakFile) != DBM_OK) { - DBM_INFO("BackupItem: delete old backup data fail."); - return DBM_ERROR; - } - - if (CopyValueToFile(db, item->key, bakFile) != DBM_OK) { - DBM_INFO("BackupItem: copy to backup data fail. cur db sum[%d]", db->kvItemSum); - DeleteValueFromFile(db, bakFile); - return DBM_ERROR; - } - - char itemFlagByte[1] = {1}; - // offset 2 pos is backup flag - int ret = FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index) + 2, SEEK_SET_FS, itemFlagByte, 1); - if (ret < 0) { - DBM_INFO("BackupItem: set backup valid flag to file fail."); - DeleteValueFromFile(db, bakFile); - return DBM_ERROR; - } - return DBM_OK; -} - -static int InitValue(int index, const void* value, unsigned int len, char* valueContent, unsigned int contentLen) -{ - if (valueContent == NULL || (contentLen < len + KV_SUM_INDEX)) { - return -1; - } - - if (sprintf_s(valueContent, KV_SUM_INDEX, "%d", index) < 0) { - return -1; - } - - errno_t ret = memcpy_s(valueContent + KV_SUM_INDEX, len, value, len); - if (ret != EOK) { - return -1; - } - - return len + KV_SUM_INDEX; -} - -static int InsertKV(DBHandle db, const KeyItem* item, const void* value, unsigned int len) -{ - char* valueContent = (char *)malloc(len + KV_SUM_BLOCK_SIZE); // Avoid stack overflows - if (valueContent == NULL) { - return DBM_ERROR; - } - (void)memset_s(valueContent, len + KV_SUM_BLOCK_SIZE, 0, len + KV_SUM_BLOCK_SIZE); - - int contentLen = InitValue(item->index, value, len, valueContent, len + KV_SUM_BLOCK_SIZE); - if (contentLen < 0) { - free(valueContent); - return DBM_ERROR; - } - - int ret = SetValueToFile(db, item->key, valueContent, contentLen); - free(valueContent); - if (ret != DBM_OK) { - DelItem(db, item); - } - - char itemData[1] = {1}; - int pos = FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index) + 1, SEEK_SET_FS, itemData, 1); - if (pos < 0) { - DBM_INFO("InsertKV: write flag to item fail."); - DelItem(db, item); - return DBM_ERROR; - } - return ret; -} - -static int UpdateKV(DBHandle db, const KeyItem* item, const void* value, unsigned int len) -{ - int ret = BackupItem(db, item); - if (ret != DBM_OK) { - DBM_INFO("UpdateKV backup cur data fail."); - return DBM_ERROR; - } - - char* valueContent = (char *)malloc(len + KV_SUM_BLOCK_SIZE); - if (valueContent == NULL) { - return DBM_ERROR; - } - - (void)memset_s(valueContent, len +KV_SUM_BLOCK_SIZE, 0, len + KV_SUM_BLOCK_SIZE); - - int contentLen = InitValue(item->index, value, len, valueContent, len + KV_SUM_BLOCK_SIZE); - if (contentLen < 0) { - free(valueContent); - DBM_INFO("UpdateKV init value fail."); - return DBM_ERROR; - } - - ret = SetValueToFile(db, item->key, valueContent, contentLen); - free(valueContent); - if (ret != DBM_OK) { - DBM_INFO("UpdateKV write value to file fail."); - RecoverItem(db, item); - return DBM_ERROR; - } - - char itemData[1] = {0}; - // offset 2 pos is backup flag - int pos = FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index) + 2, SEEK_SET_FS, itemData, 1); - if (pos < 0) { - DBM_INFO("UpdateKV set bak file is invalid flag fail."); - return DBM_ERROR; - } - char bakFile[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(bakFile, MAX_KEY_PATH + 1, "%s_dbm_kv", item->key) < 0) { - return DBM_ERROR; - } - - if (!IsNewItem(db, bakFile) && DeleteValueFromFile(db, bakFile) != DBM_OK) { - DBM_INFO("BackupItem: delete old backup data fail."); - return DBM_ERROR; - } - DBM_DEBUG("UpdateKV finish!"); - return DBM_OK; -} - -static int WriteNewItemToSumFile(DBHandle db, const KeyItem* item) -{ - char emptyBuf[2 * KV_SUM_BLOCK_SIZE] = {0}; // item flag and len 2 block size - int ret = FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index), SEEK_SET_FS, - emptyBuf, 2 * KV_SUM_BLOCK_SIZE); - if (ret < 0) { - DBM_INFO("WriteNewItemToSumFile: add new item flag fail."); - return DBM_ERROR; - } - - int strKeyOffset = GetKeyItemOffset(item->index) + 2 * KV_SUM_BLOCK_SIZE; - ret = FileWriteCursor(db->sumFileFd, strKeyOffset, SEEK_SET_FS, item->key, MAX_KEY_LEN); - if (ret < 0) { - DBM_INFO("WriteNewItemToSumFile: add new item key fail."); - return DBM_ERROR; - } - - ret = FileWriteCursor(db->sumFileFd, 0, SEEK_CUR_FS, KV_MAGIC, KV_SUM_BLOCK_SIZE); - if (ret < 0) { - DBM_INFO("WriteNewItemToSumFile: add new item magic fail."); - return DBM_ERROR; - } - return DBM_OK; -} - -static int AddNewDataItem(DBHandle db, KeyItem* item) -{ - int itemIndex = -1; - boolean isNewItem = TRUE; - for (int index = 0; index < db->kvItemSum + 1; ++index) { - char tmpKey[MAX_KEY_LEN + 1] = {0}; - if (itemIndex == -1 && IsDataItemMatched(db, tmpKey, index)) { - itemIndex = index; - } - - if (IsDataItemMatched(db, item->key, index)) { // find in sum file - itemIndex = index; - isNewItem = FALSE; - break; - } - } - - if (isNewItem) { - db->kvItemSum++; - } - - item->index = (itemIndex == -1) ? (db->kvItemSum - 1) : itemIndex; - if (item->index < 0) { - DBM_INFO("AddNewDataItem: item index calcute err [%d][%d].", db->kvItemSum, item->index); - return DBM_ERROR; - } - return WriteNewItemToSumFile(db, item); -} - -static int FindDataItem(DBHandle db, KeyItem* item, boolean kvExisted) -{ - item->index = 0; - if (kvExisted) { - char* keyPath = (char *)malloc(MAX_KEY_PATH + 1); - if (keyPath == NULL) { - return DBM_ERROR; - } - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, ItemPathFormat(db), db->dirPath, item->key) < 0) { - free(keyPath); - return DBM_ERROR; - } - - int fd = UtilsFileOpen(keyPath, O_RDONLY_FS, 0); - free(keyPath); - if (fd < 0) { - DBM_INFO("FindDataItem: open key path fail."); - return DBM_ERROR; - } - - char index[KV_SUM_BLOCK_SIZE] = {0}; - int ret = UtilsFileRead(fd, index, KV_SUM_BLOCK_SIZE); - UtilsFileClose(fd); - fd = -1; - item->index = (ret < 0) ? 0 : atoi(index); - if (IsDataItemMatched(db, item->key, item->index)) { // no need read flag, it has been checkpoint - DBM_INFO("find data in sum file, index[%d]", item->index); - return DBM_OK; - } - } - return AddNewDataItem(db, item); -} - -static int PrePut(DBHandle db, KeyItem* item, boolean* newItem) -{ - int ret = FindDataItem(db, item, !*newItem); - if (ret != DBM_OK) { - DBM_INFO("Put: find data item fail."); - return DBM_ERROR; - } - - ret = LoadDataItem(db, item->index, item); - if (ret != DBM_OK) { - DBM_INFO("Put: load data item fail."); - return DBM_ERROR; - } - - if (!*newItem) { // new item not need clean - ret = CheckPointItem(db, item); - if (ret != DBM_OK) { - DBM_INFO("Put: load data item fail ret[%d].", ret); - return DBM_ERROR; - } - // for last time key open but set flag fail or set delete flag but not delete the file - if (db->sumFlag.isInvalid || !item->flag.isValid) { - ret = WriteNewItemToSumFile(db, item); - if (ret != DBM_OK) { - return ret; - } - *newItem = TRUE; // cur item had been deleted - } - } - return DBM_OK; -} - -static int Put(KVStoreHandle db, const char* key, const void* value, unsigned int len) -{ - if (!IsValidKey(key) || (value == NULL) || (len > MAX_VALUE_LEN) || len <= 0 || db == NULL) { - return DBM_INVALID_ARGS; - } - - if (!db->initOK || !IsStrSame(db->magic, KV_MAGIC_SIZE + 1, KV_MAGIC)) { - return DBM_INVALID_ARGS; - } - - boolean newItem = IsNewItem(db, key); - if ((db->kvItemSum >= DBM_MAX_KV_SUM) && newItem) { - DBM_INFO("Put: over max limits."); - return DBM_OVER_MAX_LIMITS; - } - - KeyItem* item = (KeyItem *)malloc(sizeof(KeyItem)); - if (item == NULL) { - return DBM_ERROR; - } - - (void)memset_s(item, sizeof(KeyItem), 0, sizeof(KeyItem)); - if (strcpy_s(item->key, MAX_KEY_LEN + 1, key) != EOK) { - free(item); - return DBM_ERROR; - } - - item->len = strlen(key); - - int ret = PrePut(db, item, &newItem); - if (ret != DBM_OK) { - free(item); - DBM_INFO("Put: load data item fail."); - return DBM_ERROR; - } - - if (newItem) { - ret = InsertKV(db, item, value, len); - } else { - ret = UpdateKV(db, item, value, len); - } - - DBM_INFO("PUT index[%d] finish err[%d].", item->index, ret); - free(item); - return ret; -} - -int DBM_Put(KVStoreHandle db, const char* key, const void* value, unsigned int len) -{ - if (db == NULL) { - return DBM_INVALID_ARGS; - } - /* lock the KVDB */ - DB_LOCK(db); - int ret = Put(db, key, value, len); - DB_UNLOCK(db); - return ret; -} - -static int ExeDelete(KVStoreHandle db, const KeyItem* item, boolean newItem) -{ - char itemData[KV_SUM_DATA_ITEM_SIZE] = {0}; - int ret = FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index) + 1, SEEK_SET_FS, itemData, 1); - db->kvItemSum--; - if (ret < 0) { - DBM_INFO("Delete: set data item delete flag fail. item[%s] index[%d]", item->key, item->index); - return DBM_ERROR; - } - - if (!newItem && DeleteValueFromFile(db, item->key) != DBM_OK) { - return DBM_ERROR; - } - - char bakKey[MAX_FILE_PATH] = {0}; - if (sprintf_s(bakKey, MAX_FILE_PATH, "%s_dbm_kv", item->key) < 0) { - return DBM_ERROR; - } - - if (!IsNewItem(db, bakKey)) { - (void)DeleteValueFromFile(db, bakKey); - } - (void)FileWriteCursor(db->sumFileFd, GetKeyItemOffset(item->index), SEEK_SET_FS, - itemData, KV_SUM_DATA_ITEM_SIZE - KV_MAGIC_SIZE); - return DBM_OK; -} - -static int Delete(KVStoreHandle db, const char* key) -{ - if (!IsValidKey(key) || db == NULL) { - return DBM_INVALID_ARGS; - } - - if (!db->initOK || !IsStrSame(db->magic, KV_MAGIC_SIZE + 1, KV_MAGIC)) { - return DBM_INVALID_ARGS; - } - - boolean newItem = IsNewItem(db, key); - if (newItem) { - return DBM_OK; - } - - KeyItem* item = (KeyItem *)malloc(sizeof(KeyItem)); - if (item == NULL) { - return DBM_ERROR; - } - (void)memset_s(item, sizeof(KeyItem), 0, sizeof(KeyItem)); - if (strcpy_s(item->key, MAX_KEY_LEN + 1, key) != EOK) { - free(item); - return DBM_ERROR; - } - item->len = strlen(key); - - int ret = FindDataItem(db, item, !newItem); - if (ret != DBM_OK) { - DBM_INFO("Delete: find data item fail. item[%s]", item->key); - free(item); - return DBM_ERROR; - } - - ret = ExeDelete(db, item, newItem); - free(item); - return ret; -} - -int DBM_Delete(KVStoreHandle db, const char* key) -{ - if (db == NULL) { - return DBM_INVALID_ARGS; - } - /* lock the KVDB */ - DB_LOCK(db); - int ret = Delete(db, key); - DB_UNLOCK(db); - DBM_DEBUG("Delete: key[%s] ret[%d]", key, ret); - return ret; -} - -static int CloseKVStore(KVStoreHandle db) -{ - if (!db->initOK || !IsStrSame(db->magic, KV_MAGIC_SIZE + 1, KV_MAGIC)) { - return DBM_INVALID_ARGS; - } - - int ret = SetSumIndexToFile(db, db->kvItemSum); - if (ret != DBM_OK) { - DBM_INFO("Write sum index to file fail."); // also need free resource - } - - ret = UtilsFileClose(db->sumFileFd); - if (ret < 0) { - return DBM_ERROR; - } - db->sumFileFd = -1; - return DBM_OK; -} - -int DBM_CloseKVStore(KVStoreHandle db) -{ - if (db == NULL) { - return DBM_OK; - } - - /* lock the KVDB */ - DB_LOCK(db); - int ret = CloseKVStore(db); - DB_UNLOCK(db); - - ReleaseKVDBHandle(db); - DBM_DEBUG("FInish Get KV store ret[%d].", ret); - return ret; -} - -static int DelSumFile(DBHandle db) -{ - char* sumFilePath = (char *)malloc(MAX_KEY_PATH + 1); - if (sumFilePath == NULL) { - return DBM_ERROR; - } - - (void)memset_s(sumFilePath, MAX_FILE_PATH + 1, 0, MAX_FILE_PATH + 1); - int ret = GetSumFilePath(db, sumFilePath, MAX_FILE_PATH + 1); - if (ret != DBM_OK) { - free(sumFilePath); - return DBM_ERROR; - } - - ret = UtilsFileClose(db->sumFileFd); - if (ret < 0) { - free(sumFilePath); - return DBM_ERROR; - } - db->sumFileFd = -1; - - ret = UtilsFileDelete(sumFilePath); - free(sumFilePath); - if (ret < 0) { - return DBM_ERROR; - } - return DBM_OK; -} - -static int RemoveKVStoreFile(DBHandle db, int sumFileLen) -{ - char flag[KV_SUM_BLOCK_SIZE + 1] = {0}; - (void)memset_s(flag, KV_SUM_BLOCK_SIZE, 1, KV_SUM_BLOCK_SIZE); - int ret = FileWriteCursor(db->sumFileFd, KV_SUM_INDEX + KV_SUM_BLOCK_SIZE, SEEK_SET_FS, flag, KV_SUM_BLOCK_SIZE); - if (ret < 0) { // ret is fd offset - DBM_INFO("RemoveKVStoreFile: write sum file delete all flag fail."); - return DBM_ERROR; - } - - if (sumFileLen > 0) { - ret = LoadSumFileHeader(db); - if (ret != DBM_OK) { - DBM_INFO("RemoveKVStoreFile: Load sum file header flag fail."); - return DBM_ERROR; - } - - ret = VacuumStore(db); - if (ret != DBM_OK) { - DBM_INFO("RemoveKVStoreFile: vacuum database fail."); - return DBM_ERROR; - } - } - return DelSumFile(db); -} - -int DBM_DeleteKVStore(const char* storeFullPath) -{ - DBM_INFO("Delete kv store start."); - if (!IsValidPath(storeFullPath)) { - DBM_INFO("Get KVStore invalid path."); - return DBM_INVALID_ARGS; - } - - DBHandle db = GetKVDBHandle(storeFullPath); - if (db == NULL) { - return DBM_ERROR; - } - - db->sumFileFd = OpenSumFile(db, O_RDWR_FS); - if (db->sumFileFd < 0) { - DBM_INFO("DeleteKVStore: open sum file fail."); - ReleaseKVDBHandle(db); - return DBM_NOT_FOUND; - } - - int sumFileLen = UtilsFileSeek(db->sumFileFd, 0UL, SEEK_END_FS); - if (sumFileLen < 0) { - DBM_INFO("DeleteKVStore: Get sum file length fail."); - ReleaseKVDBHandle(db); - return DBM_ERROR; - } - - // Is need this version or corrupt - if ((sumFileLen < SUM_FILE_HEADER_SIZE) && (sumFileLen != 0) && (sumFileLen != KV_SUM_INDEX)) { - DBM_INFO("sum file invalid length!"); - ReleaseKVDBHandle(db); - return DBM_ERROR; - } - - int ret = RemoveKVStoreFile(db, sumFileLen); - ReleaseKVDBHandle(db); - DBM_INFO("Delete kv store complete[%d].", ret); - return ret; -} - -void DBM_KVStoreControl(KVStoreHandle db, int cmd, void* arg) -{ - if (db == NULL) { - return; - } - - switch (cmd) { - case DBM_CTRL_SET_LOCK: - db->lock = (void (*)(KVStoreHandle db))arg; - break; - case DBM_CTRL_SET_UNLOCK: - db->unlock = (void (*)(KVStoreHandle db))arg; - break; - default: - break; - } -} - -int DBM_UserInit(void) -{ - return 0; -} diff --git a/kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_posix/dbm_kv_store.c b/kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_posix/dbm_kv_store.c deleted file mode 100644 index 412f8c25a..000000000 --- a/kv_store/frameworks/native/dbm_kv_store/src/kv_store_impl_posix/dbm_kv_store.c +++ /dev/null @@ -1,54 +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. - */ - -/* This function is not open for user now */ -#include "dbm_kv_store.h" - -#include "dbm_errno.h" - -#ifdef DBM_DEBUG_ENABLE -#define DBM_LOG_TAG "[low_posix][kv]" -#endif - -int DBM_GetKVStore(const char* storeFullPath, KVStoreHandle* db) -{ - return DBM_NOT_SUPPORT; -} - -int DBM_Get(KVStoreHandle db, const char* key, void* value, unsigned int count, unsigned int* realValueLen) -{ - return DBM_NOT_SUPPORT; -} -int DBM_Put(KVStoreHandle db, const char* key, const void* value, unsigned int len) -{ - return DBM_NOT_SUPPORT; -} -int DBM_Delete(KVStoreHandle db, const char* key) -{ - return DBM_NOT_SUPPORT; -} - -int DBM_CloseKVStore(KVStoreHandle db) -{ - return DBM_NOT_SUPPORT; -} -int DBM_DeleteKVStore(const char* storeFullPath) -{ - return DBM_NOT_SUPPORT; -} - -void DBM_KVStoreControl(KVStoreHandle db, int cmd, void* arg) -{ -} \ No newline at end of file diff --git a/kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.c b/kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.c deleted file mode 100644 index 86147d53e..000000000 --- a/kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.c +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2020 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 "kvstore_common.h" -#include -#include -#include -#include "ohos_errno.h" - -#ifdef FEATURE_KV_CACHE -static KvItem* g_itemHeader = NULL; -static KvItem* g_itemTail = NULL; -static int g_sum = 0; -#endif - -boolean IsValidChar(const char ch) -{ - if (islower(ch) || isdigit(ch) || (ch == '_') || (ch == '.')) { - return TRUE; - } - return FALSE; -} - -boolean IsValidValue(const char* value, unsigned int len) -{ - if (value == NULL) { - return FALSE; - } - size_t valueLen = strnlen(value, MAX_VALUE_LEN); - if ((valueLen == 0) || (valueLen >= MAX_VALUE_LEN) || (valueLen >= len)) { - return FALSE; - } - return TRUE; -} - -boolean IsValidKey(const char* key) -{ - if (!IsValidValue(key, MAX_KEY_LEN)) { - return FALSE; - } - size_t keyLen = strnlen(key, MAX_KEY_LEN); - for (size_t i = 0; i < keyLen; i++) { - if (!IsValidChar(key[i])) { - return FALSE; - } - } - return TRUE; -} - -#ifdef FEATURE_KV_CACHE -static void FreeItem(KvItem* item) -{ - if (item == NULL) { - return; - } - if (item->key != NULL) { - free(item->key); - } - if (item->value != NULL) { - free(item->value); - } - free(item); -} - -void DeleteKVCache(const char* key) -{ - if (key == NULL || g_itemHeader == NULL) { - return; - } - - KvItem* item = g_itemHeader; - while (strcmp(key, item->key) != 0) { - item = item->next; - if (item == NULL) { - return; - } - } - g_sum--; - if (g_sum == 0) { - g_itemHeader = NULL; - g_itemTail = NULL; - } else if (item == g_itemHeader) { - g_itemHeader = item->next; - g_itemHeader->prev = NULL; - } else if (item == g_itemTail) { - g_itemTail = item->prev; - g_itemTail->next = NULL; - } else { - item->prev->next = item->next; - item->next->prev = item->prev; - } - FreeItem(item); -} - -void AddKVCache(const char* key, const char* value, boolean isNew) -{ - if (key == NULL || value == NULL) { - return; - } - - size_t keyLen = strnlen(key, MAX_KEY_LEN); - size_t valueLen = strnlen(value, MAX_VALUE_LEN); - if ((keyLen >= MAX_KEY_LEN) || (valueLen >= MAX_VALUE_LEN)) { - return; - } - if (isNew) { - DeleteKVCache(key); - } - KvItem* item = (KvItem *)malloc(sizeof(KvItem)); - if (item == NULL) { - return; - } - (void)memset_s(item, sizeof(KvItem), 0, sizeof(KvItem)); - item->key = (char *)malloc(keyLen + 1); - item->value = (char *)malloc(valueLen + 1); - if ((item->key == NULL) || (item->value == NULL)) { - FreeItem(item); - return; - } - if ((strcpy_s(item->key, keyLen + 1, key) != EOK) || - (strcpy_s(item->value, valueLen + 1, value) != EOK)) { - FreeItem(item); - return; - } - item->prev = NULL; - item->next = NULL; - if (g_itemHeader == NULL) { - g_itemHeader = item; - g_itemTail = item; - g_sum++; - return; - } - item->next = g_itemHeader; - g_itemHeader->prev = item; - g_itemHeader = item; - g_sum++; - while (g_sum > MAX_CACHE_SIZE) { - KvItem* needDel = g_itemTail; - g_itemTail = g_itemTail->prev; - FreeItem(needDel); - g_itemTail->next = NULL; - g_sum--; - } -} - -int GetValueByCache(const char* key, char* value, unsigned int maxLen) -{ - if (key == NULL || value == NULL || g_itemHeader == NULL) { - return EC_FAILURE; - } - - KvItem* item = g_itemHeader; - while (strcmp(key, item->key) != 0) { - item = item->next; - if (item == NULL) { - return EC_FAILURE; - } - } - size_t valueLen = strnlen(item->value, MAX_VALUE_LEN); - if (valueLen >= MAX_VALUE_LEN) { - return EC_FAILURE; - } - if ((valueLen >= maxLen) || (strcpy_s(value, maxLen, item->value) != EOK)) { - return EC_FAILURE; - } - return EC_SUCCESS; -} - -int ClearKVCacheInner(void) -{ - if (g_itemHeader == NULL) { - return EC_SUCCESS; - } - KvItem* item = g_itemHeader; - while (item != NULL) { - KvItem* temp = item; - item = item->next; - FreeItem(temp); - g_sum--; - } - g_itemHeader = NULL; - g_itemTail = NULL; - - return (g_sum != 0) ? EC_FAILURE : EC_SUCCESS; -} -#endif \ No newline at end of file diff --git a/kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.h b/kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.h deleted file mode 100644 index 251b455f7..000000000 --- a/kv_store/frameworks/native/kv_store/src/kvstore_common/kvstore_common.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2020 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 KV_STORE_COMMON_H -#define KV_STORE_COMMON_H - -#include "ohos_types.h" -#include "utils_config.h" - -#define MAX_KEY_LEN 32 -#define MAX_VALUE_LEN 128 - -boolean IsValidChar(const char ch); -boolean IsValidValue(const char* value, unsigned int len); -boolean IsValidKey(const char* key); - -#ifdef FEATURE_KV_CACHE -typedef struct KvItem_ { - char* key; - char* value; - struct KvItem_* next; - struct KvItem_* prev; -} KvItem; - -void DeleteKVCache(const char* key); -void AddKVCache(const char* key, const char* value, boolean isNew); -int GetValueByCache(const char* key, char* value, unsigned int maxLen); -int ClearKVCacheInner(void); -#endif - -#endif // KV_STORE_COMMON_H \ No newline at end of file diff --git a/kv_store/frameworks/native/kv_store/src/kvstore_impl_hal/kv_store.c b/kv_store/frameworks/native/kv_store/src/kvstore_impl_hal/kv_store.c deleted file mode 100644 index b1d9fe5ec..000000000 --- a/kv_store/frameworks/native/kv_store/src/kvstore_impl_hal/kv_store.c +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2020 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 "kv_store.h" -#include -#include -#include -#include "kvstore_common.h" -#include "ohos_errno.h" -#include "ohos_types.h" -#include "utils_config.h" -#include "utils_file.h" - -#define MAX_GET_VALUE_LEN 0x7FFFFFFF -#define KV_SUM_FILE "KV_FILE_SUM" -#define KV_SUM_INDEX 4 - -static int GetValueByFile(const char* key, char* value, unsigned int len) -{ - unsigned int valueLen = 0; - if (UtilsFileStat(key, &valueLen) != EC_SUCCESS) { - return EC_FAILURE; - } - if (valueLen >= len) { - return EC_FAILURE; - } - int fd = UtilsFileOpen(key, O_RDONLY_FS, 0); - if (fd < 0) { - return EC_FAILURE; - } - int ret = UtilsFileRead(fd, value, valueLen); - UtilsFileClose(fd); - fd = -1; - if (ret < 0) { - return EC_FAILURE; - } - value[valueLen] = '\0'; - return valueLen; -} - -static int SetValueToFile(const char* key, const char* value) -{ - int fd = UtilsFileOpen(key, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0); - if (fd < 0) { - return EC_FAILURE; - } - int ret = UtilsFileWrite(fd, value, strlen(value)); - UtilsFileClose(fd); - fd = -1; - return (ret < 0) ? EC_FAILURE : EC_SUCCESS; -} - -static int GetCurrentItem(void) -{ - int fd = UtilsFileOpen(KV_SUM_FILE, O_RDWR_FS, 0); - if (fd < 0) { - return 0; - } - char value[KV_SUM_INDEX] = {0}; - int ret = UtilsFileRead(fd, value, KV_SUM_INDEX); - UtilsFileClose(fd); - fd = -1; - return (ret < 0) ? 0 : atoi(value); -} - -static int SetCurrentItem(const int num) -{ - char value[KV_SUM_INDEX] = {0}; - if (sprintf_s(value, KV_SUM_INDEX, "%d", num) < 0) { - return EC_FAILURE; - } - int fd = UtilsFileOpen(KV_SUM_FILE, O_RDWR_FS | O_CREAT_FS, 0); - if (fd < 0) { - return EC_FAILURE; - } - int ret = UtilsFileWrite(fd, value, KV_SUM_INDEX); - UtilsFileClose(fd); - fd = -1; - return (ret < 0) ? EC_FAILURE : EC_SUCCESS; -} - -static boolean NewItem(const char* key) -{ - int fd = UtilsFileOpen(key, O_RDONLY_FS, 0); - if (fd < 0) { - return TRUE; - } - UtilsFileClose(fd); - return FALSE; -} - -int UtilsGetValue(const char* key, char* value, unsigned int len) -{ - if (!IsValidKey(key) || (value == NULL) || (len > MAX_GET_VALUE_LEN)) { - return EC_INVALID; - } -#ifdef FEATURE_KV_CACHE - if (GetValueByCache(key, value, len) == EC_SUCCESS) { - return EC_SUCCESS; - } -#endif - int ret = GetValueByFile(key, value, len); - if (ret < 0) { - return EC_FAILURE; - } -#ifdef FEATURE_KV_CACHE - AddKVCache(key, value, FALSE); -#endif - return ret; -} - -int UtilsSetValue(const char* key, const char* value) -{ - if (!IsValidKey(key) || !IsValidValue(value, MAX_VALUE_LEN)) { - return EC_INVALID; - } - int currentNum = GetCurrentItem(); - boolean newItem = NewItem(key); - if ((currentNum >= MAX_KV_SUM) && newItem) { - return EC_FAILURE; - } - int ret = SetValueToFile(key, value); - if (ret == EC_SUCCESS) { -#ifdef FEATURE_KV_CACHE - AddKVCache(key, value, TRUE); -#endif - if (newItem) { - currentNum++; - } - } - - return SetCurrentItem(currentNum); -} - -int UtilsDeleteValue(const char* key) -{ - if (!IsValidKey(key)) { - return EC_INVALID; - } -#ifdef FEATURE_KV_CACHE - DeleteKVCache(key); -#endif - int ret = UtilsFileDelete(key); - if (ret == EC_SUCCESS) { - ret = SetCurrentItem(GetCurrentItem() - 1); - } - return ret; -} - -#ifdef FEATURE_KV_CACHE -int ClearKVCache(void) -{ - return ClearKVCacheInner(); -} -#endif - -int UtilsSetEnv(const char* path) -{ - return EC_SUCCESS; -} \ No newline at end of file diff --git a/kv_store/frameworks/native/kv_store/src/kvstore_impl_posix/kv_store.c b/kv_store/frameworks/native/kv_store/src/kvstore_impl_posix/kv_store.c deleted file mode 100644 index 24bc57c4e..000000000 --- a/kv_store/frameworks/native/kv_store/src/kvstore_impl_posix/kv_store.c +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2020 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 "kv_store.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "kvstore_common.h" -#include "kvstore_env.h" -#include "ohos_errno.h" -#include "ohos_types.h" -#include "utils_config.h" - -#define KVSTORE_PATH "kvstore" -#define MAX_KEY_PATH 256 -#define MAX_GET_VALUE_LEN 0x7FFFFFFF -static pthread_mutex_t g_kvGlobalMutex = PTHREAD_MUTEX_INITIALIZER; -static int g_kvSum = 0; -static boolean g_getKvSum = FALSE; -static char g_dataPath[MAX_KEY_PATH + 1] = {0}; - -static int GetResolvedPath(const char* dataPath, const char* key, char* resolvedPath, unsigned int len) -{ - char* keyPath = (char *)malloc(MAX_KEY_PATH + 1); - if (keyPath == NULL) { - return EC_FAILURE; - } - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, "%s/%s/%s", dataPath, KVSTORE_PATH, key) < 0) { - free(keyPath); - return EC_FAILURE; - } - if (realpath(keyPath, resolvedPath) != NULL) { - free(keyPath); - return EC_SUCCESS; - } - if (errno == ENOENT) { - if (strncpy_s(resolvedPath, len, keyPath, strlen(keyPath)) == EOK) { - free(keyPath); - return EC_SUCCESS; - } - } - free(keyPath); - return EC_FAILURE; -} - -static int GetValueByFile(const char* dataPath, const char* key, char* value, unsigned int len) -{ - char* keyPath = (char *)malloc(PATH_MAX + 1); - if (keyPath == NULL) { - return EC_FAILURE; - } - if (GetResolvedPath(dataPath, key, keyPath, PATH_MAX + 1) != EC_SUCCESS) { - free(keyPath); - return EC_FAILURE; - } - struct stat info = {0}; - if (stat(keyPath, &info) != F_OK) { - free(keyPath); - return EC_FAILURE; - } - if (info.st_size >= len) { - free(keyPath); - return EC_FAILURE; - } - int fd = open(keyPath, O_RDONLY, S_IRUSR); - free(keyPath); - keyPath = NULL; - if (fd < 0) { - return EC_FAILURE; - } - int ret = read(fd, value, info.st_size); - close(fd); - fd = -1; - if (ret < 0) { - return EC_FAILURE; - } - value[info.st_size] = '\0'; - return info.st_size; -} - -static int SetValueToFile(const char* dataPath, const char* key, const char* value) -{ - char* keyPath = (char *)malloc(PATH_MAX + 1); - if (keyPath == NULL) { - return EC_FAILURE; - } - if (GetResolvedPath(dataPath, key, keyPath, PATH_MAX + 1) != EC_SUCCESS) { - free(keyPath); - return EC_FAILURE; - } - int fd = open(keyPath, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); - free(keyPath); - keyPath = NULL; - if (fd < 0) { - return EC_FAILURE; - } - int ret = write(fd, value, strlen(value)); - close(fd); - fd = -1; - return (ret < 0) ? EC_FAILURE : EC_SUCCESS; -} - -static int DeleteValueFromFile(const char* dataPath, const char* key) -{ - char* keyPath = (char *)malloc(MAX_KEY_PATH + 1); - if (keyPath == NULL) { - return EC_FAILURE; - } - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, "%s/%s/%s", dataPath, KVSTORE_PATH, key) < 0) { - free(keyPath); - return EC_FAILURE; - } - int ret = unlink(keyPath); - free(keyPath); - return ret; -} - -static int InitKv(const char* dataPath) -{ - if (dataPath == NULL) { - return EC_FAILURE; - } - char* kvPath = (char *)malloc(MAX_KEY_PATH + 1); - if (kvPath == NULL) { - return EC_FAILURE; - } - if (sprintf_s(kvPath, MAX_KEY_PATH + 1, "%s/%s", dataPath, KVSTORE_PATH) < 0) { - free(kvPath); - return EC_FAILURE; - } - if (access(kvPath, F_OK) == F_OK) { - free(kvPath); - return EC_SUCCESS; - } - if (mkdir(kvPath, S_IRUSR | S_IWUSR | S_IXUSR) != F_OK) { - free(kvPath); - return EC_FAILURE; - } - free(kvPath); - return EC_SUCCESS; -} - -static int GetCurrentItem(const char* dataPath) -{ - char kvPath[MAX_KEY_PATH + 1] = {0}; - if (sprintf_s(kvPath, MAX_KEY_PATH + 1, "%s/%s", dataPath, KVSTORE_PATH) < 0) { - return EC_FAILURE; - } - DIR* fileDir = opendir(kvPath); - if (fileDir == NULL) { - return EC_FAILURE; - } - struct dirent* dir = readdir(fileDir); - int sum = 0; - while (dir != NULL) { - char fullPath[MAX_KEY_PATH + 1] = {0}; - struct stat info = {0}; - if (sprintf_s(fullPath, MAX_KEY_PATH + 1, "%s/%s", kvPath, dir->d_name) < 0) { - closedir(fileDir); - return EC_FAILURE; - } - if (stat(fullPath, &info) != 0) { - closedir(fileDir); - return EC_FAILURE; - } - if (S_ISREG(info.st_mode)) { - sum++; - } - dir = readdir(fileDir); - } - closedir(fileDir); - return sum; -} - -static boolean NewItem(const char* dataPath, const char* key) -{ - char* keyPath = (char *)malloc(MAX_KEY_PATH + 1); - if (keyPath == NULL) { - return FALSE; - } - if (sprintf_s(keyPath, MAX_KEY_PATH + 1, "%s/%s/%s", dataPath, KVSTORE_PATH, key) < 0) { - free(keyPath); - return FALSE; - } - if (access(keyPath, F_OK) == F_OK) { - free(keyPath); - return FALSE; - } - free(keyPath); - return TRUE; -} - -int UtilsGetValue(const char* key, char* value, unsigned int len) -{ - if (!IsValidKey(key) || (value == NULL) || (len > MAX_GET_VALUE_LEN)) { - return EC_INVALID; - } - pthread_mutex_lock(&g_kvGlobalMutex); - const char* dataPath = g_dataPath; - if (dataPath == NULL) { - pthread_mutex_unlock(&g_kvGlobalMutex); - return EC_FAILURE; - } -#ifdef FEATURE_KV_CACHE - if (GetValueByCache(key, value, len) == EC_SUCCESS) { - pthread_mutex_unlock(&g_kvGlobalMutex); - return EC_SUCCESS; - } -#endif - int ret = GetValueByFile(dataPath, key, value, len); - if (ret < 0) { - pthread_mutex_unlock(&g_kvGlobalMutex); - return EC_FAILURE; - } -#ifdef FEATURE_KV_CACHE - AddKVCache(key, value, FALSE); -#endif - pthread_mutex_unlock(&g_kvGlobalMutex); - return ret; -} - -int UtilsSetValue(const char* key, const char* value) -{ - if (!IsValidKey(key) || !IsValidValue(value, MAX_VALUE_LEN)) { - return EC_INVALID; - } - pthread_mutex_lock(&g_kvGlobalMutex); - const char* dataPath = g_dataPath; - int ret = InitKv(dataPath); - if (ret != EC_SUCCESS) { - g_getKvSum = FALSE; - pthread_mutex_unlock(&g_kvGlobalMutex); - return EC_FAILURE; - } - if (!g_getKvSum) { - g_kvSum = GetCurrentItem(dataPath); - if (g_kvSum < 0) { - pthread_mutex_unlock(&g_kvGlobalMutex); - return EC_FAILURE; - } - g_getKvSum = TRUE; - } - boolean newItem = NewItem(dataPath, key); - if ((g_kvSum >= MAX_KV_SUM) && newItem) { - pthread_mutex_unlock(&g_kvGlobalMutex); - return EC_FAILURE; - } - ret = SetValueToFile(dataPath, key, value); - if (ret == EC_SUCCESS) { -#ifdef FEATURE_KV_CACHE - AddKVCache(key, value, TRUE); -#endif - if (newItem) { - g_kvSum++; - } - } - pthread_mutex_unlock(&g_kvGlobalMutex); - return ret; -} - -int UtilsDeleteValue(const char* key) -{ - if (!IsValidKey(key)) { - return EC_INVALID; - } - pthread_mutex_lock(&g_kvGlobalMutex); - const char* dataPath = g_dataPath; - if (dataPath == NULL) { - pthread_mutex_unlock(&g_kvGlobalMutex); - return EC_FAILURE; - } -#ifdef FEATURE_KV_CACHE - DeleteKVCache(key); -#endif - int ret = DeleteValueFromFile(dataPath, key); - if (ret == EC_SUCCESS) { - g_kvSum--; - } - pthread_mutex_unlock(&g_kvGlobalMutex); - return ret; -} - -#ifdef FEATURE_KV_CACHE -int ClearKVCache(void) -{ - pthread_mutex_lock(&g_kvGlobalMutex); - int ret = ClearKVCacheInner(); - pthread_mutex_unlock(&g_kvGlobalMutex); - return ret; -} -#endif - -int UtilsSetEnv(const char* path) -{ - if (path == NULL) { - return EC_FAILURE; - } - pthread_mutex_lock(&g_kvGlobalMutex); - int ret = strcpy_s(g_dataPath, MAX_KEY_PATH + 1, path); - pthread_mutex_unlock(&g_kvGlobalMutex); - return (ret != EOK) ? EC_FAILURE : EC_SUCCESS; -} \ No newline at end of file diff --git a/kv_store/interfaces/inner_api/dbm_kv_store/BUILD.gn b/kv_store/interfaces/inner_api/dbm_kv_store/BUILD.gn deleted file mode 100644 index 747854edc..000000000 --- a/kv_store/interfaces/inner_api/dbm_kv_store/BUILD.gn +++ /dev/null @@ -1,39 +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("//build/lite/config/component/lite_component.gni") -import("//foundation/distributeddatamgr/kv_store/kv_store.gni") -if (ohos_kernel_type == "liteos_m") { - static_library("foundation_dbm_kv_store") { - sources = [ "${kv_store_native_path}/dbm_kv_store/src/kv_store_impl_hal/dbm_kv_store.c" ] - include_dirs = [ - "${kv_store_api_path}/dbm_kv_store/include", - "inc", - ] - } -} else { - shared_library("foundation_dbm_kv_store") { - cflags = [ "-Wall" ] - cflags_cc = cflags - sources = [ "${kv_store_native_path}/dbm_kv_store/src/kvstore_impl_posix/dbm_kv_store.c" ] - include_dirs = [ - "${kv_store_api_path}/dbm_kv_store/include", - "inc", - ] - public_deps = [ "//third_party/bounds_checking_function:libsec_shared" ] - } -} - -lite_component("dbm_kv_store") { - features = [ ":foundation_dbm_kv_store" ] -} diff --git a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_config.h b/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_config.h deleted file mode 100644 index b2e8aab15..000000000 --- a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_config.h +++ /dev/null @@ -1,54 +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. - */ - -/** - * @addtogroup dbm_config - * @{ - * - * @brief Represents the configuration file of the dbm subsystem. - * - * Vendors can set their desired items in the configuration file. - * - * @since 1.0 - * @version 1.0 - */ - -/** - * @file dbm_config.h - * - * @brief Represents the configuration file of the dbm subsystem. - * - * Vendors can set their desired items in the configuration file. - * - * @since 1.0 - * @version 1.0 - */ - -#ifndef DBM_CONFIG_H -#define DBM_CONFIG_H - -/** - * @brief Indicates the number of data items that can be stored for each application. - * It depends on the remaining capacity limit of the file system. - * It is recommended to be set to 90 percent of the remaining capacity - * - * Default value: 45 - */ -#ifndef DBM_MAX_KV_SUM -#define DBM_MAX_KV_SUM 45 -#endif - -#endif // DBM_CONFIG_H -/** @} */ diff --git a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_errno.h b/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_errno.h deleted file mode 100644 index 49d8b8f91..000000000 --- a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_errno.h +++ /dev/null @@ -1,39 +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 DBM_ERRNO_H -#define DBM_ERRNO_H -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif /* __cpluscplus */ -#endif /* __cpluscplus */ -/* --------------------------------------------------------------------------------------------* - * Defintion of status code. The status codes are refer to > L1 - *-------------------------------------------------------------------------------------------- */ -enum DBLiteStatus { - DBM_ERROR = -1, /* Execution failed */ - DBM_OK = 0, /* OK or No error */ - DBM_NOT_FOUND = 2, /* Data not found */ - DBM_INVALID_ARGS = 3, /* Invalid argument */ - DBM_NOT_SUPPORT = 5, /* unsupported this function */ - DBM_OVER_MAX_LIMITS = 7, /* Over max limits */ -}; - -#ifdef __cplusplus -#if __cplusplus -} -#endif /* __cpluscplus */ -#endif /* __cpluscplus */ -#endif // DBM_ERRNO_H diff --git a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store.h b/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store.h deleted file mode 100644 index 69ec19ccf..000000000 --- a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store.h +++ /dev/null @@ -1,71 +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. - */ - -/** - * @addtogroup dbm_kv_store - * @{ - * - * @brief Provides functions for obtaining, setting, and deleting a key-value pair. - * - * - * Key-value pairs can be permanently stored in the file system. \n - * For details about the number of key-value pairs that can be stored in an application, see {@link DBM_MAX_KV_SUM}. \n - * - * @since 1.0 - * @version 1.0 - */ - -/** - * @file dbm_kv_store.h - * - * @brief Provides functions for obtaining, setting, and deleting a key-value pair. - * Files with a _DBM_KV suffix are system files and should not be used. - * pleals file len and file system limit. - * - * @since 1.0 - * @version 1.0 - */ - -#ifndef DBM_KV_STORE_H -#define DBM_KV_STORE_H - -#include "dbm_config.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif /* __cplusplus */ - -typedef struct DBM *KVStoreHandle; -int DBM_GetKVStore(const char* storeFullPath, KVStoreHandle* kvStore); - -int DBM_Get(KVStoreHandle db, const char* key, void* value, unsigned int count, unsigned int* realValueLen); -int DBM_Put(KVStoreHandle db, const char* key, const void* value, unsigned int len); -int DBM_Delete(KVStoreHandle db, const char* key); - -int DBM_CloseKVStore(KVStoreHandle db); -int DBM_DeleteKVStore(const char* storeFullPath); - -void DBM_KVStoreControl(KVStoreHandle db, int cmd, void* arg); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif /* __cplusplus */ - -#endif // DBM_KV_STORE_H -/** @} */ diff --git a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store_env.h b/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store_env.h deleted file mode 100644 index cec2253a4..000000000 --- a/kv_store/interfaces/inner_api/dbm_kv_store/include/dbm_kv_store_env.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 DBM_KV_STORE_ENV_H -#define DBM_KV_STORE_ENV_H - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif /* __cplusplus */ - -__attribute__((weak)) int DBM_UserInit(void); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif /* __cplusplus */ - -#endif // DBM_KV_STORE_ENV_H diff --git a/kv_store/interfaces/inner_api/kv_store/BUILD.gn b/kv_store/interfaces/inner_api/kv_store/BUILD.gn deleted file mode 100644 index 5ce8a5bca..000000000 --- a/kv_store/interfaces/inner_api/kv_store/BUILD.gn +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (c) 2020 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/lite/config/component/lite_component.gni") -import("//foundation/distributeddatamgr/kv_store/kv_store.gni") - -declare_args() { - enable_ohos_utils_native_lite_kv_store_use_posix_kv_api = true -} - -if (ohos_kernel_type == "liteos_m") { - static_library("utils_kv_store") { - sources = [ - "${kv_store_native_path}/kv_store/src/kvstore_common/kvstore_common.c", - ] - if (enable_ohos_utils_native_lite_kv_store_use_posix_kv_api) { - sources += [ - "${kv_store_native_path}/kv_store/src/kvstore_impl_posix/kv_store.c", - ] - } else { - sources += - [ "${kv_store_native_path}/kv_store/src/kvstore_impl_hal/kv_store.c" ] - } - include_dirs = [ - "//utils/native/lite/include", - "${kv_store_native_path}/kv_store/src/kvstore_common", - "${kv_store_api_path}/kv_store/include", - ] - } -} else { - shared_library("utils_kv_store") { - cflags = [ "-Wall" ] - cflags_cc = cflags - sources = [ - "${kv_store_native_path}/kv_store/src/kvstore_common/kvstore_common.c", - "${kv_store_native_path}/kv_store/src/kvstore_impl_posix/kv_store.c", - ] - include_dirs = [ - "//utils/native/lite/include", - "${kv_store_native_path}/kv_store/src/kvstore_common", - "//third_party/bounds_checking_function/include", - "${kv_store_api_path}/kv_store/include", - ] - public_deps = [ "//third_party/bounds_checking_function:libsec_shared" ] - } -} - -lite_component("kv_store") { - features = [ ":utils_kv_store" ] -} diff --git a/kv_store/interfaces/inner_api/kv_store/include/kvstore_env.h b/kv_store/interfaces/inner_api/kv_store/include/kvstore_env.h deleted file mode 100644 index 2b076f35b..000000000 --- a/kv_store/interfaces/inner_api/kv_store/include/kvstore_env.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2020 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 KV_STORE_ENV_API_H -#define KV_STORE_ENV_API_H - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif /* __cplusplus */ - -int UtilsSetEnv(const char* path); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif /* __cplusplus */ - -#endif // KV_STORE_ENV_API_H \ No newline at end of file diff --git a/kv_store/kv_store.gni b/kv_store/kv_store.gni deleted file mode 100644 index 0250a1d90..000000000 --- a/kv_store/kv_store.gni +++ /dev/null @@ -1,18 +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. - -kv_store_base_path = "//foundation/distributeddatamgr/kv_store" - -kv_store_native_path = "${kv_store_base_path}/frameworks/native" - -kv_store_api_path = "${kv_store_base_path}/interfaces/inner_api" diff --git a/preferences/README_zh.md b/preferences/README_zh.md deleted file mode 100644 index 100d944de..000000000 --- a/preferences/README_zh.md +++ /dev/null @@ -1,55 +0,0 @@ -# 首选项(Preferences) - -## 简介 - -**首选项(Preferences)** 主要提供轻量级Key-Value操作,支持本地应用存储少量数据,数据存储在本地文件中,同时也加载在内存中,所以访问速度更快,效率更高。首选项提供非关系型数据存储,不宜存储大量数据,经常用于操作键值对形式数据的场景。 - -1. 本模块提供首选项的操作类,应用通过这些操作类完成首选项操作。 -2. 借助getPreferences,可以将指定文件的内容加载到Preferences实例,每个文件最多有一个Preferences实例,系统会通过静态容器将该实例存储在内存中,直到主动从内存中移除该实例或者删除该文件。 -3. 获取Preferences实例后,可以借助Preferences类的函数,从Preferences实例中读取数据或者将数据写入Preferences实例,通过flush将Preferences实例持久化。 - -以下是几个基本概念: - -- **Key-Value数据库** - - 一种以键值对存储数据的一种数据库。Key是关键字,Value是值。 - -- **非关系型数据库** - - 区别于关系数据库,不保证遵循ACID(Atomic、Consistency、Isolation及Durability)特性,不采用关系模型来组织数据,数据之间无关系,扩展性好。 - -- **偏好数据** - - 用户经常访问和使用的数据。 - -**图 2** 首选项运行机制 - -![](figures/zh-cn_首选项运行机制.png) - -## 目录 - -``` -//foundation/distributeddatamgr/preferences -├── frameworks # 框架层代码 -│ └── js # JS API的实现 -│ │ └── napi # napi代码实现 -│ └── native # 内部接口实现 -├── interfaces # 接口代码 -│ └── inner_api # 内部接口声明 -└── test # 测试用例 - ├── js # js用例 - └── native # C++用例 -``` -## 约束 - -- Key键为String类型,要求非空且长度不超过80个字符。 - -- 如果Value值为String类型,可以为空但是长度不超过8192个字符。 - -- 存储的数据量应该是轻量级的,建议存储的数据不超过一万条,否则会在内存方面产生较大的开销。 - -## 相关仓 - -- [分布式数据管理子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%88%86%E5%B8%83%E5%BC%8F%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md) - -- [**distributeddatamgr\_preferences**](https://gitee.com/openharmony/distributeddatamgr_preferences/blob/master/README_zh.md) \ No newline at end of file diff --git a/preferences/bundle.json b/preferences/bundle.json deleted file mode 100644 index b02554e3a..000000000 --- a/preferences/bundle.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "name": "@ohos/distributeddatamgr_preferences", - "version": "3.1.0", - "description": "Local Data Management", - "homePage": "https://gitee.com/openharmony", - "license": "Apache V2", - "repository": "https://gitee.com/openharmony/distributeddatamgr_preferences", - "domain": "os", - "language": "", - "publishAs": "code-segment", - "private": false, - "scripts": {}, - "tags": [ - "foundation" - ], - "keywords": [ - "distributeddatamgr", - "preferences" - ], - "envs": [], - "dirs": {}, - "author": { - "name": "", - "email": "", - "url": "" - }, - "contributors": [ - { - "name": "", - "email": "", - "url": "" - } - ], - "segment": { - "destPath": "foundation/distributeddatamgr/preferences" - }, - "component": { - "name": "preferences", - "subsystem": "distributeddatamgr", - "syscap": [ - "SystemCapability.DistributedDataManager.Preferences.Core" - ], - "features": [], - "adapted_system_type": [ - "standard" - ], - "rom": "", - "ram": "", - "deps": { - "components": [ - "ability_runtime", - "napi", - "hilog_native", - "ipc", - "utils_base", - "ability_base" - ], - "third_party": [ - "libxml2", - "gtest_main" - ] - }, - "build": { - "sub_component": [ - "//foundation/distributeddatamgr/preferences/interfaces/inner_api:native_preferences", - "//foundation/distributeddatamgr/preferences/frameworks/js/napi:preferences", - "//foundation/distributeddatamgr/preferences/frameworks/js/napi:storage", - "//foundation/distributeddatamgr/preferences/frameworks/js/napi:storage_napi" - ], - "inner_kits": [ - { - "name": "//foundation/distributeddatamgr/preferences/interfaces/inner_api:native_preferences", - "header": { - "header_files": [ - "preferences.h", - "preferences_observer.h", - "preferences_helper.h", - "preferences_errno.h", - "preferences_xml_utils.h", - "preferences_value.h" - ], - "header_base": "//foundation/distributeddatamgr/preferences/interfaces/inner_api/include" - } - } - ], - "test": [ - "//foundation/distributeddatamgr/preferences/test/native:unittest", - "//foundation/distributeddatamgr/preferences/test/js:unittest" - ] - } - } -} diff --git a/preferences/figures/en-us_How_the_preferences_database_works.png b/preferences/figures/en-us_How_the_preferences_database_works.png deleted file mode 100644 index f4199c10df74662f6f28da36adc31f04389657fb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 42340 zcmbSycOX^&|9_=Ib}}M_LS+*&3sG5>GBa*M+56(URIZhk$P7iLVO)f3Tyo9KBwXBU zbB*hAjcZ)@`kkxy`~6wpzkYu-?s}c)dA*+F@q9d3ir9 zYZL9y;Wp1tj}9GrzjIUf+Py&AWlB_-KwHpCB3Wzud{yWQa{N@9im{uxF+PjGO*v-z zoY|M@lIc9-n2Yzy9jyZ-JIz+gf<3>f#_HaAy_mfya{g8x`s#Cg@oUdnjvi%yKUcMK zS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s)~jjy0vj;^U6cTs3R7c@ z%r9jwK%EDBJ6$!T|Cf287M=&S$30|&Y8oift+?a=+kO9MpT<3M4h1D(*T~A>=2iK` z11KPkYU6vn2mzGHpA1rYy#Hel$v?DC>SeNS>E0(B_mTYiLr - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "preferences.h" -#include "preferences_helper.h" - -namespace OHOS { -namespace PreferencesJsKit { -class PreferencesProxy { -public: - static void Init(napi_env env, napi_value exports); - static napi_value New(napi_env env, napi_callback_info info); - static napi_status NewInstance(napi_env env, napi_value arg, napi_value *instance); - static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); - -private: - explicit PreferencesProxy(std::shared_ptr &value); - ~PreferencesProxy(); - - static napi_value GetValue(napi_env env, napi_callback_info info); - static napi_value SetValue(napi_env env, napi_callback_info info); - static napi_value HasKey(napi_env env, napi_callback_info info); - static napi_value Delete(napi_env env, napi_callback_info info); - static napi_value Flush(napi_env env, napi_callback_info info); - static napi_value Clear(napi_env env, napi_callback_info info); - static napi_value RegisterObserver(napi_env env, napi_callback_info info); - static napi_value UnRegisterObserver(napi_env env, napi_callback_info info); - static napi_value GetAll(napi_env env, napi_callback_info info); - - std::shared_ptr value_; - napi_env env_; - napi_ref wrapper_; - std::shared_ptr observer_; -}; - -class PreferencesObserverImpl : public OHOS::NativePreferences::PreferencesObserver { -public: - PreferencesObserverImpl(napi_env env, napi_value callback); - virtual ~PreferencesObserverImpl(); - void OnChange(OHOS::NativePreferences::Preferences &preferences, const std::string &key) override; - -private: - napi_env env_; - napi_ref observerRef; -}; -} // namespace PreferencesJsKit -} // namespace OHOS - -#endif // PREFERENCES_JSKIT_NAPI_PREFERENCE_H diff --git a/preferences/frameworks/js/napi/include/napi_preferences_helper.h b/preferences/frameworks/js/napi/include/napi_preferences_helper.h deleted file mode 100644 index 15686d2b1..000000000 --- a/preferences/frameworks/js/napi/include/napi_preferences_helper.h +++ /dev/null @@ -1,27 +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 PREFERENCES_JSKIT_NAPI_PREFERENCE_HELPER_H -#define PREFERENCES_JSKIT_NAPI_PREFERENCE_HELPER_H - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace PreferencesJsKit { -napi_value InitPreferencesHelper(napi_env env, napi_value exports); -} -} // namespace OHOS -#endif // PREFERENCES_JSKIT_NAPI_PREFERENCE_HELPER_H \ No newline at end of file diff --git a/preferences/frameworks/js/napi/include/napi_storage.h b/preferences/frameworks/js/napi/include/napi_storage.h deleted file mode 100644 index 399ab6db0..000000000 --- a/preferences/frameworks/js/napi/include/napi_storage.h +++ /dev/null @@ -1,74 +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 PREFERENCES_JSKIT_NAPI_PREFERENCE_H -#define PREFERENCES_JSKIT_NAPI_PREFERENCE_H - -#include - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "preferences.h" -#include "preferences_helper.h" - -namespace OHOS { -namespace PreferencesJsKit { -class StorageProxy { -public: - static void Init(napi_env env, napi_value exports); - static napi_value New(napi_env env, napi_callback_info info); - static napi_status NewInstance(napi_env env, napi_value arg, napi_value *instance); - static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); - -private: - explicit StorageProxy(std::shared_ptr &value); - ~StorageProxy(); - - static napi_value GetValueSync(napi_env env, napi_callback_info info); - static napi_value GetValue(napi_env env, napi_callback_info info); - static napi_value SetValueSync(napi_env env, napi_callback_info info); - static napi_value SetValue(napi_env env, napi_callback_info info); - static napi_value HasKeySync(napi_env env, napi_callback_info info); - static napi_value HasKey(napi_env env, napi_callback_info info); - static napi_value DeleteSync(napi_env env, napi_callback_info info); - static napi_value Delete(napi_env env, napi_callback_info info); - static napi_value FlushSync(napi_env env, napi_callback_info info); - static napi_value Flush(napi_env env, napi_callback_info info); - static napi_value ClearSync(napi_env env, napi_callback_info info); - static napi_value Clear(napi_env env, napi_callback_info info); - static napi_value RegisterObserver(napi_env env, napi_callback_info info); - static napi_value UnRegisterObserver(napi_env env, napi_callback_info info); - - std::shared_ptr value_; - napi_env env_; - napi_ref wrapper_; - std::shared_ptr observer_; -}; - -class StorageObserverImpl : public OHOS::NativePreferences::PreferencesObserver { -public: - StorageObserverImpl(napi_env env, napi_value callback); - virtual ~StorageObserverImpl(); - void OnChange(OHOS::NativePreferences::Preferences &preferences, const std::string &key) override; - -private: - napi_env env_; - napi_ref observerRef; -}; -} // namespace PreferencesJsKit -} // namespace OHOS - -#endif // PREFERENCES_JSKIT_NAPI_PREFERENCE_H diff --git a/preferences/frameworks/js/napi/include/napi_storage_helper.h b/preferences/frameworks/js/napi/include/napi_storage_helper.h deleted file mode 100644 index a12013337..000000000 --- a/preferences/frameworks/js/napi/include/napi_storage_helper.h +++ /dev/null @@ -1,27 +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 PREFERENCES_JSKIT_NAPI_STORAGE_HELPER_H -#define PREFERENCES_JSKIT_NAPI_STORAGE_HELPER_H - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace PreferencesJsKit { -napi_value InitPreferenceHelper(napi_env env, napi_value exports); -} -} // namespace OHOS -#endif // PREFERENCES_JSKIT_NAPI_PREFERENCE_HELPER_H \ No newline at end of file diff --git a/preferences/frameworks/js/napi/include/napi_system_storage.h b/preferences/frameworks/js/napi/include/napi_system_storage.h deleted file mode 100644 index c1d746eca..000000000 --- a/preferences/frameworks/js/napi/include/napi_system_storage.h +++ /dev/null @@ -1,27 +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 PREFERENCES_JSKIT_NAPI_SYSTEM_STORAGE_H -#define PREFERENCES_JSKIT_NAPI_SYSTEM_STORAGE_H - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace SystemStorageJsKit { -napi_value InitSystemStorage(napi_env env, napi_value exports); -} // namespace SystemStorageJsKit -} // namespace OHOS -#endif // PREFERENCES_JSKIT_NAPI_SYSTEM_STORAGE_H \ No newline at end of file diff --git a/preferences/frameworks/js/napi/src/entry_point.cpp b/preferences/frameworks/js/napi/src/entry_point.cpp deleted file mode 100644 index 31313846c..000000000 --- a/preferences/frameworks/js/napi/src/entry_point.cpp +++ /dev/null @@ -1,51 +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 "napi/native_api.h" -#include "napi/native_node_api.h" -#include "napi_preferences.h" -#include "napi_preferences_helper.h" - -using namespace OHOS::PreferencesJsKit; - -EXTERN_C_START -/* - * function for module exports - */ -static napi_value Init(napi_env env, napi_value exports) -{ - PreferencesProxy::Init(env, exports); - InitPreferencesHelper(env, exports); - - return exports; -} -EXTERN_C_END - -/* - * Module define - */ -static napi_module _module = { .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "data.preferences", - .nm_priv = ((void *)0), - .reserved = { 0 } }; -/* - * Module register function - */ -static __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&_module); -} diff --git a/preferences/frameworks/js/napi/src/entry_point_storage.cpp b/preferences/frameworks/js/napi/src/entry_point_storage.cpp deleted file mode 100644 index e8aa30071..000000000 --- a/preferences/frameworks/js/napi/src/entry_point_storage.cpp +++ /dev/null @@ -1,53 +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 "napi/native_api.h" -#include "napi/native_node_api.h" -#include "napi_storage.h" -#include "napi_storage_helper.h" - -using namespace OHOS::PreferencesJsKit; - -EXTERN_C_START -/* - * function for module exports - */ -static napi_value Init(napi_env env, napi_value exports) -{ - StorageProxy::Init(env, exports); - InitPreferenceHelper(env, exports); - - return exports; -} -EXTERN_C_END - -/* - * Module define - */ -static napi_module _module = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "data.storage", - .nm_priv = ((void *)0), - .reserved = { 0 } -}; -/* - * Module register function - */ -static __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&_module); -} diff --git a/preferences/frameworks/js/napi/src/entry_point_system_storage.cpp b/preferences/frameworks/js/napi/src/entry_point_system_storage.cpp deleted file mode 100644 index c12b835d8..000000000 --- a/preferences/frameworks/js/napi/src/entry_point_system_storage.cpp +++ /dev/null @@ -1,46 +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 "napi/native_api.h" -#include "napi/native_node_api.h" -#include "napi_system_storage.h" - -EXTERN_C_START -/* - * function for module exports - */ -static napi_value Init(napi_env env, napi_value exports) -{ - OHOS::SystemStorageJsKit::InitSystemStorage(env, exports); - return exports; -} -EXTERN_C_END - -/* - * Module define - */ -static napi_module _module = { .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "storage", - .nm_priv = ((void *)0), - .reserved = { 0 } }; -/* - * Module register function - */ -static __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&_module); -} \ No newline at end of file diff --git a/preferences/frameworks/js/napi/src/napi_preferences.cpp b/preferences/frameworks/js/napi/src/napi_preferences.cpp deleted file mode 100644 index f0ca5908a..000000000 --- a/preferences/frameworks/js/napi/src/napi_preferences.cpp +++ /dev/null @@ -1,625 +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 "napi_preferences.h" - -#include - -#include -#include -#include - -#include "js_logger.h" -#include "js_utils.h" -#include "napi_async_proxy.h" -#include "preferences.h" -#include "preferences_errno.h" -#include "preferences_value.h" -#include "securec.h" - -using namespace OHOS::NativePreferences; -using namespace OHOS::AppDataMgrJsKit; - -namespace OHOS { -namespace PreferencesJsKit { -#define MAX_KEY_LENGTH Preferences::MAX_KEY_LENGTH -#define MAX_VALUE_LENGTH Preferences::MAX_VALUE_LENGTH - -struct PreferencesAysncContext : NapiAsyncProxy::AysncContext { - std::string key; - PreferencesValue defValue = PreferencesValue((int)0); - std::map allElements; - bool hasKey; -}; - -static __thread napi_ref constructor_; - -PreferencesProxy::PreferencesProxy(std::shared_ptr &value) - : value_(value), env_(nullptr), wrapper_(nullptr) -{ -} - -PreferencesProxy::~PreferencesProxy() -{ - napi_delete_reference(env_, wrapper_); -} - -void PreferencesProxy::Destructor(napi_env env, void *nativeObject, void *finalize_hint) -{ - PreferencesProxy *obj = static_cast(nativeObject); - delete obj; -} - -void PreferencesProxy::Init(napi_env env, napi_value exports) -{ - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_FUNCTION("put", SetValue), - DECLARE_NAPI_FUNCTION("get", GetValue), - DECLARE_NAPI_FUNCTION("getAll", GetAll), - DECLARE_NAPI_FUNCTION("delete", Delete), - DECLARE_NAPI_FUNCTION("clear", Clear), - DECLARE_NAPI_FUNCTION("has", HasKey), - DECLARE_NAPI_FUNCTION("flush", Flush), - DECLARE_NAPI_FUNCTION("on", RegisterObserver), - DECLARE_NAPI_FUNCTION("off", UnRegisterObserver), - }; - napi_value cons = nullptr; - napi_define_class(env, "Storage", NAPI_AUTO_LENGTH, New, nullptr, - sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons); - - napi_create_reference(env, cons, 1, &constructor_); -} - -napi_status PreferencesProxy::NewInstance(napi_env env, napi_value arg, napi_value *instance) -{ - napi_status status; - - const int argc = 1; - napi_value argv[argc] = { arg }; - - napi_value cons; - status = napi_get_reference_value(env, constructor_, &cons); - if (status != napi_ok) { - return status; - } - - status = napi_new_instance(env, cons, argc, argv, instance); - if (status != napi_ok) { - return status; - } - - return napi_ok; -} - -napi_value PreferencesProxy::New(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_value thiz = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - if (thiz == nullptr) { - LOG_WARN("get this failed"); - return nullptr; - } - - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "input type not string"); - char *path = new char[PATH_MAX]; - size_t pathLen = 0; - napi_status status = napi_get_value_string_utf8(env, args[0], path, PATH_MAX, &pathLen); - if (status != napi_ok) { - LOG_ERROR("get path failed. "); - delete[] path; - return nullptr; - } - // get native object - int errCode = 0; - std::shared_ptr preference = - OHOS::NativePreferences::PreferencesHelper::GetPreferences(path, errCode); - delete[] path; - NAPI_ASSERT(env, preference != nullptr, "failed to call native"); - PreferencesProxy *obj = new PreferencesProxy(preference); - obj->env_ = env; - NAPI_CALL(env, napi_wrap(env, thiz, obj, PreferencesProxy::Destructor, - nullptr, // finalize_hint - &obj->wrapper_)); - return thiz; -} - -template bool CheckNumberType(double input) -{ - if (input > (std::numeric_limits::max)() || input < (std::numeric_limits::min)()) { - return false; - } - return true; -} - -bool IsFloat(double input) -{ - return abs(input - floor(input)) >= 0; // DBL_EPSILON; -} - -void ParseKey(const napi_env &env, const napi_value &arg, PreferencesAysncContext *asyncContext) -{ - // get input key - char key[MAX_KEY_LENGTH] = { 0 }; - size_t keySize = 0; - napi_get_value_string_utf8(env, arg, key, MAX_KEY_LENGTH, &keySize); - asyncContext->key = key; -} - -int32_t ParseDoubleElement(const napi_env &env, const napi_value &jsVal, PreferencesAysncContext *asyncContext) -{ - std::vector array; - if (JSUtils::Convert2DoubleVector(env, jsVal, array) != E_OK) { - LOG_ERROR("ParseDoubleElement Convert2DoubleVector failed"); - return E_ERROR; - } - asyncContext->defValue = array; - return E_OK; -} - -int32_t ParseBoolElement(const napi_env &env, const napi_value &jsVal, PreferencesAysncContext *asyncContext) -{ - std::vector array; - if (JSUtils::Convert2BoolVector(env, jsVal, array) != E_OK) { - LOG_ERROR("ParseBoolElement Convert2BoolVector failed"); - return E_ERROR; - } - asyncContext->defValue = array; - return E_OK; -} - -int32_t ParseStringElement(const napi_env &env, const napi_value &jsVal, PreferencesAysncContext *asyncContext) -{ - std::vector array; - if (JSUtils::Convert2StrVector(env, jsVal, array) != E_OK) { - LOG_ERROR("ParseStringElement Convert2StrVector failed"); - return E_ERROR; - } - asyncContext->defValue = array; - return E_OK; -} - -int32_t ParseObjectElement( - napi_valuetype valueType, const napi_env &env, const napi_value &jsVal, PreferencesAysncContext *asyncContext) -{ - if (valueType == napi_number) { - return ParseDoubleElement(env, jsVal, asyncContext); - } else if (valueType == napi_boolean) { - return ParseBoolElement(env, jsVal, asyncContext); - } else if (valueType == napi_string) { - return ParseStringElement(env, jsVal, asyncContext); - } else { - LOG_ERROR("ParseObjectElement unexpected valueType"); - return E_ERROR; - } -} - -int32_t ParseDefObject(const napi_env &env, const napi_value &jsVal, PreferencesAysncContext *asyncContext) -{ - napi_valuetype valueType = napi_undefined; - uint32_t arrLen = 0; - napi_status status = napi_get_array_length(env, jsVal, &arrLen); - if (status != napi_ok) { - LOG_ERROR("ParseDefObject get array failed, status = %{public}d", status); - return E_ERROR; - } - napi_value flag = nullptr; - status = napi_get_element(env, jsVal, 0, &flag); - if (status != napi_ok) { - LOG_ERROR("ParseDefObject get array element failed, status = %{public}d", status); - return E_ERROR; - } - status = napi_typeof(env, flag, &valueType); - if (status != napi_ok) { - LOG_ERROR("ParseDefObject get array element type failed, status = %{public}d", status); - return E_ERROR; - } - if (ParseObjectElement(valueType, env, jsVal, asyncContext) != E_OK) { - LOG_ERROR("ParseDefObject parse array element failed, status = %{public}d", status); - return E_ERROR; - } - return E_OK; -} - -void ParseDefValue(const napi_env &env, const napi_value &jsVal, PreferencesAysncContext *asyncContext) -{ - napi_valuetype valueType = napi_undefined; - napi_typeof(env, jsVal, &valueType); - if (valueType == napi_number) { - double number = 0.0; - if (JSUtils::Convert2Double(env, jsVal, number) != E_OK) { - LOG_ERROR("ParseDefValue Convert2Double error"); - return; - } - asyncContext->defValue = number; - } else if (valueType == napi_string) { - std::string str; - if (JSUtils::Convert2String(env, jsVal, str) != E_OK) { - LOG_ERROR("ParseDefValue Convert2String error"); - return; - } - asyncContext->defValue = str; - } else if (valueType == napi_boolean) { - bool bValue = false; - if (JSUtils::Convert2Bool(env, jsVal, bValue) != E_OK) { - LOG_ERROR("ParseDefValue Convert2Bool error"); - return; - } - asyncContext->defValue = bValue; - } else if (valueType == napi_object) { - if (ParseDefObject(env, jsVal, asyncContext) != E_OK) { - LOG_ERROR("ParseDefValue::ParseDefObject failed"); - } - } else { - LOG_ERROR("Wrong second parameter type"); - } -} - -int32_t GetAllArr( - const std::string &key, const PreferencesValue &value, PreferencesAysncContext *asyncContext, napi_value &output) -{ - napi_value jsArr = nullptr; - if (value.IsDoubleArray()) { - if (JSUtils::Convert2JSDoubleArr(asyncContext->env, (std::vector)value, jsArr) != E_OK) { - LOG_ERROR("PreferencesProxy::GetAllArr Convert2JSValue failed"); - return ERR; - } - if (napi_set_named_property(asyncContext->env, output, key.c_str(), jsArr) != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAllArr set property doubleArr failed"); - return ERR; - } - } else if (value.IsStringArray()) { - if (JSUtils::Convert2JSStringArr(asyncContext->env, (std::vector)value, jsArr) != E_OK) { - LOG_ERROR("PreferencesProxy::GetAllArr Convert2JSValue failed"); - return ERR; - } - if (napi_set_named_property(asyncContext->env, output, key.c_str(), jsArr) != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAll set property stringArr failed"); - return ERR; - } - } else if (value.IsBoolArray()) { - if (JSUtils::Convert2JSBoolArr(asyncContext->env, (std::vector)value, jsArr) != E_OK) { - LOG_ERROR("PreferencesProxy::GetAllArr Convert2JSValue failed"); - return ERR; - } - - napi_status status = napi_set_named_property(asyncContext->env, output, key.c_str(), jsArr); - if (status != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAll set property boolArr failed, status = %{public}d", status); - return ERR; - } - } - return OK; -} - -int32_t GetAllExecute(PreferencesAysncContext *asyncContext, napi_value &output) -{ - if (napi_create_object(asyncContext->env, &output) != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAll creat object failed"); - return ERR; - } - napi_value jsVal = nullptr; - for (const auto &[key, value] : asyncContext->allElements) { - if (value.IsBool()) { - if (JSUtils::Convert2JSValue(asyncContext->env, (bool)value, jsVal) != E_OK) { - LOG_ERROR("PreferencesProxy::GetAll get property bool failed"); - return ERR; - } - if (napi_set_named_property(asyncContext->env, output, key.c_str(), jsVal) != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAll set property bool failed"); - return ERR; - } - } else if (value.IsDouble()) { - if (JSUtils::Convert2JSValue(asyncContext->env, (double)value, jsVal) != E_OK) { - LOG_ERROR("PreferencesProxy::GetAll get property double failed"); - return ERR; - } - if (napi_set_named_property(asyncContext->env, output, key.c_str(), jsVal) != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAll set property double failed"); - return ERR; - } - } else if (value.IsString()) { - std::string tempStr = (std::string)value; - if (JSUtils::Convert2JSValue(asyncContext->env, (std::string)value, jsVal) != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAll get property string failed"); - return ERR; - } - if (napi_set_named_property(asyncContext->env, output, key.c_str(), jsVal) != napi_ok) { - LOG_ERROR("PreferencesProxy::GetAll set property string failed"); - return ERR; - } - } else { - int errCode = GetAllArr(key, value, asyncContext, output); - if (errCode != OK) { - LOG_ERROR("PreferencesProxy::GetAll set property array failed"); - return ERR; - } - } - } - return OK; -} - -napi_value PreferencesProxy::GetAll(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - proxy.ParseInputs(parsers); - return proxy.DoAsyncWork( - "GetAll", - [](PreferencesAysncContext *asyncContext) { - PreferencesProxy *obj = reinterpret_cast(asyncContext->boundObj); - asyncContext->allElements = obj->value_->GetAll(); - return OK; - }, - GetAllExecute); -} - -int32_t GetArrayValue(PreferencesAysncContext *asyncContext, napi_value &output) -{ - if (asyncContext->defValue.IsDoubleArray()) { - if (JSUtils::Convert2JSDoubleArr(asyncContext->env, (std::vector)asyncContext->defValue, output) - != E_OK) { - LOG_ERROR("GetArrayValue Convert2JSValue get doubleArray failed"); - return E_NAPI_GET_ERROR; - } - } else if (asyncContext->defValue.IsStringArray()) { - if (JSUtils::Convert2JSStringArr(asyncContext->env, (std::vector)asyncContext->defValue, output) - != E_OK) { - LOG_ERROR("GetArrayValue Convert2JSValue get stringArray failed"); - return E_NAPI_GET_ERROR; - } - } else if (asyncContext->defValue.IsBoolArray()) { - std::vector array = asyncContext->defValue; - if (JSUtils::Convert2JSBoolArr(asyncContext->env, (std::vector)asyncContext->defValue, output) != E_OK) { - LOG_ERROR("GetArrayValue Convert2JSValue get boolArray failed"); - return E_NAPI_GET_ERROR; - } - } - return E_OK; -} - -napi_value PreferencesProxy::GetValue(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - parsers.push_back(ParseDefValue); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "GetValue", - [](PreferencesAysncContext *asyncContext) { - int errCode = OK; - PreferencesProxy *obj = reinterpret_cast(asyncContext->boundObj); - asyncContext->defValue = obj->value_->Get(asyncContext->key, asyncContext->defValue); - return errCode; - }, - [](PreferencesAysncContext *asyncContext, napi_value &output) { - int errCode = OK; - if (asyncContext->defValue.IsBool()) { - if (JSUtils::Convert2JSValue(asyncContext->env, (bool)asyncContext->defValue, output) != E_OK) { - LOG_ERROR("PreferencesProxy::GetValue Convert2JSValue boolVal failed"); - errCode = ERR; - } - } else if (asyncContext->defValue.IsString()) { - if (JSUtils::Convert2JSValue(asyncContext->env, (std::string)asyncContext->defValue, output) != E_OK) { - LOG_ERROR("PreferencesProxy::GetValue Convert2JSValue stringVal failed"); - errCode = ERR; - } - } else if (asyncContext->defValue.IsDouble()) { - if (JSUtils::Convert2JSValue(asyncContext->env, (double)asyncContext->defValue, output) != E_OK) { - LOG_ERROR("PreferencesProxy::GetValue Convert2JSValue boolVal failed"); - errCode = ERR; - } - } else if (asyncContext->defValue.IsDoubleArray() || asyncContext->defValue.IsStringArray() - || asyncContext->defValue.IsBoolArray()) { - if (GetArrayValue(asyncContext, output) != E_OK) { - LOG_ERROR("PreferencesProxy::GetValue GetArrayValue failed"); - errCode = ERR; - } - } else { - errCode = ERR; - } - - return errCode; - }); -} - -napi_value PreferencesProxy::SetValue(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - parsers.push_back(ParseDefValue); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "SetValue", - [](PreferencesAysncContext *asyncContext) { - int errCode = ERR; - PreferencesProxy *obj = reinterpret_cast(asyncContext->boundObj); - errCode = obj->value_->Put(asyncContext->key, asyncContext->defValue); - return errCode; - }, - [](PreferencesAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value PreferencesProxy::Delete(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "Delete", - [](PreferencesAysncContext *asyncContext) { - PreferencesProxy *obj = reinterpret_cast(asyncContext->boundObj); - int errCode = obj->value_->Delete(asyncContext->key); - - return errCode; - }, - [](PreferencesAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value PreferencesProxy::HasKey(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "HasKey", - [](PreferencesAysncContext *asyncContext) { - PreferencesProxy *obj = reinterpret_cast(asyncContext->boundObj); - asyncContext->hasKey = obj->value_->HasKey(asyncContext->key); - - return OK; - }, - [](PreferencesAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_boolean(asyncContext->env, asyncContext->hasKey, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value PreferencesProxy::Flush(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "Flush", - [](PreferencesAysncContext *asyncContext) { - PreferencesProxy *obj = reinterpret_cast(asyncContext->boundObj); - return obj->value_->FlushSync(); - }, - [](PreferencesAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value PreferencesProxy::Clear(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "Clear", - [](PreferencesAysncContext *asyncContext) { - PreferencesProxy *obj = reinterpret_cast(asyncContext->boundObj); - return obj->value_->Clear(); - }, - [](PreferencesAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value PreferencesProxy::RegisterObserver(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 2; - napi_value args[2] = { 0 }; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - napi_valuetype type; - NAPI_CALL(env, napi_typeof(env, args[0], &type)); - NAPI_ASSERT(env, type == napi_string, "key not string type"); - - NAPI_CALL(env, napi_typeof(env, args[1], &type)); - NAPI_ASSERT(env, type == napi_function, "observer not function type"); - - PreferencesProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - - // reference save - obj->observer_ = std::make_shared(env, args[1]); - obj->value_->RegisterObserver(obj->observer_); - LOG_DEBUG("RegisterObserver end"); - - return nullptr; -} - -napi_value PreferencesProxy::UnRegisterObserver(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 2; - napi_value args[2] = { 0 }; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - napi_valuetype type; - NAPI_CALL(env, napi_typeof(env, args[0], &type)); - NAPI_ASSERT(env, type == napi_string, "key not string type"); - - NAPI_CALL(env, napi_typeof(env, args[1], &type)); - NAPI_ASSERT(env, type == napi_function, "observer not function type"); - - PreferencesProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - obj->value_->UnRegisterObserver(obj->observer_); - obj->observer_.reset(); - obj->observer_ = nullptr; - LOG_DEBUG("UnRegisterObserver end"); - return nullptr; -} - -PreferencesObserverImpl::PreferencesObserverImpl(napi_env env, napi_value callback) : observerRef(nullptr) -{ - this->env_ = env; - napi_create_reference(env_, callback, 1, &observerRef); -} - -PreferencesObserverImpl::~PreferencesObserverImpl() -{ - napi_delete_reference(env_, observerRef); -} - -void PreferencesObserverImpl::OnChange(Preferences &preferences, const std::string &key) -{ - LOG_DEBUG("OnChange key:%{public}s", key.c_str()); - napi_value callback = nullptr; - napi_value global = nullptr; - napi_value result = nullptr; - napi_value args[1] = { 0 }; - - napi_create_string_utf8(env_, key.c_str(), key.size(), &args[0]); - napi_get_reference_value(env_, observerRef, &callback); - napi_get_global(env_, &global); - - napi_call_function(env_, global, callback, 1, args, &result); - LOG_DEBUG("OnChange key end"); -} -} // namespace PreferencesJsKit -} // namespace OHOS diff --git a/preferences/frameworks/js/napi/src/napi_preferences_helper.cpp b/preferences/frameworks/js/napi/src/napi_preferences_helper.cpp deleted file mode 100644 index b2db27f28..000000000 --- a/preferences/frameworks/js/napi/src/napi_preferences_helper.cpp +++ /dev/null @@ -1,141 +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 "napi_preferences_helper.h" - -#include - -#include - -#include "js_ability.h" -#include "js_logger.h" -#include "js_utils.h" -#include "napi_async_proxy.h" -#include "napi_preferences.h" -#include "preferences_errno.h" -#include "securec.h" - -using namespace OHOS::NativePreferences; -using namespace OHOS::AppDataMgrJsKit; - -namespace OHOS { -namespace PreferencesJsKit { -struct HelperAysncContext : NapiAsyncProxy::AysncContext { - std::string path; - std::shared_ptr context; -}; - -void ParseContext(const napi_env &env, const napi_value &object, HelperAysncContext *asyncContext) -{ - auto context = JSAbility::GetContext(env, object); - NAPI_ASSERT_RETURN_VOID(env, context != nullptr, "ParseContext get context failed."); - asyncContext->context = context; -} - -void ParseName(const napi_env &env, const napi_value &value, HelperAysncContext *asyncContext) -{ - LOG_DEBUG("ParseName start"); - NAPI_ASSERT_RETURN_VOID(env, asyncContext->context != nullptr, "ParseName context is null."); - std::string name = JSUtils::Convert2String(env, value); - NAPI_ASSERT_RETURN_VOID(env, !name.empty(), "Get preferences name empty."); - - size_t pos = name.find_first_of('/'); - NAPI_ASSERT_RETURN_VOID(env, pos == std::string::npos, "A name without path should be input."); - std::string preferencesDir = asyncContext->context->GetPreferencesDir(); - asyncContext->path = preferencesDir.append("/").append(name); - LOG_DEBUG("ParseName: path %{public}s", asyncContext->path.c_str()); -} - -napi_value GetPreferences(napi_env env, napi_callback_info info) -{ - LOG_DEBUG("GetPreferences start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseContext); - parsers.push_back(ParseName); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "GetPreferences", - [](HelperAysncContext *asyncContext) { - int errCode = OK; - OHOS::NativePreferences::PreferencesHelper::GetPreferences(asyncContext->path, errCode); - LOG_DEBUG("GetPreferences return %{public}d", errCode); - return errCode; - }, - [](HelperAysncContext *asyncContext, napi_value &output) { - napi_value path = nullptr; - napi_create_string_utf8(asyncContext->env, asyncContext->path.c_str(), NAPI_AUTO_LENGTH, &path); - auto ret = PreferencesProxy::NewInstance(asyncContext->env, path, &output); - return (ret == napi_ok) ? OK : ERR; - }); -} - -napi_value DeletePreferences(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseContext); - parsers.push_back(ParseName); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "DeletePreferences", - [](HelperAysncContext *asyncContext) { - int errCode = PreferencesHelper::DeletePreferences(asyncContext->path); - LOG_DEBUG("DeletePreferences return %{public}d", errCode); - return errCode; - }, - [](HelperAysncContext *asyncContext, napi_value &output) { - napi_get_undefined(asyncContext->env, &output); - return OK; - }); -} - -napi_value RemovePreferencesFromCache(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseContext); - parsers.push_back(ParseName); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "RemovePreferencesFromCache", - [](HelperAysncContext *asyncContext) { - int errCode = PreferencesHelper::RemovePreferencesFromCache(asyncContext->path); - LOG_DEBUG("RemovePreferencesFromCache return %{public}d", errCode); - return errCode; - }, - [](HelperAysncContext *asyncContext, napi_value &output) { - napi_get_undefined(asyncContext->env, &output); - return OK; - }); -} - -napi_value InitPreferencesHelper(napi_env env, napi_value exports) -{ - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("getPreferences", GetPreferences), - DECLARE_NAPI_FUNCTION("deletePreferences", DeletePreferences), - DECLARE_NAPI_FUNCTION("removePreferencesFromCache", RemovePreferencesFromCache), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); - return exports; -} -} // namespace PreferencesJsKit -} // namespace OHOS diff --git a/preferences/frameworks/js/napi/src/napi_storage.cpp b/preferences/frameworks/js/napi/src/napi_storage.cpp deleted file mode 100644 index 14ce101f1..000000000 --- a/preferences/frameworks/js/napi/src/napi_storage.cpp +++ /dev/null @@ -1,589 +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 "napi_storage.h" - -#include - -#include -#include -#include - -#include "js_logger.h" -#include "napi_async_proxy.h" -#include "preferences.h" -#include "preferences_errno.h" -#include "preferences_value.h" -#include "securec.h" - -using namespace OHOS::NativePreferences; -using namespace OHOS::AppDataMgrJsKit; - -namespace OHOS { -namespace PreferencesJsKit { -#define MAX_KEY_LENGTH Preferences::MAX_KEY_LENGTH -#define MAX_VALUE_LENGTH Preferences::MAX_VALUE_LENGTH - -struct StorageAysncContext : NapiAsyncProxy::AysncContext { - std::string key; - PreferencesValue defValue = PreferencesValue((int)0); - bool hasKey; -}; - -static __thread napi_ref constructor_; - -StorageProxy::StorageProxy(std::shared_ptr &value) - : value_(value), env_(nullptr), wrapper_(nullptr) -{ -} - -StorageProxy::~StorageProxy() -{ - napi_delete_reference(env_, wrapper_); -} - -void StorageProxy::Destructor(napi_env env, void *nativeObject, void *finalize_hint) -{ - StorageProxy *obj = static_cast(nativeObject); - delete obj; -} - -void StorageProxy::Init(napi_env env, napi_value exports) -{ - napi_property_descriptor descriptors[] = { - DECLARE_NAPI_FUNCTION("putSync", SetValueSync), DECLARE_NAPI_FUNCTION("put", SetValue), - DECLARE_NAPI_FUNCTION("getSync", GetValueSync), DECLARE_NAPI_FUNCTION("get", GetValue), - DECLARE_NAPI_FUNCTION("deleteSync", DeleteSync), DECLARE_NAPI_FUNCTION("delete", Delete), - DECLARE_NAPI_FUNCTION("clearSync", ClearSync), DECLARE_NAPI_FUNCTION("clear", Clear), - DECLARE_NAPI_FUNCTION("hasSync", HasKeySync), DECLARE_NAPI_FUNCTION("has", HasKey), - DECLARE_NAPI_FUNCTION("flushSync", FlushSync), DECLARE_NAPI_FUNCTION("flush", Flush), - DECLARE_NAPI_FUNCTION("on", RegisterObserver), DECLARE_NAPI_FUNCTION("off", UnRegisterObserver), - }; - napi_value cons = nullptr; - napi_define_class(env, "Storage", NAPI_AUTO_LENGTH, New, nullptr, - sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons); - - napi_create_reference(env, cons, 1, &constructor_); -} - -napi_status StorageProxy::NewInstance(napi_env env, napi_value arg, napi_value *instance) -{ - napi_status status; - - const int argc = 1; - napi_value argv[argc] = { arg }; - - napi_value cons; - status = napi_get_reference_value(env, constructor_, &cons); - if (status != napi_ok) { - return status; - } - - status = napi_new_instance(env, cons, argc, argv, instance); - if (status != napi_ok) { - return status; - } - - return napi_ok; -} - -napi_value StorageProxy::New(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_value thiz = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - if (thiz == nullptr) { - LOG_WARN("get this failed"); - return nullptr; - } - - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "input type not string"); - char *path = new char[PATH_MAX]; - size_t pathLen = 0; - napi_status status = napi_get_value_string_utf8(env, args[0], path, PATH_MAX, &pathLen); - if (status != napi_ok) { - LOG_ERROR("get path failed. "); - delete[] path; - return nullptr; - } - // get native object - int errCode = 0; - std::shared_ptr preference = - OHOS::NativePreferences::PreferencesHelper::GetPreferences(path, errCode); - delete[] path; - NAPI_ASSERT(env, preference != nullptr, "failed to call native"); - StorageProxy *obj = new StorageProxy(preference); - obj->env_ = env; - NAPI_CALL(env, napi_wrap(env, thiz, obj, StorageProxy::Destructor, - nullptr, // finalize_hint - &obj->wrapper_)); - return thiz; -} - -template bool CheckNumberType(double input) -{ - if (input > (std::numeric_limits::max)() || input < (std::numeric_limits::min)()) { - return false; - } - return true; -} - -bool IsFloat(double input) -{ - return abs(input - floor(input)) >= 0; // DBL_EPSILON; -} - -napi_value StorageProxy::GetValueSync(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 2; // arg count - napi_value args[2] = { 0 }; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); - // get value type - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "type mismatch for key"); - - // get input key - char key[MAX_KEY_LENGTH] = { 0 }; - size_t keySize = 0; - NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], key, MAX_KEY_LENGTH, &keySize)); - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - NAPI_ASSERT(env, (obj != nullptr && obj->value_ != nullptr), "unwrap null native pointer"); - - napi_value output = nullptr; - NAPI_CALL(env, napi_typeof(env, args[1], &valueType)); - if (valueType == napi_number) { - double value = 0.0; - NAPI_CALL(env, napi_get_value_double(env, args[1], &value)); - double result = obj->value_->GetDouble(key, value); - NAPI_CALL(env, napi_create_double(env, result, &output)); // double - } else if (valueType == napi_string) { - char *value = new char[MAX_VALUE_LENGTH]; - size_t valueSize = 0; - napi_get_value_string_utf8(env, args[1], value, MAX_VALUE_LENGTH, &valueSize); - // get value - std::string result = obj->value_->GetString(key, value); - delete[] value; - NAPI_CALL(env, napi_create_string_utf8(env, result.c_str(), result.size(), &output)); - } else if (valueType == napi_boolean) { - bool value = false; - NAPI_CALL(env, napi_get_value_bool(env, args[1], &value)); - // get value - bool result = obj->value_->GetBool(key, value); - NAPI_CALL(env, napi_get_boolean(env, result, &output)); - } else { - NAPI_ASSERT(env, false, "Wrong second parameter type"); - } - return output; -} - -void ParseKey(const napi_env &env, const napi_value &arg, StorageAysncContext *asyncContext) -{ - // get input key - char key[MAX_KEY_LENGTH] = { 0 }; - size_t keySize = 0; - napi_get_value_string_utf8(env, arg, key, MAX_KEY_LENGTH, &keySize); - asyncContext->key = key; -} - -void ParseDefValue(const napi_env &env, const napi_value &arg, StorageAysncContext *asyncContext) -{ - napi_valuetype valueType = napi_undefined; - napi_typeof(env, arg, &valueType); - if (valueType == napi_number) { - double number = 0.0; - napi_get_value_double(env, arg, &number); - PreferencesValue value((double)number); - asyncContext->defValue = value; - } else if (valueType == napi_string) { - char *str = new char[MAX_VALUE_LENGTH]; - size_t valueSize = 0; - napi_get_value_string_utf8(env, arg, str, MAX_VALUE_LENGTH, &valueSize); - PreferencesValue value((std::string)(str)); - asyncContext->defValue = value; - delete[] str; - } else if (valueType == napi_boolean) { - bool bValue = false; - napi_get_value_bool(env, arg, &bValue); - PreferencesValue value((bool)(bValue)); - asyncContext->defValue = value; - } else { - LOG_ERROR("Wrong second parameter type"); - } -} - -napi_value StorageProxy::GetValue(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - parsers.push_back(ParseDefValue); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "GetValue", - [](StorageAysncContext *asyncContext) { - int errCode = OK; - StorageProxy *obj = reinterpret_cast(asyncContext->boundObj); - if (asyncContext->defValue.IsBool()) { - bool tmpValue = (bool)obj->value_->GetBool(asyncContext->key, (bool)asyncContext->defValue); - asyncContext->defValue = PreferencesValue((bool)tmpValue); - } else if (asyncContext->defValue.IsString()) { - std::string tmpValue = obj->value_->GetString(asyncContext->key, (std::string)asyncContext->defValue); - asyncContext->defValue = PreferencesValue((std::string)tmpValue); - } else if (asyncContext->defValue.IsDouble()) { - double tmpValue = obj->value_->GetDouble(asyncContext->key, (double)asyncContext->defValue); - asyncContext->defValue = PreferencesValue((double)tmpValue); - } else { - errCode = ERR; - } - - return errCode; - }, - [](StorageAysncContext *asyncContext, napi_value &output) { - int errCode = OK; - if (asyncContext->defValue.IsBool()) { - napi_get_boolean(asyncContext->env, (bool)asyncContext->defValue, &output); - } else if (asyncContext->defValue.IsString()) { - std::string tempStr = (std::string)asyncContext->defValue; - napi_create_string_utf8(asyncContext->env, tempStr.c_str(), tempStr.size(), &output); - } else if (asyncContext->defValue.IsDouble()) { - napi_create_double(asyncContext->env, (double)asyncContext->defValue, &output); - } else { - errCode = ERR; - } - - return errCode; - }); -} - -napi_value StorageProxy::SetValueSync(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 2; - napi_value args[2] = { 0 }; - - LOG_DEBUG("SETVALUE"); - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); - // get value type - napi_valuetype valueType = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "type mismatch for key"); - - // get input key - char key[MAX_KEY_LENGTH] = { 0 }; - size_t out = 0; - NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], key, MAX_KEY_LENGTH, &out)); - - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - NAPI_ASSERT(env, (obj != nullptr && obj->value_ != nullptr), "unwrap null native pointer"); - - NAPI_CALL(env, napi_typeof(env, args[1], &valueType)); - if (valueType == napi_number) { - double value = 0.0; - NAPI_CALL(env, napi_get_value_double(env, args[1], &value)); - int result = obj->value_->PutDouble(key, (double)value); - NAPI_ASSERT(env, result == E_OK, "call PutDouble failed"); - } else if (valueType == napi_string) { - char *value = new char[MAX_VALUE_LENGTH]; - napi_get_value_string_utf8(env, args[1], value, MAX_VALUE_LENGTH, &out); - // get value - int result = obj->value_->PutString(key, value); - delete[] value; - NAPI_ASSERT(env, result == E_OK, "call PutString failed"); - } else if (valueType == napi_boolean) { - bool value = false; - NAPI_CALL(env, napi_get_value_bool(env, args[1], &value)); - // get value - int result = obj->value_->PutBool(key, value); - NAPI_ASSERT(env, result == E_OK, "call PutBool failed"); - } else { - NAPI_ASSERT(env, false, "Wrong second parameter type"); - } - return nullptr; -} - -napi_value StorageProxy::SetValue(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - parsers.push_back(ParseDefValue); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "SetValue", - [](StorageAysncContext *asyncContext) { - int errCode = OK; - StorageProxy *obj = reinterpret_cast(asyncContext->boundObj); - if (asyncContext->defValue.IsBool()) { - errCode = obj->value_->PutBool(asyncContext->key, (bool)asyncContext->defValue); - } else if (asyncContext->defValue.IsString()) { - errCode = obj->value_->PutString(asyncContext->key, (std::string)asyncContext->defValue); - } else if (asyncContext->defValue.IsDouble()) { - errCode = obj->value_->PutDouble(asyncContext->key, (double)asyncContext->defValue); - } else { - errCode = ERR; - } - - return errCode; - }, - [](StorageAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value StorageProxy::DeleteSync(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); - // get value type - napi_valuetype valueType; - NAPI_CALL(env, napi_typeof(env, args[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "type mismatch for key"); - - char key[MAX_KEY_LENGTH] = { 0 }; - size_t out = 0; - NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], key, MAX_KEY_LENGTH, &out)); - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - int result = obj->value_->Delete(key); - NAPI_ASSERT(env, result == E_OK, "call Delete failed"); - LOG_INFO("Delete"); - return nullptr; -} - -napi_value StorageProxy::Delete(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "Delete", - [](StorageAysncContext *asyncContext) { - StorageProxy *obj = reinterpret_cast(asyncContext->boundObj); - int errCode = obj->value_->Delete(asyncContext->key); - - return errCode; - }, - [](StorageAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value StorageProxy::HasKeySync(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); - // get value type - napi_valuetype valueType; - NAPI_CALL(env, napi_typeof(env, args[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "type mismatch for key"); - - char key[MAX_KEY_LENGTH] = { 0 }; - size_t out = 0; - NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], key, MAX_KEY_LENGTH, &out)); - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - bool result = obj->value_->HasKey(key); - napi_value output = nullptr; - NAPI_CALL(env, napi_get_boolean(env, result, &output)); - LOG_DEBUG("HasKey"); - return output; -} - -napi_value StorageProxy::HasKey(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseKey); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "HasKey", - [](StorageAysncContext *asyncContext) { - StorageProxy *obj = reinterpret_cast(asyncContext->boundObj); - asyncContext->hasKey = obj->value_->HasKey(asyncContext->key); - - return OK; - }, - [](StorageAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_boolean(asyncContext->env, asyncContext->hasKey, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value StorageProxy::Flush(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "Flush", - [](StorageAysncContext *asyncContext) { - StorageProxy *obj = reinterpret_cast(asyncContext->boundObj); - return obj->value_->FlushSync(); - }, - [](StorageAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value StorageProxy::FlushSync(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr)); - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - int result = obj->value_->FlushSync(); - napi_value output = nullptr; - NAPI_CALL(env, napi_create_int64(env, result, &output)); - LOG_DEBUG("FlushSync"); - return output; -} - -napi_value StorageProxy::ClearSync(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr)); - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - int result = obj->value_->Clear(); - NAPI_ASSERT(env, result == E_OK, "call Clear failed"); - LOG_DEBUG("Clear"); - return nullptr; -} - -napi_value StorageProxy::Clear(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "Clear", - [](StorageAysncContext *asyncContext) { - StorageProxy *obj = reinterpret_cast(asyncContext->boundObj); - return obj->value_->Clear(); - }, - [](StorageAysncContext *asyncContext, napi_value &output) { - napi_status status = napi_get_undefined(asyncContext->env, &output); - return (status == napi_ok) ? OK : ERR; - }); -} - -napi_value StorageProxy::RegisterObserver(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 2; - napi_value args[2] = { 0 }; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - napi_valuetype type; - NAPI_CALL(env, napi_typeof(env, args[0], &type)); - NAPI_ASSERT(env, type == napi_string, "key not string type"); - - NAPI_CALL(env, napi_typeof(env, args[1], &type)); - NAPI_ASSERT(env, type == napi_function, "observer not function type"); - - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - - // reference save - obj->observer_ = std::make_shared(env, args[1]); - obj->value_->RegisterObserver(obj->observer_); - LOG_DEBUG("RegisterObserver end"); - - return nullptr; -} - -napi_value StorageProxy::UnRegisterObserver(napi_env env, napi_callback_info info) -{ - napi_value thiz = nullptr; - size_t argc = 2; - napi_value args[2] = { 0 }; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thiz, nullptr)); - napi_valuetype type; - NAPI_CALL(env, napi_typeof(env, args[0], &type)); - NAPI_ASSERT(env, type == napi_string, "key not string type"); - - NAPI_CALL(env, napi_typeof(env, args[1], &type)); - NAPI_ASSERT(env, type == napi_function, "observer not function type"); - - StorageProxy *obj = nullptr; - NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&obj))); - obj->value_->UnRegisterObserver(obj->observer_); - obj->observer_.reset(); - obj->observer_ = nullptr; - LOG_DEBUG("UnRegisterObserver end"); - return nullptr; -} - -StorageObserverImpl::StorageObserverImpl(napi_env env, napi_value callback) : observerRef(nullptr) -{ - this->env_ = env; - napi_create_reference(env_, callback, 1, &observerRef); -} - -StorageObserverImpl::~StorageObserverImpl() -{ - napi_delete_reference(env_, observerRef); -} - -void StorageObserverImpl::OnChange(Preferences &preferences, const std::string &key) -{ - LOG_DEBUG("OnChange key:%{public}s", key.c_str()); - napi_value callback = nullptr; - napi_value global = nullptr; - napi_value result = nullptr; - napi_value args[1] = { 0 }; - - napi_create_string_utf8(env_, key.c_str(), key.size(), &args[0]); - napi_get_reference_value(env_, observerRef, &callback); - napi_get_global(env_, &global); - - napi_call_function(env_, global, callback, 1, args, &result); - LOG_DEBUG("OnChange key end"); -} -} // namespace PreferencesJsKit -} // namespace OHOS diff --git a/preferences/frameworks/js/napi/src/napi_storage_helper.cpp b/preferences/frameworks/js/napi/src/napi_storage_helper.cpp deleted file mode 100644 index 4d390b1e5..000000000 --- a/preferences/frameworks/js/napi/src/napi_storage_helper.cpp +++ /dev/null @@ -1,201 +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 "napi_storage_helper.h" - -#include - -#include - -#include "js_logger.h" -#include "napi_async_proxy.h" -#include "napi_storage.h" -#include "preferences_errno.h" -#include "securec.h" - -using namespace OHOS::NativePreferences; -using namespace OHOS::AppDataMgrJsKit; - -namespace OHOS { -namespace PreferencesJsKit { -struct HelperAysncContext : NapiAsyncProxy::AysncContext { - std::string path; -}; - -napi_value GetStorageSync(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value args[1] = { 0 }; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); - LOG_DEBUG("getPreferences %{public}zu", argc); - napi_value instance = nullptr; - NAPI_CALL(env, StorageProxy::NewInstance(env, args[0], &instance)); - LOG_DEBUG("getPreferences end"); - return instance; -} - -void ParseString(const napi_env &env, const napi_value &value, HelperAysncContext *asyncContext) -{ - if (asyncContext == nullptr) { - LOG_WARN("error input"); - return; - } - char *path = new char[PATH_MAX]; - size_t pathLen = 0; - napi_get_value_string_utf8(env, value, path, PATH_MAX, &pathLen); - asyncContext->path = path; - delete[] path; -} - -napi_value GetStorage(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseString); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "GetStorage", - [](HelperAysncContext *asyncContext) { - int errCode = OK; - OHOS::NativePreferences::PreferencesHelper::GetPreferences(asyncContext->path, errCode); - LOG_DEBUG("GetPreferences return %{public}d", errCode); - return errCode; - }, - [](HelperAysncContext *asyncContext, napi_value &output) { - napi_value path = nullptr; - napi_create_string_utf8(asyncContext->env, asyncContext->path.c_str(), NAPI_AUTO_LENGTH, &path); - auto ret = StorageProxy::NewInstance(asyncContext->env, path, &output); - return (ret == napi_ok) ? OK : ERR; - }); -} - -napi_status GetInputPath(napi_env env, napi_callback_info info, std::string &pathString) -{ - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_status ret = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - if (ret != napi_ok) { - return ret; - } - - napi_valuetype valueType; - ret = napi_typeof(env, args[0], &valueType); - if (ret != napi_ok || valueType != napi_string) { - return napi_invalid_arg; - } - - char *path = new char[PATH_MAX]; - size_t pathLen = 0; - ret = napi_get_value_string_utf8(env, args[0], path, PATH_MAX, &pathLen); - pathString = path; - delete[] path; - return ret; -} - -napi_value DeleteStorageSync(napi_env env, napi_callback_info info) -{ - std::string path; - napi_status ret = GetInputPath(env, info, path); - if (ret != napi_ok) { - napi_throw_error(env, nullptr, "Input path error"); - return nullptr; - } - int errCode = PreferencesHelper::DeletePreferences(path); - if (errCode != E_OK) { - LOG_ERROR("deleteStorage failed %{public}d", errCode); - napi_throw_error(env, std::to_string(errCode).c_str(), "deleteStorage failed"); - } - LOG_DEBUG("deleteStorage end"); - - return nullptr; -} - -napi_value DeleteStorage(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseString); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "DeleteStorage", - [](HelperAysncContext *asyncContext) { - int errCode = PreferencesHelper::DeletePreferences(asyncContext->path); - LOG_DEBUG("DeletePreferences return %{public}d", errCode); - return errCode; - }, - [](HelperAysncContext *asyncContext, napi_value &output) { - napi_get_undefined(asyncContext->env, &output); - return OK; - }); -} - -napi_value RemoveStorageFromCacheSync(napi_env env, napi_callback_info info) -{ - std::string path; - napi_status ret = GetInputPath(env, info, path); - if (ret != napi_ok) { - napi_throw_error(env, nullptr, "Input path error"); - return nullptr; - } - - int errCode = PreferencesHelper::RemovePreferencesFromCache(path); - if (errCode != E_OK) { - LOG_ERROR("removeStorageFromCache failed %{public}d", errCode); - napi_throw_error(env, std::to_string(errCode).c_str(), "removeStorageFromCache failed"); - } - LOG_DEBUG("removeStorageFromCache end"); - - return nullptr; -} - -napi_value RemoveStorageFromCache(napi_env env, napi_callback_info info) -{ - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseString); - proxy.ParseInputs(parsers); - - return proxy.DoAsyncWork( - "RemoveStorageFromCache", - [](HelperAysncContext *asyncContext) { - int errCode = PreferencesHelper::RemovePreferencesFromCache(asyncContext->path); - LOG_DEBUG("RemovePreferencesFromCache return %{public}d", errCode); - return errCode; - }, - [](HelperAysncContext *asyncContext, napi_value &output) { - napi_get_undefined(asyncContext->env, &output); - return OK; - }); -} - -napi_value InitPreferenceHelper(napi_env env, napi_value exports) -{ - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("getStorage", GetStorage), - DECLARE_NAPI_FUNCTION("getStorageSync", GetStorageSync), - DECLARE_NAPI_FUNCTION("deleteStorage", DeleteStorage), - DECLARE_NAPI_FUNCTION("deleteStorageSync", DeleteStorageSync), - DECLARE_NAPI_FUNCTION("removeStorageFromCache", RemoveStorageFromCache), - DECLARE_NAPI_FUNCTION("removeStorageFromCacheSync", RemoveStorageFromCacheSync), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); - return exports; -} -} // namespace PreferencesJsKit -} // namespace OHOS diff --git a/preferences/frameworks/js/napi/src/napi_system_storage.cpp b/preferences/frameworks/js/napi/src/napi_system_storage.cpp deleted file mode 100644 index 7fdfcb940..000000000 --- a/preferences/frameworks/js/napi/src/napi_system_storage.cpp +++ /dev/null @@ -1,283 +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 "napi_system_storage.h" - -#include - -#include "js_ability.h" -#include "js_logger.h" -#include "js_utils.h" -#include "preferences_errno.h" -#include "preferences_helper.h" - -using namespace OHOS::AppDataMgrJsKit; -using namespace OHOS::NativePreferences; - -namespace OHOS { -namespace SystemStorageJsKit { -struct AsyncContext { - std::string key; - std::string def; - std::string val; - std::string prefName; - napi_ref success; - napi_ref fail; - napi_ref complete; - napi_deferred deferred = nullptr; - int32_t output = E_ERROR; - napi_async_work request; -}; - -static const unsigned int MAX_KEY_LENGTH = 32; - -static const unsigned int MAX_VALUE_LENGTH = 128; - -static const int32_t FAILCOUNT = 2; - -static const int32_t SUCCOUNT = 1; - -void ParseString(napi_env env, napi_value &object, const char *name, const bool enable, std::string &output) -{ - napi_value value = nullptr; - bool exist = false; - napi_has_named_property(env, object, name, &exist); - if (exist && (napi_get_named_property(env, object, name, &value) == napi_ok)) { - std::string key = JSUtils::Convert2String(env, value); - NAPI_ASSERT_RETURN_VOID(env, enable || !key.empty(), "StorageOptions is empty."); - output = std::move(key); - } -} - -void ParseFunction(napi_env env, napi_value &object, const char *name, napi_ref &output) -{ - napi_value value = nullptr; - bool exist = false; - napi_has_named_property(env, object, name, &exist); - if (exist && (napi_get_named_property(env, object, name, &value) == napi_ok)) { - napi_valuetype valueType = napi_null; - NAPI_ASSERT_RETURN_VOID(env, value != nullptr, "value == nullptr"); - NAPI_CALL_RETURN_VOID(env, napi_typeof(env, value, &valueType)); - NAPI_ASSERT_RETURN_VOID(env, valueType == napi_function, "Wrong argument, function expected."); - NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, value, 1, &output)); - } -} - -const std::string GetMessageInfo(int errCode) -{ - switch (errCode) { - case E_KEY_EMPTY: - return "The key string is null or empty."; - case E_KEY_EXCEED_LENGTH_LIMIT: - return "The key string length should shorter than 32."; - case E_VALUE_EXCEED_LENGTH_LIMIT: - return "The value string length should shorter than 128."; - case E_DEFAULT_EXCEED_LENGTH_LIMIT: - return "The default string length should shorter than 128."; - default: - return "unknown err"; - } -} - -void Complete(napi_env env, napi_status status, void *data) -{ - AsyncContext *ctx = static_cast(data); - if (status != napi_ok) { - napi_throw_type_error(env, nullptr, "Execute callback failed."); - return; - } - size_t len = 0; - if (ctx->output == E_OK && ctx->success != nullptr) { - napi_value successCallBack = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, ctx->success, &successCallBack)); - napi_value succRes[SUCCOUNT] = { 0 }; - len = ctx->val.size(); - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, ctx->val.c_str(), len, &succRes[0])); - napi_value succCallbackResult = nullptr; - NAPI_CALL_RETURN_VOID( - env, napi_call_function(env, nullptr, successCallBack, SUCCOUNT, succRes, &succCallbackResult)); - } - - if (ctx->output != E_OK && ctx->fail != nullptr) { - napi_value failCallBack = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, ctx->fail, &failCallBack)); - napi_value failRes[FAILCOUNT] = { 0 }; - std::string message = GetMessageInfo(ctx->output); - len = message.size(); - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, message.c_str(), len, &failRes[0])); - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, ctx->output, &failRes[1])); - napi_value failCallbackResult = nullptr; - NAPI_CALL_RETURN_VOID( - env, napi_call_function(env, nullptr, failCallBack, FAILCOUNT, failRes, &failCallbackResult)); - } - - if (ctx->complete != nullptr) { - napi_value completeCallBack = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, ctx->complete, &completeCallBack)); - napi_value completeCallbackResult = nullptr; - NAPI_CALL_RETURN_VOID( - env, napi_call_function(env, nullptr, completeCallBack, 0, nullptr, &completeCallbackResult)); - } - napi_delete_async_work(env, ctx->request); - napi_delete_reference(env, ctx->success); - napi_delete_reference(env, ctx->fail); - napi_delete_reference(env, ctx->complete); - napi_value res = nullptr; - napi_get_undefined(env, &res); - napi_resolve_deferred(env, ctx->deferred, res); - delete ctx; -} - -std::string GetPrefName(napi_env env) -{ - auto ctx = JSAbility::GetContext(env, nullptr); - return ctx->GetPreferencesDir() + "/default.xml"; -} - -napi_value Operate(napi_env env, napi_callback_info info, const char *resource, bool parseStrFlag, - napi_async_execute_callback execute) -{ - size_t argc = 1; - napi_value argv[1] = { 0 }; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); - NAPI_ASSERT(env, argc == 1, "Not enough arguments, expected 1."); - napi_valuetype valueType = napi_null; - NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type, object expected."); - - AsyncContext *context = new AsyncContext(); - context->prefName = GetPrefName(env); - - ParseString(env, argv[0], "key", parseStrFlag, context->key); - ParseString(env, argv[0], "value", false, context->val); - ParseString(env, argv[0], "default", false, context->def); - - ParseFunction(env, argv[0], "success", context->success); - ParseFunction(env, argv[0], "fail", context->fail); - ParseFunction(env, argv[0], "complete", context->complete); - - napi_value ret = nullptr; - napi_value resourceName = nullptr; - napi_status status = napi_create_string_utf8(env, resource, NAPI_AUTO_LENGTH, &resourceName); - if (status != napi_ok) { - LOG_ERROR("Operate get resourceName failed, status = %{public}d", status); - delete context; - return ret; - } - status = napi_create_promise(env, &context->deferred, &ret); - if (status != napi_ok) { - LOG_ERROR("Operate create promise failed, status = %{public}d", status); - delete context; - return ret; - } - status = napi_create_async_work(env, nullptr, resourceName, execute, Complete, context, &context->request); - if (status != napi_ok) { - LOG_ERROR("Operate create asyncWork failed, status = %{public}d", status); - delete context; - return ret; - } - status = napi_queue_async_work(env, context->request); - if (status != napi_ok) { - LOG_ERROR("Operate queue asyncWork failed, status = %{public}d", status); - delete context; - } - return ret; -} - -napi_value NapiGet(napi_env env, napi_callback_info info) -{ - return Operate(env, info, "get", true, [](napi_env env, void *data) { - AsyncContext *context = static_cast(data); - if (context->key.size() > MAX_KEY_LENGTH) { - context->output = E_KEY_EXCEED_LENGTH_LIMIT; - return; - } - - if (context->def.size() > MAX_VALUE_LENGTH) { - context->output = E_DEFAULT_EXCEED_LENGTH_LIMIT; - return; - } - - auto pref = PreferencesHelper::GetPreferences(context->prefName, context->output); - context->val = pref->GetString(context->key, context->def); - }); -} - -napi_value NapiSet(napi_env env, napi_callback_info info) -{ - return Operate(env, info, "set", true, [](napi_env env, void *data) { - AsyncContext *context = static_cast(data); - if (context->key.size() > MAX_KEY_LENGTH) { - context->output = E_KEY_EXCEED_LENGTH_LIMIT; - return; - } - if (context->val.size() > MAX_VALUE_LENGTH) { - context->output = E_VALUE_EXCEED_LENGTH_LIMIT; - return; - } - - auto pref = PreferencesHelper::GetPreferences(context->prefName, context->output); - if (context->output != E_OK) { - return; - } - context->output = pref->PutString(context->key, context->val); - pref->FlushSync(); - }); -} - -napi_value NapiDelete(napi_env env, napi_callback_info info) -{ - return Operate(env, info, "delete", true, [](napi_env env, void *data) { - AsyncContext *context = static_cast(data); - if (context->key.size() > MAX_KEY_LENGTH) { - context->output = E_KEY_EXCEED_LENGTH_LIMIT; - return; - } - - auto pref = PreferencesHelper::GetPreferences(context->prefName, context->output); - if (context->output != E_OK) { - return; - } - context->output = pref->Delete(context->key); - pref->FlushSync(); - }); -} - -napi_value NapiClear(napi_env env, napi_callback_info info) -{ - return Operate(env, info, "clear", false, [](napi_env env, void *data) { - AsyncContext *context = static_cast(data); - auto pref = PreferencesHelper::GetPreferences(context->prefName, context->output); - if (context->output != E_OK) { - return; - } - context->output = pref->Clear(); - pref->FlushSync(); - }); -} - -napi_value InitSystemStorage(napi_env env, napi_value exports) -{ - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("get", NapiGet), - DECLARE_NAPI_FUNCTION("delete", NapiDelete), - DECLARE_NAPI_FUNCTION("clear", NapiClear), - DECLARE_NAPI_FUNCTION("set", NapiSet), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); - return exports; -} -} // namespace SystemStorageJsKit -} // namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/include/logger.h b/preferences/frameworks/native/include/logger.h deleted file mode 100644 index b5f61f475..000000000 --- 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 deleted file mode 100644 index 3ec35a708..000000000 --- a/preferences/frameworks/native/include/preferences_impl.h +++ /dev/null @@ -1,215 +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 PREFERENCES_IMPL_H -#define PREFERENCES_IMPL_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "preferences.h" -#include "preferences_observer.h" -#include "preferences_value.h" -#include "task_pool.h" - -namespace OHOS { -namespace NativePreferences { -class PreferencesImpl : public Preferences { -public: - explicit PreferencesImpl(const std::filesystem::path &path); - virtual ~PreferencesImpl(); - - int Init(); - - PreferencesValue Get(const std::string &key, const PreferencesValue &defValue) override; - - int Put(const std::string &key, const PreferencesValue &value) override; - - int GetInt(const std::string &key, const int &defValue) override - { - PreferencesValue preferencesValue = Get(key, defValue); - if (!preferencesValue.IsInt()) { - return defValue; - } - return preferencesValue; - } - - std::string GetString(const std::string &key, const std::string &defValue) override - { - PreferencesValue preferencesValue = Get(key, defValue); - if (!preferencesValue.IsString()) { - return defValue; - } - return preferencesValue; - } - - bool GetBool(const std::string &key, const bool &defValue) override - { - PreferencesValue preferencesValue = Get(key, defValue); - if (!preferencesValue.IsBool()) { - return defValue; - } - return preferencesValue; - } - - float GetFloat(const std::string &key, const float &defValue) override - { - PreferencesValue preferencesValue = Get(key, defValue); - if (!preferencesValue.IsFloat()) { - return defValue; - } - return preferencesValue; - } - - double GetDouble(const std::string &key, const double &defValue) override - { - PreferencesValue preferencesValue = Get(key, defValue); - if (!preferencesValue.IsDouble()) { - return defValue; - } - return preferencesValue; - } - - int64_t GetLong(const std::string &key, const int64_t &defValue) override - { - PreferencesValue preferencesValue = Get(key, defValue); - if (!preferencesValue.IsLong()) { - return defValue; - } - return preferencesValue; - } - - bool HasKey(const std::string &key) override; - - int PutInt(const std::string &key, int value) override - { - return Put(key, value); - } - - int PutString(const std::string &key, const std::string &value) override - { - return Put(key, value); - } - - int PutBool(const std::string &key, bool value) override - { - return Put(key, value); - } - - int PutLong(const std::string &key, int64_t value) override - { - return Put(key, value); - } - - int PutFloat(const std::string &key, float value) override - { - return Put(key, value); - } - - int PutDouble(const std::string &key, double value) override - { - return Put(key, value); - } - - std::map GetAll() override; - - int Delete(const std::string &key) override; - - int Clear() override; - - void Flush() override; - - int FlushSync() override; - - void RegisterObserver(std::shared_ptr preferencesObserver) override; - - void UnRegisterObserver(std::shared_ptr preferencesObserver) override; - - static std::filesystem::path MakeBackupPath(const std::filesystem::path &prefPath); - static std::filesystem::path MakeBrokenPath(const std::filesystem::path &prefPath); - -private: - class MemoryToDiskRequest { - public: - MemoryToDiskRequest(const std::map &writeToDiskMap, - const std::list &keysModified, - const std::vector> preferencesObservers, int64_t memStataGeneration); - ~MemoryToDiskRequest() - { - } - void SetDiskWriteResult(bool wasWritten, int result); - - bool isSyncRequest_; - int64_t memoryStateGeneration_; - std::map writeToDiskMap_; - std::mutex reqMutex_; - std::condition_variable reqCond_; - std::list keysModified_; - std::vector> preferencesObservers_; - - int writeToDiskResult_; - bool wasWritten_; - bool handled_; - }; - - std::shared_ptr commitToMemory(); - void notifyPreferencesObserver(const MemoryToDiskRequest &request); - void StartLoadFromDisk(); - int CheckKey(const std::string &key); - int CheckStringValue(const std::string &value); - - /* thread function */ - static void LoadFromDisk(PreferencesImpl &pref); - void AwaitLoadFile(); - void WriteToDiskFile(std::shared_ptr mcr); - bool CheckRequestValidForStateGeneration(const MemoryToDiskRequest &mcr); - - bool ReadSettingXml(const std::filesystem::path &prefPath, std::map &prefMap); - bool WriteSettingXml(const std::filesystem::path &prefPath, const std::map &prefMap); - - bool loaded_; - - /* Current memory state (always increasing) */ - int64_t currentMemoryStateGeneration_; - /* Latest memory state that was committed to disk */ - int64_t diskStateGeneration_; - - std::mutex mutex_; - std::condition_variable cond_; - - std::vector> preferencesObservers_; - std::map map_; - std::list modifiedKeys_; - - const std::filesystem::path filePath_; - const std::filesystem::path backupPath_; - const std::filesystem::path brokenPath_; - // Task pool - /* max threads of the task pool. */ - static constexpr int MAX_TP_THREADS = 10; - /* min threads of the task pool. */ - static constexpr int MIN_TP_THREADS = 1; - TaskPool taskPool_; -}; -} // End of namespace NativePreferences -} // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_IMPL_H diff --git a/preferences/frameworks/native/include/task_pool.h b/preferences/frameworks/native/include/task_pool.h deleted file mode 100644 index aeeb0972a..000000000 --- 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_queue.h b/preferences/frameworks/native/include/task_queue.h deleted file mode 100644 index f968cd30d..000000000 --- a/preferences/frameworks/native/include/task_queue.h +++ /dev/null @@ -1,42 +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_QUEUE_H -#define TASK_QUEUE_H - -#include -#include - -namespace OHOS { -namespace NativePreferences { -using Task = std::function; - -class TaskQueue { -public: - explicit TaskQueue(bool lockable = true); - ~TaskQueue(); - void PutTask(const Task &task); - Task GetTaskAutoLock(); - void ReleaseLock(); - bool IsEmptyAndUnlocked(); - -private: - bool lockable_; - std::thread::id lockThread_; - std::queue tasks_; -}; -} // namespace NativePreferences -} // namespace OHOS -#endif // TASK_QUEUE_H diff --git a/preferences/frameworks/native/src/preferences_helper.cpp b/preferences/frameworks/native/src/preferences_helper.cpp deleted file mode 100644 index 6c9a14e16..000000000 --- a/preferences/frameworks/native/src/preferences_helper.cpp +++ /dev/null @@ -1,154 +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 "preferences_helper.h" - -#include -#include - -#include -#include - -#include "logger.h" -#include "preferences.h" -#include "preferences_errno.h" -#include "preferences_impl.h" -#include "securec.h" - -namespace OHOS { -namespace NativePreferences { -std::map> PreferencesHelper::prefsCache_; -std::mutex PreferencesHelper::prefsCacheMutex_; - -static bool IsFileExist(const std::filesystem::path &path) -{ - FILE *file = std::fopen(path.c_str(), "r"); - if (file != nullptr) { - std::fclose(file); - return true; - } - return false; -} - -std::string PreferencesHelper::GetRealPath(const std::string &path, int &errorCode) -{ - if (path.empty()) { - LOG_ERROR("The path can not be empty."); - errorCode = E_EMPTY_FILE_PATH; - return ""; - } - if (path.front() != '/') { - LOG_ERROR("The path can not be relative path."); - errorCode = E_RELATIVE_PATH; - return ""; - } - if (strlen(path.c_str()) > PATH_MAX) { - LOG_ERROR("The path exceeds max length."); - errorCode = E_PATH_EXCEED_MAX_LENGTH; - return ""; - } - std::string::size_type pos = path.find_last_of('/'); - if (pos == std::string::npos) { - LOG_ERROR("path can not be relative path."); - errorCode = E_RELATIVE_PATH; - return ""; - } - std::string filePath = path.substr(0, pos); - char canonicalPath[PATH_MAX + 1] = { 0 }; - if (realpath(filePath.c_str(), canonicalPath) == nullptr) { - LOG_ERROR("Failed to obtain real path, errno:%{public}d", errno); - errorCode = E_INVALID_FILE_PATH; - return ""; - } - std::string fileName = path.substr(pos + 1, path.length()); - if (fileName.empty()) { - LOG_ERROR("file name can not be empty."); - errorCode = E_EMPTY_FILE_NAME; - return ""; - } - errorCode = E_OK; - std::string realFilePath(canonicalPath); - return realFilePath.append("/").append(fileName); -} - -std::shared_ptr PreferencesHelper::GetPreferences(const std::string &path, int &errCode) -{ - std::string realPath = GetRealPath(path, errCode); - if (realPath == "" || errCode != E_OK) { - return nullptr; - } - - std::lock_guard lock(prefsCacheMutex_); - std::map>::iterator it = prefsCache_.find(realPath); - if (it != prefsCache_.end()) { - return it->second; - } - - std::filesystem::path filePath = realPath.c_str(); - std::shared_ptr pref = std::make_shared(filePath); - errCode = pref->Init(); - if (errCode != E_OK) { - return nullptr; - } - prefsCache_.insert(make_pair(realPath, pref)); - return pref; -} - -int PreferencesHelper::DeletePreferences(const std::string &path) -{ - int errCode = E_OK; - std::string realPath = GetRealPath(path, errCode); - if (realPath == "" || errCode != E_OK) { - return errCode; - } - - std::lock_guard lock(prefsCacheMutex_); - std::map>::iterator it = prefsCache_.find(realPath); - if (it != prefsCache_.end()) { - prefsCache_.erase(it); - } - - std::filesystem::path filePath = realPath.c_str(); - std::filesystem::path backupPath = PreferencesImpl::MakeBackupPath(filePath); - std::filesystem::path brokenPath = PreferencesImpl::MakeBrokenPath(filePath); - - std::remove(filePath.c_str()); - std::remove(backupPath.c_str()); - std::remove(brokenPath.c_str()); - - if (IsFileExist(filePath) || IsFileExist(backupPath) || IsFileExist(brokenPath)) { - return E_DELETE_FILE_FAIL; - } - return E_OK; -} - -int PreferencesHelper::RemovePreferencesFromCache(const std::string &path) -{ - int errCode = E_OK; - std::string realPath = GetRealPath(path, errCode); - if (realPath == "" || errCode != E_OK) { - return errCode; - } - - std::lock_guard lock(prefsCacheMutex_); - std::map>::iterator it = prefsCache_.find(realPath); - if (it == prefsCache_.end()) { - return E_OK; - } - prefsCache_.erase(it); - return E_OK; -} -} // End of namespace NativePreferences -} // End of namespace OHOS diff --git a/preferences/frameworks/native/src/preferences_impl.cpp b/preferences/frameworks/native/src/preferences_impl.cpp deleted file mode 100644 index d072ef4b6..000000000 --- a/preferences/frameworks/native/src/preferences_impl.cpp +++ /dev/null @@ -1,571 +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 "preferences_impl.h" - -#include -#include -#include -#include -#include - -#include "logger.h" -#include "preferences_errno.h" -#include "preferences_xml_utils.h" -#include "securec.h" - -namespace OHOS { -namespace NativePreferences { -static bool IsFileExist(const std::filesystem::path &inputPath) -{ - char path[PATH_MAX + 1] = { 0x00 }; - if (strlen(inputPath.c_str()) > PATH_MAX || realpath(inputPath.c_str(), path) == nullptr) { - return false; - } - const char *pathString = path; - FILE *file = std::fopen(pathString, "r"); - if (file != nullptr) { - std::fclose(file); - return true; - } - return false; -} - -PreferencesImpl::PreferencesImpl(const std::filesystem::path &filePath) - : loaded_(false), filePath_(filePath), backupPath_(MakeBackupPath(filePath_)), - brokenPath_(MakeBrokenPath(filePath_)), taskPool_(TaskPool(MAX_TP_THREADS, MIN_TP_THREADS)) -{ - currentMemoryStateGeneration_ = 0; - diskStateGeneration_ = 0; -} - -std::filesystem::path PreferencesImpl::MakeBackupPath(const std::filesystem::path &prefPath) -{ - std::filesystem::path backupPath = prefPath; - backupPath += ".bak"; - return backupPath; -} - -std::filesystem::path PreferencesImpl::MakeBrokenPath(const std::filesystem::path &prefPath) -{ - std::filesystem::path brokenPath = prefPath; - brokenPath += ".bak"; - return brokenPath; -} - -PreferencesImpl::~PreferencesImpl() -{ - taskPool_.Stop(); -} - -int PreferencesImpl::Init() -{ - int errCode = taskPool_.Start(); - if (errCode != E_OK) { - return errCode; - } - StartLoadFromDisk(); - return E_OK; -} - -void PreferencesImpl::StartLoadFromDisk() -{ - { - std::lock_guard lock(mutex_); - loaded_ = false; - } - taskPool_.Schedule(std::string("PreferencesImpl"), std::bind(&PreferencesImpl::LoadFromDisk, std::ref(*this))); -} - -int PreferencesImpl::CheckKey(const std::string &key) -{ - if (key.empty()) { - LOG_ERROR("The key string is null or empty."); - return E_KEY_EMPTY; - } - if (Preferences::MAX_KEY_LENGTH < key.length()) { - LOG_ERROR("The key string length should shorter than 80."); - return E_KEY_EXCEED_MAX_LENGTH; - } - return E_OK; -} - -/* static */ -void PreferencesImpl::LoadFromDisk(PreferencesImpl &pref) -{ - std::lock_guard lock(pref.mutex_); - if (pref.loaded_) { - return; - } - - if (IsFileExist(pref.backupPath_)) { - if (std::remove(pref.filePath_.c_str())) { - LOG_ERROR("Couldn't delete file %{private}s when LoadFromDisk and backup exist.", pref.filePath_.c_str()); - } - if (std::rename(pref.backupPath_.c_str(), pref.filePath_.c_str())) { - LOG_ERROR("Couldn't rename backup file %{private}s to file %{private}s,when LoadFromDisk and backup " - "exist.", - pref.backupPath_.c_str(), pref.filePath_.c_str()); - } else { - PreferencesXmlUtils::LimitXmlPermission(pref.filePath_); - } - } - - if (IsFileExist(pref.filePath_)) { - pref.ReadSettingXml(pref.filePath_, pref.map_); - } - - pref.loaded_ = true; - pref.cond_.notify_all(); -} - -void PreferencesImpl::AwaitLoadFile() -{ - std::unique_lock lock(mutex_); - if (!loaded_) { - cond_.wait(lock, [this] { return loaded_; }); - } -} - -void PreferencesImpl::WriteToDiskFile(std::shared_ptr mcr) -{ - bool fileExists = false; - if (IsFileExist(filePath_)) { - fileExists = true; - } - - if (fileExists) { - bool needWrite = CheckRequestValidForStateGeneration(*mcr); - if (!needWrite) { - mcr->SetDiskWriteResult(false, E_OK); - return; - } - - if (IsFileExist(backupPath_)) { - if (std::remove(filePath_.c_str())) { - LOG_ERROR("Couldn't delete file %{private}s when writeToFile and backup exist.", filePath_.c_str()); - } - } else { - if (std::rename(filePath_.c_str(), backupPath_.c_str())) { - LOG_ERROR("Couldn't rename file %{private}s to backup file %{private}s", filePath_.c_str(), - backupPath_.c_str()); - mcr->SetDiskWriteResult(false, E_ERROR); - return; - } else { - PreferencesXmlUtils::LimitXmlPermission(backupPath_); - } - } - } - - if (WriteSettingXml(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()); - } - diskStateGeneration_ = mcr->memoryStateGeneration_; - mcr->SetDiskWriteResult(true, E_OK); - } else { - /* Clean up an unsuccessfully written file */ - if (IsFileExist(filePath_)) { - if (std::remove(filePath_.c_str())) { - LOG_ERROR("Couldn't clean up partially-written file %{private}s", filePath_.c_str()); - } - } - mcr->SetDiskWriteResult(false, E_ERROR); - } -} - -bool PreferencesImpl::CheckRequestValidForStateGeneration(const MemoryToDiskRequest &mcr) -{ - bool valid = false; - - if (diskStateGeneration_ < mcr.memoryStateGeneration_) { - if (mcr.isSyncRequest_) { - valid = true; - } else { - if (currentMemoryStateGeneration_ == mcr.memoryStateGeneration_) { - valid = true; - } - } - } - return valid; -} - -PreferencesValue PreferencesImpl::Get(const std::string &key, const PreferencesValue &defValue) -{ - if (CheckKey(key) != E_OK) { - return defValue; - } - - AwaitLoadFile(); - std::lock_guard lock(mutex_); - auto iter = map_.find(key); - if (iter != map_.end()) { - return iter->second; - } - return defValue; -} - -std::map PreferencesImpl::GetAll() -{ - AwaitLoadFile(); - - return map_; -} - -void ReadXmlArrayElement(Element element, std::map &prefMap) -{ - 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))); - } -} - -void ReadXmlElement( - Element element, std::map &prefMap, const std::filesystem::path &prefPath) -{ - 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()); - } -} - -bool PreferencesImpl::ReadSettingXml( - const std::filesystem::path &prefPath, std::map &prefMap) -{ - std::vector settings; - if (!PreferencesXmlUtils::ReadSettingXml(prefPath.generic_string(), settings)) { - LOG_ERROR("ReadSettingXml:%{private}s failed!", filePath_.c_str()); - return false; - } - - for (auto it = settings.begin(); it != settings.end(); it++) { - Element element = *it; - ReadXmlElement(element, prefMap, prefPath); - } - return true; -} - -void WriteXmlElement(Element &elem, PreferencesValue value, const std::filesystem::path filePath) -{ - 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_ = (std::string)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; - } else { - LOG_WARN("WriteSettingXml:%{private}s, unknown element type.", filePath.c_str()); - } -} - -bool PreferencesImpl::WriteSettingXml( - const std::filesystem::path &prefPath, const std::map &prefMap) -{ - std::vector settings; - for (auto it = prefMap.begin(); it != prefMap.end(); it++) { - Element elem; - elem.key_ = it->first; - PreferencesValue value = it->second; - - WriteXmlElement(elem, value, filePath_); - settings.push_back(elem); - } - - return PreferencesXmlUtils::WriteSettingXml(prefPath.generic_string(), settings); -} - -bool PreferencesImpl::HasKey(const std::string &key) -{ - if (CheckKey(key) != E_OK) { - return false; - } - - AwaitLoadFile(); - - std::lock_guard lock(mutex_); - return (map_.find(key) != map_.end()); -} - -void PreferencesImpl::RegisterObserver(std::shared_ptr preferencesObserver) -{ - std::lock_guard lock(mutex_); - std::weak_ptr weakPreferencesObserver = preferencesObserver; - preferencesObservers_.push_back(weakPreferencesObserver); -} - -void PreferencesImpl::UnRegisterObserver(std::shared_ptr preferencesObserver) -{ - std::lock_guard lock(mutex_); - for (auto it = preferencesObservers_.begin(); it != preferencesObservers_.end(); ++it) { - std::weak_ptr weakPreferencesObserver = *it; - std::shared_ptr sharedPreferencesObserver = weakPreferencesObserver.lock(); - if (!sharedPreferencesObserver || sharedPreferencesObserver == preferencesObserver) { - preferencesObservers_.erase(it); - break; - } - } -} - -int PreferencesImpl::Put(const std::string &key, const PreferencesValue &value) -{ - int errCode = CheckKey(key); - if (errCode != E_OK) { - return errCode; - } - if (value.IsString()) { - errCode = CheckStringValue(value); - if (errCode != E_OK) { - LOG_ERROR("PreferencesImpl::Put string value length should shorter than 8*1024"); - return errCode; - } - } - - AwaitLoadFile(); - - std::lock_guard lock(mutex_); - - auto iter = map_.find(key); - if (iter != map_.end()) { - PreferencesValue &val = iter->second; - if (val == value) { - return E_OK; - } - } - - map_.insert_or_assign(key, value); - modifiedKeys_.push_back(key); - return E_OK; -} - -int PreferencesImpl::CheckStringValue(const std::string &value) -{ - if (Preferences::MAX_VALUE_LENGTH < value.length()) { - LOG_ERROR("The value string length should shorter than 8 * 1024."); - return E_VALUE_EXCEED_MAX_LENGTH; - } - return E_OK; -} - -int PreferencesImpl::Delete(const std::string &key) -{ - int errCode = CheckKey(key); - if (errCode != E_OK) { - return errCode; - } - - std::lock_guard lock(mutex_); - - auto pos = map_.find(key); - if (pos != map_.end()) { - map_.erase(pos); - modifiedKeys_.push_back(key); - } - - return E_OK; -} - -int PreferencesImpl::Clear() -{ - std::lock_guard lock(mutex_); - - if (!map_.empty()) { - for (auto &kv : map_) { - modifiedKeys_.push_back(kv.first); - } - map_.clear(); - } - return E_OK; -} - -void PreferencesImpl::Flush() -{ - std::shared_ptr request = commitToMemory(); - request->isSyncRequest_ = false; - - taskPool_.Schedule( - std::string("PreferencesImpl"), std::bind(&PreferencesImpl::WriteToDiskFile, std::ref(*this), request)); - notifyPreferencesObserver(*request); -} - -int PreferencesImpl::FlushSync() -{ - std::shared_ptr request = commitToMemory(); - request->isSyncRequest_ = true; - - taskPool_.Schedule( - std::string("PreferencesImpl"), std::bind(&PreferencesImpl::WriteToDiskFile, std::ref(*this), request)); - std::unique_lock lock(request->reqMutex_); - request->reqCond_.wait(lock, [request] { return request->handled_; }); - if (request->wasWritten_) { - LOG_DEBUG("%{private}s:%{public}" PRId64 " written", filePath_.c_str(), request->memoryStateGeneration_); - } - - notifyPreferencesObserver(*request); - return request->writeToDiskResult_; -} - -std::shared_ptr PreferencesImpl::commitToMemory() -{ - std::lock_guard lock(mutex_); - int64_t memoryStateGeneration = -1; - std::list keysModified; - std::vector> preferencesObservers; - std::map writeToDiskMap; - writeToDiskMap = map_; - - if (!modifiedKeys_.empty()) { - currentMemoryStateGeneration_++; - keysModified = modifiedKeys_; - modifiedKeys_.clear(); - } - memoryStateGeneration = currentMemoryStateGeneration_; - preferencesObservers = preferencesObservers_; - return std::make_shared( - writeToDiskMap, keysModified, preferencesObservers, memoryStateGeneration); -} - -void PreferencesImpl::notifyPreferencesObserver(const PreferencesImpl::MemoryToDiskRequest &request) -{ - if ((request.preferencesObservers_.empty()) || (request.keysModified_.empty())) { - return; - } - for (auto key = request.keysModified_.begin(); key != request.keysModified_.end(); ++key) { - for (auto it = request.preferencesObservers_.begin(); it != request.preferencesObservers_.end(); ++it) { - std::weak_ptr weakPreferencesObserver = *it; - if (std::shared_ptr sharedPreferencesObserver = weakPreferencesObserver.lock()) { - sharedPreferencesObserver->OnChange(*this, *key); - } - } - } -} - -PreferencesImpl::MemoryToDiskRequest::MemoryToDiskRequest( - const std::map &writeToDiskMap, const std::list &keysModified, - const std::vector> preferencesObservers, int64_t memStataGeneration) -{ - writeToDiskMap_ = writeToDiskMap; - keysModified_ = keysModified; - preferencesObservers_ = preferencesObservers; - memoryStateGeneration_ = memStataGeneration; - isSyncRequest_ = false; - handled_ = false; - wasWritten_ = false; - writeToDiskResult_ = E_ERROR; -} - -void PreferencesImpl::MemoryToDiskRequest::SetDiskWriteResult(bool wasWritten, int result) -{ - writeToDiskResult_ = result; - wasWritten_ = wasWritten; - handled_ = true; - reqCond_.notify_one(); -} -} // End of namespace NativePreferences -} // End of namespace OHOS diff --git a/preferences/frameworks/native/src/preferences_observer.cpp b/preferences/frameworks/native/src/preferences_observer.cpp deleted file mode 100644 index bbf363cf7..000000000 --- a/preferences/frameworks/native/src/preferences_observer.cpp +++ /dev/null @@ -1,24 +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 "preferences_observer.h" - -namespace OHOS { -namespace NativePreferences { -PreferencesObserver::~PreferencesObserver() -{ -} -} // End of namespace NativePreferences -} // End of namespace OHOS diff --git a/preferences/frameworks/native/src/preferences_value.cpp b/preferences/frameworks/native/src/preferences_value.cpp deleted file mode 100644 index a7672d0ce..000000000 --- a/preferences/frameworks/native/src/preferences_value.cpp +++ /dev/null @@ -1,199 +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 "preferences_value.h" - -namespace OHOS { -namespace NativePreferences { -PreferencesValue::PreferencesValue(const PreferencesValue &preferencesValue) -{ - if (this == &preferencesValue) { - return; - } - value_ = preferencesValue.value_; -} - -PreferencesValue::PreferencesValue(PreferencesValue &&preferencesValue) noexcept -{ - if (this == &preferencesValue) { - return; - } - value_ = std::move(preferencesValue.value_); -} - -PreferencesValue::PreferencesValue(int value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(int64_t value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(float value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(double value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(bool value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(const char *value) -{ - PreferencesValue((std::string)value); -} - -PreferencesValue::PreferencesValue(std::string value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(std::vector value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(std::vector value) -{ - value_ = value; -} - -PreferencesValue::PreferencesValue(std::vector value) -{ - value_ = value; -} - -PreferencesValue &PreferencesValue::operator=(PreferencesValue &&preferencesValue) noexcept -{ - if (this == &preferencesValue) { - return *this; - } - value_ = std::move(preferencesValue.value_); - return *this; -} - -PreferencesValue &PreferencesValue::operator=(const PreferencesValue &preferencesValue) -{ - if (this == &preferencesValue) { - return *this; - } - value_ = preferencesValue.value_; - return *this; -} - -bool PreferencesValue::IsInt() const -{ - return std::holds_alternative(value_); -} - -bool PreferencesValue::IsLong() const -{ - return std::holds_alternative(value_); -} - -bool PreferencesValue::IsFloat() const -{ - return std::holds_alternative(value_); -} - -bool PreferencesValue::IsDouble() const -{ - return std::holds_alternative(value_); -} - -bool PreferencesValue::IsBool() const -{ - return std::holds_alternative(value_); -} - -bool PreferencesValue::IsString() const -{ - return std::holds_alternative(value_); -} - -bool PreferencesValue::IsDoubleArray() const -{ - return std::holds_alternative>(value_); -} - -bool PreferencesValue::IsStringArray() const -{ - return std::holds_alternative>(value_); -} - -bool PreferencesValue::IsBoolArray() const -{ - return std::holds_alternative>(value_); -} - -PreferencesValue::operator int() const -{ - return std::get(value_); -} - -PreferencesValue::operator int64_t() const -{ - return std::get(value_); -} - -PreferencesValue::operator float() const -{ - return std::get(value_); -} - -PreferencesValue::operator double() const -{ - return std::get(value_); -} - -PreferencesValue::operator bool() const -{ - return std::get(value_); -} - -PreferencesValue::operator std::string() const -{ - return std::get(value_); -} - -PreferencesValue::operator std::vector() const -{ - return std::get>(value_); -} - -PreferencesValue::operator std::vector() const -{ - return std::get>(value_); -} - -PreferencesValue::operator std::vector() const -{ - return std::get>(value_); -} - -bool PreferencesValue::operator==(const PreferencesValue &value) -{ - return (this->value_ == value.value_); -} -} // End of namespace NativePreferences -} // End of namespace OHOS diff --git a/preferences/frameworks/native/src/preferences_xml_utils.cpp b/preferences/frameworks/native/src/preferences_xml_utils.cpp deleted file mode 100644 index 0de6b93f4..000000000 --- a/preferences/frameworks/native/src/preferences_xml_utils.cpp +++ /dev/null @@ -1,390 +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 "preferences_xml_utils.h" - -#include - -#include -#include - -#include "libxml/parser.h" -#include "logger.h" - -namespace OHOS { -namespace NativePreferences { -static bool ParseNodeElement(const xmlNode *node, Element &element); -static bool ParsePrimitiveNodeElement(const xmlNode *node, Element &element); -static bool ParseStringNodeElement(const xmlNode *node, Element &element); -static bool ParseArrayNodeElement(const xmlNode *node, Element &element); -static xmlNode *CreateElementNode(Element &element); -static xmlNode *CreatePrimitiveNode(Element &element); -static xmlNode *CreateStringNode(Element &element); -static xmlNode *CreateArrayNode(Element &element); -/* static */ -bool PreferencesXmlUtils::ReadSettingXml(const std::string &fileName, std::vector &settings) -{ - LOG_DEBUG("Read setting xml %{private}s start.", fileName.c_str()); - 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) == nullptr) { - LOG_ERROR("The file name is incorrect."); - return false; - } - const char *pathString = path; - xmlDoc *doc = xmlReadFile(pathString, "UTF-8", XML_PARSE_NOBLANKS); - if (doc == nullptr) { - LOG_ERROR("The file name is incorrect."); - return false; - } - - xmlNode *root = xmlDocGetRootElement(doc); - if (!root || xmlStrcmp(root->name, reinterpret_cast("preferences"))) { - xmlFreeDoc(doc); - LOG_ERROR("Failed to obtain the XML root element."); - return false; - } - - bool success = true; - const xmlNode *cur = nullptr; - for (cur = root->children; cur != nullptr; cur = cur->next) { - Element element; - - if (ParseNodeElement(cur, element)) { - settings.push_back(element); - } else { - success = false; - LOG_ERROR("The error occurred during getting xml child elements."); - break; - } - } - - /* free the document */ - xmlFreeDoc(doc); - LOG_DEBUG("Read setting xml %{private}s end.", fileName.c_str()); - return success; -} - -/* static */ -bool ParseNodeElement(const xmlNode *node, Element &element) -{ - if (!xmlStrcmp(node->name, reinterpret_cast("int")) - || !xmlStrcmp(node->name, reinterpret_cast("long")) - || !xmlStrcmp(node->name, reinterpret_cast("bool")) - || !xmlStrcmp(node->name, reinterpret_cast("float")) - || !xmlStrcmp(node->name, reinterpret_cast("double"))) { - return ParsePrimitiveNodeElement(node, element); - } - - if (!xmlStrcmp(node->name, reinterpret_cast("string"))) { - return ParseStringNodeElement(node, element); - } - - if (!xmlStrcmp(node->name, reinterpret_cast("boolArray")) - || !xmlStrcmp(node->name, reinterpret_cast("stringArray")) - || !xmlStrcmp(node->name, reinterpret_cast("doubleArray")) - || !xmlStrcmp(node->name, reinterpret_cast("set"))) { - return ParseArrayNodeElement(node, element); - } - - LOG_ERROR("An unsupported element type was encountered in parsing = %{public}s.", node->name); - return false; -} - -/* static */ -bool ParsePrimitiveNodeElement(const xmlNode *node, Element &element) -{ - if (node == nullptr) { - return false; - } - - xmlChar *key = xmlGetProp(node, reinterpret_cast("key")); - xmlChar *value = xmlGetProp(node, reinterpret_cast("value")); - - bool success = false; - if (value != nullptr) { - element.tag_ = std::string(reinterpret_cast(node->name)); - if (key != nullptr) { - element.key_ = std::string(reinterpret_cast(key)); - } - element.value_ = std::string(reinterpret_cast(value)); - success = true; - } else { - LOG_ERROR("Failed to obtain a valid key or value when parsing %{public}s.", node->name); - } - - if (key != nullptr) { - xmlFree(key); - } - if (value != nullptr) { - xmlFree(value); - } - return success; -} - -/* static */ -bool ParseStringNodeElement(const xmlNode *node, Element &element) -{ - if (node == nullptr) { - return false; - } - - xmlChar *key = xmlGetProp(node, (const xmlChar *)"key"); - xmlChar *text = xmlNodeGetContent(node); - - bool success = false; - if (text != nullptr) { - element.tag_ = std::string(reinterpret_cast(node->name)); - if (key != nullptr) { - element.key_ = std::string(reinterpret_cast(key)); - } - element.value_ = std::string(reinterpret_cast(text)); - success = true; - } else { - LOG_ERROR("Failed to obtain a valid key or value when parsing a String element."); - } - - if (key != nullptr) { - xmlFree(key); - } - if (text != nullptr) { - xmlFree(text); - } - return success; -} - -/* static */ -bool ParseArrayNodeElement(const xmlNode *node, Element &element) -{ - if (node == nullptr) { - return false; - } - - xmlChar *key = xmlGetProp(node, (const xmlChar *)"key"); - const xmlNode *children = node->children; - - bool success = false; - if (key != nullptr) { - element.tag_ = std::string(reinterpret_cast(node->name)); - element.key_ = std::string(reinterpret_cast(key)); - - const xmlNode *cur = nullptr; - bool finishTravelChild = true; - for (cur = children; cur != nullptr; cur = cur->next) { - Element child; - if (ParseNodeElement(cur, child)) { - element.children_.push_back(child); - } else { - finishTravelChild = false; - LOG_ERROR("Failed to parse the Array element and could not be completed successfully."); - break; - } - } - success = finishTravelChild; - } else { - LOG_ERROR("Failed to obtain a valid key or value when parsing a Array element."); - } - - if (key != nullptr) { - xmlFree(key); - } - return success; -} - -/* static */ -bool PreferencesXmlUtils::WriteSettingXml(const std::string &fileName, std::vector &settings) -{ - LOG_DEBUG("Write setting xml %{private}s start.", fileName.c_str()); - 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"); - if (doc == nullptr) { - LOG_ERROR("Failed to initialize the xmlDoc."); - return false; - } - xmlNode *root_node = xmlNewNode(NULL, BAD_CAST "preferences"); - if (root_node == 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"); - - // set root node - xmlDocSetRootElement(doc, root_node); - - // 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) { - /* 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; -} - -/* static */ -xmlNode *CreateElementNode(Element &element) -{ - if ((element.tag_.compare("int") == 0) || (element.tag_.compare("long") == 0) - || (element.tag_.compare("float") == 0) || (element.tag_.compare("bool") == 0) - || (element.tag_.compare("double") == 0)) { - return CreatePrimitiveNode(element); - } - - if (element.tag_.compare("string") == 0) { - return CreateStringNode(element); - } - - if ((element.tag_.compare("doubleArray") == 0) || (element.tag_.compare("stringArray") == 0) - || (element.tag_.compare("boolArray") == 0)) { - return CreateArrayNode(element); - } - - LOG_ERROR("An unsupported element type was encountered in parsing = %{public}s.", element.tag_.c_str()); - return nullptr; -} - -/* static */ -xmlNode *CreatePrimitiveNode(Element &element) -{ - xmlNode *node = xmlNewNode(NULL, BAD_CAST element.tag_.c_str()); - if (node == nullptr) { - LOG_ERROR("The xmlDoc failed to initialize the primitive element node."); - return nullptr; - } - if (!element.key_.empty()) { - const char *key = element.key_.c_str(); - xmlNewProp(node, BAD_CAST "key", BAD_CAST key); - } - - const char *value = element.value_.c_str(); - xmlNewProp(node, BAD_CAST "value", BAD_CAST value); - return node; -} - -xmlNode *CreateStringNode(Element &element) -{ - xmlNode *node = xmlNewNode(NULL, BAD_CAST element.tag_.c_str()); - if (node == nullptr) { - LOG_ERROR("The xmlDoc failed to initialize the string element node."); - return nullptr; - } - - if (!element.key_.empty()) { - const char *key = element.key_.c_str(); - xmlNewProp(node, BAD_CAST "key", BAD_CAST key); - } - - const char *value = element.value_.c_str(); - xmlNodePtr text = xmlNewText(BAD_CAST value); - if (xmlAddChild(node, text) == nullptr) { - xmlFreeNode(text); - } - return node; -} - -xmlNode *CreateArrayNode(Element &element) -{ - xmlNode *node = xmlNewNode(NULL, BAD_CAST element.tag_.c_str()); - if (node == nullptr) { - LOG_ERROR("The xmlDoc failed to initialize the array element node."); - return nullptr; - } - - const char *key = element.key_.c_str(); - xmlNewProp(node, BAD_CAST "key", BAD_CAST key); - - Element flag = element.children_[0]; - if ((flag.tag_.compare("bool") == 0) || (flag.tag_.compare("double") == 0)) { - for (Element &child : element.children_) { - xmlNode *childNode = CreatePrimitiveNode(child); - if (childNode == nullptr) { - continue; - } - if (xmlAddChild(node, childNode) == nullptr) { - xmlFreeNode(childNode); - } - } - } else if (flag.tag_.compare("string") == 0) { - for (Element child : element.children_) { - xmlNode *childNode = CreateStringNode(child); - if (childNode == nullptr) { - continue; - } - if (xmlAddChild(node, childNode) == nullptr) { - xmlFreeNode(childNode); - } - } - } - return node; -} - -void PreferencesXmlUtils::LimitXmlPermission(const std::string &fileName) -{ - /* clear execute permission of owner, clear execute permission of group, clear all permission of group. */ - struct stat fileStat = { 0 }; - if (stat(fileName.c_str(), &fileStat) != 0) { - LOG_ERROR("Failed to obtain stat of file, errno:%{public}d.", errno); - return; - } - if ((fileStat.st_mode & (S_IXUSR | S_IXGRP | S_IRWXO)) != 0) { - int result = chmod(fileName.c_str(), fileStat.st_mode & (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)); - if (result != 0) { - LOG_ERROR("Failed to chmod file, errno:%{public}d.", errno); - } - } -} - -void PreferencesXmlUtils::XmlInitParser() -{ - xmlInitParser(); - LOG_DEBUG("Xml parser get ready."); -} - -void PreferencesXmlUtils::XmlCleanupParser() -{ - xmlCleanupParser(); - LOG_DEBUG("Xml parser clean up."); -} -} // End of namespace NativePreferences -} // End of namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/native/src/task_pool.cpp b/preferences/frameworks/native/src/task_pool.cpp deleted file mode 100644 index d33d8fa80..000000000 --- a/preferences/frameworks/native/src/task_pool.cpp +++ /dev/null @@ -1,310 +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" - -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]() { 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 52b796185..000000000 --- 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 deleted file mode 100644 index ee82de8e3..000000000 --- a/preferences/interfaces/inner_api/BUILD.gn +++ /dev/null @@ -1,52 +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("//build/ohos.gni") -import("//foundation/distributeddatamgr/preferences/preferences.gni") -config("native_preferences_config") { - visibility = [ ":*" ] - include_dirs = [ - "include", - "${preferences_native_path}/include", - ] -} - -config("native_preferences_public_config") { - visibility = [ "//foundation/distributeddatamgr/preferences:*" ] - include_dirs = [ "include" ] -} - -ohos_shared_library("native_preferences") { - sources = [ - "${preferences_native_path}/src/preferences_helper.cpp", - "${preferences_native_path}/src/preferences_impl.cpp", - "${preferences_native_path}/src/preferences_observer.cpp", - "${preferences_native_path}/src/preferences_value.cpp", - "${preferences_native_path}/src/preferences_xml_utils.cpp", - "${preferences_native_path}/src/task_pool.cpp", - "${preferences_native_path}/src/task_queue.cpp", - ] - - configs = [ ":native_preferences_config" ] - - deps = [ "//third_party/libxml2:libxml2" ] - - external_deps = [ - "c_utils:utils", - "hilog_native:libhilog", - ] - - public_configs = [ ":native_preferences_public_config" ] - - subsystem_name = "distributeddatamgr" - part_name = "preferences" -} diff --git a/preferences/interfaces/inner_api/include/preferences.h b/preferences/interfaces/inner_api/include/preferences.h deleted file mode 100644 index b1eb1786f..000000000 --- a/preferences/interfaces/inner_api/include/preferences.h +++ /dev/null @@ -1,85 +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 PREFERENCES_H -#define PREFERENCES_H - -#include -#include -#include -#include - -#include "preferences_observer.h" -#include "preferences_value.h" - -namespace OHOS { -namespace NativePreferences { -class Preferences { -public: - virtual ~Preferences() - { - } - - static const unsigned int MAX_KEY_LENGTH = 80; - - static const unsigned int MAX_VALUE_LENGTH = 8 * 1024; - - virtual PreferencesValue Get(const std::string &key, const PreferencesValue &defValue) = 0; - - virtual int Put(const std::string &key, const PreferencesValue &value) = 0; - - virtual int GetInt(const std::string &key, const int &defValue = {}) = 0; - - virtual std::string GetString(const std::string &key, const std::string &defValue = {}) = 0; - - virtual bool GetBool(const std::string &key, const bool &defValue = {}) = 0; - - virtual float GetFloat(const std::string &key, const float &defValue = {}) = 0; - - virtual double GetDouble(const std::string &key, const double &defValue = {}) = 0; - - virtual int64_t GetLong(const std::string &key, const int64_t &defValue = {}) = 0; - - virtual std::map GetAll() = 0; - - virtual bool HasKey(const std::string &key) = 0; - - virtual int PutInt(const std::string &key, int value) = 0; - - virtual int PutString(const std::string &key, const std::string &value) = 0; - - virtual int PutBool(const std::string &key, bool value) = 0; - - virtual int PutLong(const std::string &key, int64_t value) = 0; - - virtual int PutFloat(const std::string &key, float value) = 0; - - virtual int PutDouble(const std::string &key, double value) = 0; - - virtual int Delete(const std::string &key) = 0; - - virtual int Clear() = 0; - - virtual void Flush() = 0; - - virtual int FlushSync() = 0; - - virtual void RegisterObserver(std::shared_ptr preferencesObserver) = 0; - - virtual void UnRegisterObserver(std::shared_ptr preferencesObserver) = 0; -}; -} // End of namespace NativePreferences -} // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_H diff --git a/preferences/interfaces/inner_api/include/preferences_errno.h b/preferences/interfaces/inner_api/include/preferences_errno.h deleted file mode 100644 index f42b62845..000000000 --- a/preferences/interfaces/inner_api/include/preferences_errno.h +++ /dev/null @@ -1,46 +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 PREFERENCES_ERRNO_H -#define PREFERENCES_ERRNO_H - -#include - -namespace OHOS { -namespace NativePreferences { -constexpr int E_OK = 0; -constexpr int E_BASE = -1000; // different from the other errno. -constexpr int E_ERROR = (E_BASE - 1); -constexpr int E_STALE = (E_BASE - 2); // Resource has been stopped, killed or destroyed. -constexpr int E_INVALID_ARGS = (E_BASE - 3); // the input args is invalid. -constexpr int E_OUT_OF_MEMORY = (E_BASE - 4); // out of memory -constexpr int E_NOT_PERMIT = (E_BASE - 5); // operation is not permitted -constexpr int E_KEY_EMPTY = (E_BASE - 6); -constexpr int E_KEY_EXCEED_MAX_LENGTH = (E_BASE - 7); -constexpr int E_PTR_EXIST_ANOTHER_HOLDER = (E_BASE - 8); -constexpr int E_DELETE_FILE_FAIL = (E_BASE - 9); -constexpr int E_EMPTY_FILE_PATH = (E_BASE - 10); -constexpr int E_RELATIVE_PATH = (E_BASE - 11); -constexpr int E_EMPTY_FILE_NAME = (E_BASE - 12); -constexpr int E_INVALID_FILE_PATH = (E_BASE - 13); -constexpr int E_PATH_EXCEED_MAX_LENGTH = (E_BASE - 14); -constexpr int E_VALUE_EXCEED_MAX_LENGTH = (E_BASE - 15); -constexpr int E_KEY_EXCEED_LENGTH_LIMIT = (E_BASE - 16); -constexpr int E_VALUE_EXCEED_LENGTH_LIMIT = (E_BASE - 17); -constexpr int E_DEFAULT_EXCEED_LENGTH_LIMIT = (E_BASE - 18); -constexpr int E_NAPI_GET_ERROR = (E_BASE - 19); -} // namespace NativePreferences -} // namespace OHOS -#endif // PREFERENCES_ERRNO_H diff --git a/preferences/interfaces/inner_api/include/preferences_helper.h b/preferences/interfaces/inner_api/include/preferences_helper.h deleted file mode 100644 index 06d89b3b3..000000000 --- a/preferences/interfaces/inner_api/include/preferences_helper.h +++ /dev/null @@ -1,42 +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 PREFERENCES_HELPER_H -#define PREFERENCES_HELPER_H - -#include -#include -#include -#include - -#include "preferences.h" - -namespace OHOS { -namespace NativePreferences { -class PreferencesHelper { -public: - static std::shared_ptr GetPreferences(const std::string &path, int &errCode); - static int DeletePreferences(const std::string &path); - static int RemovePreferencesFromCache(const std::string &path); - -private: - static std::map> prefsCache_; - static std::mutex prefsCacheMutex_; - - static std::string GetRealPath(const std::string &path, int &errorCode); -}; -} // End of namespace NativePreferences -} // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_HELPER_H diff --git a/preferences/interfaces/inner_api/include/preferences_observer.h b/preferences/interfaces/inner_api/include/preferences_observer.h deleted file mode 100644 index 93c609f9e..000000000 --- a/preferences/interfaces/inner_api/include/preferences_observer.h +++ /dev/null @@ -1,31 +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 PREFERENCES_OBSERVER_H -#define PREFERENCES_OBSERVER_H - -#include - -namespace OHOS { -namespace NativePreferences { -class Preferences; -class PreferencesObserver { -public: - virtual ~PreferencesObserver(); - virtual void OnChange(Preferences &preferences, const std::string &key) = 0; -}; -} // End of namespace NativePreferences -} // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_OBSERVER_H diff --git a/preferences/interfaces/inner_api/include/preferences_value.h b/preferences/interfaces/inner_api/include/preferences_value.h deleted file mode 100644 index c74356dc0..000000000 --- a/preferences/interfaces/inner_api/include/preferences_value.h +++ /dev/null @@ -1,76 +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 PREFERENCES_VALUE_H -#define PREFERENCES_VALUE_H - -#include -#include -#include - -namespace OHOS { -namespace NativePreferences { -class PreferencesValue { -public: - ~PreferencesValue() - { - } - - PreferencesValue(PreferencesValue &&preferencesValue) noexcept; - PreferencesValue(const PreferencesValue &preferencesValue); - - PreferencesValue(int value); - PreferencesValue(int64_t value); - PreferencesValue(float value); - PreferencesValue(double value); - PreferencesValue(bool value); - PreferencesValue(std::string value); - PreferencesValue(const char *value); - PreferencesValue(std::vector value); - PreferencesValue(std::vector value); - PreferencesValue(std::vector value); - PreferencesValue &operator=(PreferencesValue &&preferencesValue) noexcept; - PreferencesValue &operator=(const PreferencesValue &preferencesValue); - - bool IsInt() const; - bool IsLong() const; - bool IsFloat() const; - bool IsDouble() const; - bool IsBool() const; - bool IsString() const; - bool IsStringArray() const; - bool IsBoolArray() const; - bool IsDoubleArray() const; - - operator int() const; - operator float() const; - operator double() const; - operator bool() const; - operator int64_t() const; - operator std::string() const; - operator std::vector() const; - operator std::vector() const; - operator std::vector() const; - - bool operator==(const PreferencesValue &value); - -private: - std::variant, std::vector, - std::vector> - value_; -}; -} // End of namespace NativePreferences -} // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_VALUE_H diff --git a/preferences/interfaces/inner_api/include/preferences_xml_utils.h b/preferences/interfaces/inner_api/include/preferences_xml_utils.h deleted file mode 100644 index 7ba5b8633..000000000 --- a/preferences/interfaces/inner_api/include/preferences_xml_utils.h +++ /dev/null @@ -1,51 +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 PREFERENCES_XML_UTILS_H -#define PREFERENCES_XML_UTILS_H - -#include -#include - -namespace OHOS { -namespace NativePreferences { -class Element { -public: - std::string tag_; - std::string key_; - std::string value_; - - std::vector children_; -}; - -class PreferencesXmlUtils { -public: - static bool ReadSettingXml(const std::string &fileName, std::vector &settings); - static bool WriteSettingXml(const std::string &fileName, std::vector &settings); - static void LimitXmlPermission(const std::string &fileName); - static void XmlInitParser(); - static void XmlCleanupParser(); - -private: - PreferencesXmlUtils() - { - } - ~PreferencesXmlUtils() - { - } -}; -} // End of namespace NativePreferences -} // End of namespace OHOS -#endif // End of #ifndef PREFERENCES_XML_UTILS_H diff --git a/preferences/preferences.gni b/preferences/preferences.gni deleted file mode 100644 index 9e0b2eaea..000000000 --- a/preferences/preferences.gni +++ /dev/null @@ -1,20 +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. - -preferences_base_path = "//foundation/distributeddatamgr/preferences" - -preferences_napi_path = "${preferences_base_path}/frameworks/js/napi" - -preferences_native_path = "${preferences_base_path}/frameworks/native" - -preferences_innerapi_path = "${preferences_base_path}/interfaces/inner_api" diff --git a/preferences/test/js/unittest/src/BUILD.gn b/preferences/test/js/unittest/src/BUILD.gn deleted file mode 100644 index 14324f803..000000000 --- a/preferences/test/js/unittest/src/BUILD.gn +++ /dev/null @@ -1,29 +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("//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/developertest/signature/openharmony_sx.p7b" -} - -group("unittest") { - testonly = true - deps = [ ":StorageJsTest" ] -} 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 a4504cc11..000000000 --- a/preferences/test/js/unittest/src/PreferencesCallBackJsunit.test.js +++ /dev/null @@ -1,416 +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() - }) - }) -}) \ 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 9bb1b7aed..000000000 --- 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); - expect(value).assertEqual(2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @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 1cde06354..000000000 --- a/preferences/test/js/unittest/src/PreferencesPromiseJsunit.test.js +++ /dev/null @@ -1,452 +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"); - expect("defaultvalue").assertEqual(per); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @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); - expect(true).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @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); - expect(4.0).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @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); - expect(4).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @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); - expect(4).assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - done(); - }) - - /** - * @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") - expect('').assertEqual(per2); - }).catch((err) => { - expect(null).assertFail(); - }); - await promise; - 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 d6cfa1acf..000000000 --- a/preferences/test/js/unittest/src/StorageCallBackJsunit.test.js +++ /dev/null @@ -1,306 +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."); - }) - }); - }) - }); - }); - }) -}) \ 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 369c87f81..000000000 --- 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 688ee134e..000000000 --- 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 4ae5086e3..000000000 --- a/preferences/test/js/unittest/src/StorageSyncJsunit.test.js +++ /dev/null @@ -1,289 +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"); - }) -}) 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 c252b4bbb..000000000 --- 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/native/BUILD.gn b/preferences/test/native/BUILD.gn deleted file mode 100644 index dfbd14551..000000000 --- a/preferences/test/native/BUILD.gn +++ /dev/null @@ -1,53 +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("//build/test.gni") -import("//foundation/distributeddatamgr/preferences/preferences.gni") - -module_output_path = "preferences/native_preferences" - -############################################################################### -config("module_private_config") { - visibility = [ ":*" ] - - include_dirs = [ - "${preferences_native_path}/include/", - "${preferences_innerapi_path}/include", - ] -} - -ohos_unittest("NativePreferencesTest") { - module_out_path = module_output_path - - sources = [ - "unittest/preferences_file_test.cpp", - "unittest/preferences_helper_test.cpp", - "unittest/preferences_test.cpp", - ] - - configs = [ ":module_private_config" ] - - external_deps = [ "hilog_native:libhilog" ] - - deps = [ - "${preferences_innerapi_path}:native_preferences", - "//third_party/googletest:gtest_main", - ] -} - -############################################################################### -group("unittest") { - testonly = true - - deps = [ ":NativePreferencesTest" ] -} -############################################################################### diff --git a/preferences/test/native/unittest/preferences_file_test.cpp b/preferences/test/native/unittest/preferences_file_test.cpp deleted file mode 100644 index d51ddeff0..000000000 --- a/preferences/test/native/unittest/preferences_file_test.cpp +++ /dev/null @@ -1,301 +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 - -#include -#include - -#include "logger.h" -#include "preferences.h" -#include "preferences_errno.h" -#include "preferences_helper.h" -#include "preferences_xml_utils.h" - -using namespace testing::ext; -using namespace OHOS::NativePreferences; - -class PreferencesFileTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void PreferencesFileTest::SetUpTestCase(void) -{ -} - -void PreferencesFileTest::TearDownTestCase(void) -{ -} - -void PreferencesFileTest::SetUp(void) -{ -} - -void PreferencesFileTest::TearDown(void) -{ -} - -/** - * @tc.name: NativePreferencesFileTest_001 - * @tc.desc: normal testcase of backup file - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: liulinna - */ -HWTEST_F(PreferencesFileTest, NativePreferencesFileTest_001, TestSize.Level1) -{ - std::string file = "/data/test/test"; - std::string backupFile = "/data/test/test.bak"; - - std::remove(file.c_str()); - std::remove(backupFile.c_str()); - - std::vector settings; - Element elem; - elem.key_ = "intKey"; - elem.tag_ = std::string("int"); - elem.value_ = std::to_string(10); - settings.push_back(elem); - PreferencesXmlUtils::WriteSettingXml(backupFile, settings); - - int errCode = E_OK; - std::shared_ptr pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - int ret = pref->GetInt("intKey", 0); - EXPECT_EQ(ret, 10); - - struct stat st = { 0 }; - ret = stat(file.c_str(), &st); - EXPECT_EQ(ret, 0); - ret = (st.st_mode & (S_IXUSR | S_IXGRP | S_IRWXO)); - EXPECT_EQ(ret, 0); - - pref = nullptr; - ret = PreferencesHelper::DeletePreferences(file); - EXPECT_EQ(ret, E_OK); -} - -/** - * @tc.name: NativePreferencesFileTest_002 - * @tc.desc: normal testcase of file permission - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: liulinna - */ -HWTEST_F(PreferencesFileTest, NativePreferencesFileTest_002, TestSize.Level1) -{ - std::string file = "/data/test/test"; - std::remove(file.c_str()); - - int errCode = E_OK; - std::shared_ptr pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - - pref->PutInt("key1", 2); - pref->PutString("key2", "test"); - int ret = pref->FlushSync(); - EXPECT_EQ(ret, E_OK); - - struct stat st = { 0 }; - int result = stat(file.c_str(), &st); - EXPECT_EQ(result, 0); - result = st.st_mode & (S_IXUSR | S_IXGRP | S_IRWXO); - EXPECT_EQ(result, 0); - - pref = nullptr; - result = PreferencesHelper::DeletePreferences(file); - EXPECT_EQ(result, E_OK); -} - -/** - * @tc.name: NativePreferencesFileTest_003 - * @tc.desc: test two same file path - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: liulinna - */ -HWTEST_F(PreferencesFileTest, NativePreferencesFileTest_003, TestSize.Level1) -{ - std::string absolutePath = "/data/test1"; - std::string relativePath = "/data/test/../test1"; - std::remove(absolutePath.c_str()); - - int errCode = E_OK; - std::shared_ptr pref1 = PreferencesHelper::GetPreferences(absolutePath, errCode); - EXPECT_EQ(errCode, E_OK); - - errCode = E_OK; - std::shared_ptr pref2 = PreferencesHelper::GetPreferences(relativePath, errCode); - EXPECT_EQ(errCode, E_OK); - - EXPECT_EQ(pref1, pref2); - - pref1 = nullptr; - pref2 = nullptr; - int result = PreferencesHelper::DeletePreferences(absolutePath); - EXPECT_EQ(result, E_OK); -} - -/** - * @tc.name: NativePreferencesFileTest_004 - * @tc.desc: test FlushSync one times and five times - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: liulinna - */ -HWTEST_F(PreferencesFileTest, NativePreferencesFileTest_004, TestSize.Level1) -{ - std::string file = "/data/test/test"; - int ret = PreferencesHelper::DeletePreferences(file); - EXPECT_EQ(ret, E_OK); - - int errCode = E_OK; - std::shared_ptr pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - - pref->PutInt("intKey", 1); - pref->PutString("stringKey", "string1"); - ret = pref->FlushSync(); - EXPECT_EQ(ret, E_OK); - - EXPECT_EQ(1, pref->GetInt("intKey", 0)); - EXPECT_EQ("string1", pref->GetString("stringKey", "")); - - pref = nullptr; - ret = PreferencesHelper::RemovePreferencesFromCache("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); - - errCode = E_OK; - pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - - EXPECT_EQ(1, pref->GetInt("intKey", 0)); - EXPECT_EQ("string1", pref->GetString("stringKey", "")); - - pref->PutInt("intKey", 2); - pref->PutString("stringKey", "string2"); - ret = pref->FlushSync(); - EXPECT_EQ(ret, E_OK); - pref->PutInt("intKey", 3); - pref->PutString("stringKey", "string3"); - ret = pref->FlushSync(); - EXPECT_EQ(ret, E_OK); - - pref->PutInt("intKey", 4); - pref->PutString("stringKey", "string4"); - ret = pref->FlushSync(); - EXPECT_EQ(ret, E_OK); - - pref = PreferencesHelper::GetPreferences(file, errCode); - pref->PutInt("intKey", 5); - pref->PutString("stringKey", "string5"); - ret = pref->FlushSync(); - EXPECT_EQ(ret, E_OK); - - EXPECT_EQ(5, pref->GetInt("intKey", 0)); - EXPECT_EQ("string5", pref->GetString("stringKey", "")); - - pref = nullptr; - ret = PreferencesHelper::RemovePreferencesFromCache("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); - - errCode = E_OK; - pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - - EXPECT_EQ(5, pref->GetInt("intKey", 0)); - EXPECT_EQ("string5", pref->GetString("stringKey", "")); - - pref = nullptr; - ret = PreferencesHelper::DeletePreferences("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); -} - -/** - * @tc.name: NativePreferencesFileTest_005 - * @tc.desc: test Flush one times and five times - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: liulinna - */ -HWTEST_F(PreferencesFileTest, NativePreferencesFileTest_005, TestSize.Level3) -{ - std::string file = "/data/test/test"; - int ret = PreferencesHelper::DeletePreferences(file); - EXPECT_EQ(ret, E_OK); - - int errCode = E_OK; - std::shared_ptr pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - - pref->PutInt("intKey", 1); - pref->PutString("stringKey", "string1"); - pref->Flush(); - - EXPECT_EQ(1, pref->GetInt("intKey", 0)); - EXPECT_EQ("string1", pref->GetString("stringKey", "")); - - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - - pref = nullptr; - ret = PreferencesHelper::RemovePreferencesFromCache("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); - - errCode = E_OK; - pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - - EXPECT_EQ(1, pref->GetInt("intKey", 0)); - EXPECT_EQ("string1", pref->GetString("stringKey", "")); - - pref->PutInt("intKey", 2); - pref->PutString("stringKey", "string2"); - pref->Flush(); - pref->PutInt("intKey", 3); - pref->PutString("stringKey", "string3"); - pref->Flush(); - - pref->PutInt("intKey", 4); - pref->PutString("stringKey", "string4"); - pref->Flush(); - - pref->PutInt("intKey", 5); - pref->PutString("stringKey", "string5"); - pref->Flush(); - - EXPECT_EQ(5, pref->GetInt("intKey", 0)); - EXPECT_EQ("string5", pref->GetString("stringKey", "")); - - std::this_thread::sleep_for(std::chrono::milliseconds(20)); - - pref = nullptr; - ret = PreferencesHelper::RemovePreferencesFromCache("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); - - errCode = E_OK; - pref = PreferencesHelper::GetPreferences(file, errCode); - EXPECT_EQ(errCode, E_OK); - - EXPECT_EQ(5, pref->GetInt("intKey", 0)); - EXPECT_EQ("string5", pref->GetString("stringKey", "")); - - pref = nullptr; - ret = PreferencesHelper::DeletePreferences("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); -} diff --git a/preferences/test/native/unittest/preferences_helper_test.cpp b/preferences/test/native/unittest/preferences_helper_test.cpp deleted file mode 100644 index 4617f775a..000000000 --- a/preferences/test/native/unittest/preferences_helper_test.cpp +++ /dev/null @@ -1,81 +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 "preferences_helper.h" - -#include - -#include -#include -#include - -#include "logger.h" -#include "preferences.h" -#include "preferences_errno.h" -#include "preferences_observer.h" - -using namespace testing::ext; -using namespace OHOS::NativePreferences; - -class PreferencesHelperTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void PreferencesHelperTest::SetUpTestCase(void) -{ -} - -void PreferencesHelperTest::TearDownTestCase(void) -{ -} - -void PreferencesHelperTest::SetUp(void) -{ -} - -void PreferencesHelperTest::TearDown(void) -{ -} - -/** - * @tc.name: NativePreferencesHelperTest_001 - * @tc.desc: normal testcase of DeletePreferences - * @tc.type: FUNC - * @tc.require: SR000CU2BL - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesHelperTest, NativePreferencesHelperTest_001, TestSize.Level1) -{ - int errCode = E_OK; - std::shared_ptr pref = PreferencesHelper::GetPreferences("/data/test/test_helper", errCode); - EXPECT_EQ(errCode, E_OK); - - pref->PutInt("key1", 2); - pref->PutString("key2", "test"); - int ret = pref->FlushSync(); - EXPECT_EQ(ret, E_OK); - - pref = nullptr; - - ret = PreferencesHelper::RemovePreferencesFromCache("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); - - ret = PreferencesHelper::DeletePreferences("/data/test/test_helper"); - EXPECT_EQ(ret, E_OK); -} diff --git a/preferences/test/native/unittest/preferences_test.cpp b/preferences/test/native/unittest/preferences_test.cpp deleted file mode 100644 index 1d7c8b2a2..000000000 --- a/preferences/test/native/unittest/preferences_test.cpp +++ /dev/null @@ -1,706 +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 "preferences.h" - -#include - -#include -#include -#include - -#include "logger.h" -#include "preferences_errno.h" -#include "preferences_helper.h" -#include "preferences_observer.h" - -using namespace testing::ext; -using namespace OHOS::NativePreferences; - -class PreferencesTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - - static std::shared_ptr pref; - - static const std::string LONG_KEY; - - static const std::string KEY_TEST_INT_ELEMENT; - static const std::string KEY_TEST_LONG_ELEMENT; - static const std::string KEY_TEST_FLOAT_ELEMENT; - static const std::string KEY_TEST_DOUBLE_ELEMENT; - static const std::string KEY_TEST_BOOL_ELEMENT; - static const std::string KEY_TEST_STRING_ELEMENT; -}; - -std::shared_ptr PreferencesTest::pref = nullptr; - -const std::string PreferencesTest::LONG_KEY = std::string(Preferences::MAX_KEY_LENGTH, std::toupper('a')); -; - -const std::string PreferencesTest::KEY_TEST_INT_ELEMENT = "key_test_int"; -const std::string PreferencesTest::KEY_TEST_LONG_ELEMENT = "key_test_long"; -const std::string PreferencesTest::KEY_TEST_FLOAT_ELEMENT = "key_test_float"; -const std::string PreferencesTest::KEY_TEST_DOUBLE_ELEMENT = "key_test_double"; -const std::string PreferencesTest::KEY_TEST_BOOL_ELEMENT = "key_test_bool"; -const std::string PreferencesTest::KEY_TEST_STRING_ELEMENT = "key_test_string"; - -void PreferencesTest::SetUpTestCase(void) -{ - int errCode = E_OK; - pref = PreferencesHelper::GetPreferences("/data/test/test", errCode); - EXPECT_EQ(errCode, E_OK); -} - -void PreferencesTest::TearDownTestCase(void) -{ - pref = nullptr; - int ret = PreferencesHelper::DeletePreferences("/data/test/test"); - EXPECT_EQ(ret, E_OK); -} - -void PreferencesTest::SetUp(void) -{ -} - -void PreferencesTest::TearDown(void) -{ - /* clear all data after every case */ - if (pref) { - pref->Clear(); - pref->Flush(); - } -} - -class PreferencesObserverCounter : public PreferencesObserver { -public: - virtual ~PreferencesObserverCounter(); - void OnChange(Preferences &preferences, const std::string &key) override; - - std::atomic_int notifyTimes; - static const std::vector NOTIFY_KEYS_VECTOR; -}; - -PreferencesObserverCounter::~PreferencesObserverCounter() -{ -} - -void PreferencesObserverCounter::OnChange(Preferences &preferences, const std::string &key) -{ - for (auto it = NOTIFY_KEYS_VECTOR.cbegin(); it != NOTIFY_KEYS_VECTOR.cend(); it++) { - if (key.compare(*it)) { - notifyTimes++; - break; - } - } -} - -const std::vector PreferencesObserverCounter::NOTIFY_KEYS_VECTOR = { PreferencesTest::KEY_TEST_INT_ELEMENT, - PreferencesTest::KEY_TEST_LONG_ELEMENT, PreferencesTest::KEY_TEST_FLOAT_ELEMENT, - PreferencesTest::KEY_TEST_BOOL_ELEMENT, PreferencesTest::KEY_TEST_STRING_ELEMENT }; - -/** - * @tc.name: NativePreferencesTest_001 - * @tc.desc: normal testcase of FlushSync - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_001, TestSize.Level1) -{ - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->FlushSync(); - - int ret1 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 6); - EXPECT_EQ(ret1, 2); - std::string ret2 = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1"); - EXPECT_EQ(ret2, "test"); -} - -/** - * @tc.name: NativePreferencesTest_002 - * @tc.desc: normal testcase of HasKey - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_002, TestSize.Level1) -{ - bool ret = pref->HasKey(LONG_KEY + 'x'); - EXPECT_EQ(ret, false); - - ret = pref->HasKey(std::string()); - EXPECT_EQ(ret, false); - - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - ret = pref->HasKey(KEY_TEST_STRING_ELEMENT); - EXPECT_EQ(ret, true); - - pref->Flush(); - ret = pref->HasKey(KEY_TEST_STRING_ELEMENT); - EXPECT_EQ(ret, true); -} - -/** - * @tc.name: NativePreferencesTest_003 - * @tc.desc: normal testcase of pref - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_003, TestSize.Level1) -{ - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1"); - - std::string ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); - EXPECT_EQ(ret, "test1"); - - pref->Flush(); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); - EXPECT_EQ(ret, "test1"); -} - -/** - * @tc.name: NativePreferencesTest_004 - * @tc.desc: normal testcase of GetBool - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_004, TestSize.Level1) -{ - bool ret = pref->GetBool(PreferencesTest::LONG_KEY + 'x', true); - EXPECT_EQ(ret, true); - - ret = pref->GetBool("", true); - EXPECT_EQ(ret, true); - - pref->PutBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, false); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "false"); - pref->Flush(); - - ret = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); - EXPECT_EQ(ret, false); - - ret = pref->GetBool(PreferencesTest::KEY_TEST_STRING_ELEMENT, true); - EXPECT_EQ(ret, true); -} - -/** - * @tc.name: NativePreferencesTest_005 - * @tc.desc: normal testcase of GetFloat - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_005, TestSize.Level1) -{ - float ret = pref->GetFloat(PreferencesTest::LONG_KEY + 'x', 3.0f); - EXPECT_EQ(ret, 3.0f); - - ret = pref->GetFloat("", 3.0f); - EXPECT_EQ(ret, 3.0f); - - pref->PutFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 5.0f); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "5.0"); - pref->Flush(); - - ret = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, true); - EXPECT_EQ(ret, 5.0f); - - ret = pref->GetFloat(PreferencesTest::KEY_TEST_STRING_ELEMENT, 3.0f); - EXPECT_EQ(ret, 3.0f); -} - -/** - * @tc.name: NativePreferencesTest_006 - * @tc.desc: normal testcase of GetInt - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_006, TestSize.Level1) -{ - int ret = pref->GetInt(PreferencesTest::LONG_KEY + 'x', 35); - EXPECT_EQ(ret, 35); - - ret = pref->GetInt("", 35); - EXPECT_EQ(ret, 35); - - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 5); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "5"); - pref->Flush(); - - ret = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); - EXPECT_EQ(ret, 5); - - ret = pref->GetInt(PreferencesTest::KEY_TEST_STRING_ELEMENT, 3); - EXPECT_EQ(ret, 3); -} - -/** - * @tc.name: NativePreferencesTest_007 - * @tc.desc: normal testcase of GetLong - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_007, TestSize.Level1) -{ - int64_t ret = pref->GetLong(PreferencesTest::LONG_KEY + 'x', 35L); - EXPECT_EQ(ret, 35L); - - ret = pref->GetLong("", 35L); - EXPECT_EQ(ret, 35L); - - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 5); - pref->PutLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 5L); - pref->Flush(); - - ret = pref->GetLong(PreferencesTest::KEY_TEST_INT_ELEMENT, 3L); - EXPECT_EQ(ret, 3L); - - ret = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 3L); - EXPECT_EQ(ret, 5L); -} - -/** - * @tc.name: NativePreferencesTest_008 - * @tc.desc: normal testcase of GetString - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_008, TestSize.Level1) -{ - std::string ret = pref->GetString(PreferencesTest::LONG_KEY + 'x', "test"); - EXPECT_EQ(ret, "test"); - - ret = pref->GetString("", "test"); - EXPECT_EQ(ret, "test"); - - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 5); - pref->PutString(PreferencesTest::KEY_TEST_LONG_ELEMENT, "test"); - pref->Flush(); - - ret = pref->GetString(PreferencesTest::KEY_TEST_INT_ELEMENT, "defaultvalue"); - EXPECT_EQ(ret, "defaultvalue"); - - ret = pref->GetString(PreferencesTest::KEY_TEST_LONG_ELEMENT, "defaultvalue"); - EXPECT_EQ(ret, "test"); -} - -/** - * @tc.name: NativePreferencesTest_009 - * @tc.desc: normal testcase of GetDefValue - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_009, TestSize.Level1) -{ - int ret0 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, -1); - EXPECT_EQ(ret0, -1); - - float ret1 = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 1.0f); - EXPECT_EQ(ret1, 1.0f); - - int64_t ret2 = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 10000L); - EXPECT_EQ(ret2, 10000L); - - bool ret3 = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); - EXPECT_EQ(ret3, true); - - std::string ret4 = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - EXPECT_EQ(ret4, "test"); -} - -/** - * @tc.name: NativePreferencesTest_010 - * @tc.desc: normal testcase of PutBool - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_010, TestSize.Level1) -{ - pref->PutBool(PreferencesTest::LONG_KEY + 'x', true); - pref->PutBool("", true); - pref->Flush(); - - bool ret = pref->GetBool(PreferencesTest::LONG_KEY + 'x', false); - EXPECT_EQ(ret, false); - ret = pref->GetBool("", false); - EXPECT_EQ(ret, false); - - pref->PutBool(PreferencesTest::LONG_KEY, true); - pref->PutBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); - pref->Flush(); - - ret = pref->GetBool(PreferencesTest::LONG_KEY, false); - EXPECT_EQ(ret, true); - ret = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, false); - EXPECT_EQ(ret, true); -} - -/** - * @tc.name: NativePreferencesTest_011 - * @tc.desc: normal testcase of PutFloat - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_011, TestSize.Level1) -{ - pref->PutFloat(PreferencesTest::LONG_KEY + 'x', 3.0f); - pref->PutFloat("", 3.0f); - pref->Flush(); - - float ret = pref->GetFloat(PreferencesTest::LONG_KEY + 'x', 1.0f); - EXPECT_EQ(ret, 1.0f); - ret = pref->GetFloat("", 1.0f); - EXPECT_EQ(ret, 1.0f); - - pref->PutFloat(PreferencesTest::LONG_KEY, 3.0f); - pref->PutFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 3.0f); - pref->Flush(); - - ret = pref->GetFloat(PreferencesTest::LONG_KEY, 1.0f); - EXPECT_EQ(ret, 3.0f); - ret = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 1.0f); - EXPECT_EQ(ret, 3.0f); -} - -/** - * @tc.name: NativePreferencesTest_012 - * @tc.desc: normal testcase of PutInt - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_012, TestSize.Level1) -{ - pref->PutInt(PreferencesTest::LONG_KEY + 'x', 3); - pref->PutInt("", 3); - pref->Flush(); - - int ret = pref->GetInt(PreferencesTest::LONG_KEY + 'x', 1); - EXPECT_EQ(ret, 1); - ret = pref->GetInt("", 1); - EXPECT_EQ(ret, 1); - - pref->PutInt(PreferencesTest::LONG_KEY, 3); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); - pref->Flush(); - - ret = pref->GetInt(PreferencesTest::LONG_KEY, 1); - EXPECT_EQ(ret, 3); - ret = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 1); - EXPECT_EQ(ret, 3); -} - -/** - * @tc.name: NativePreferencesTest_013 - * @tc.desc: normal testcase of PutLong - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_013, TestSize.Level1) -{ - pref->PutLong(PreferencesTest::LONG_KEY + 'x', 3L); - pref->PutLong("", 3L); - pref->Flush(); - - int64_t ret = pref->GetLong(PreferencesTest::LONG_KEY + 'x', 1L); - EXPECT_EQ(ret, 1L); - ret = pref->GetLong("", 1L); - EXPECT_EQ(ret, 1L); - - pref->PutLong(PreferencesTest::LONG_KEY, 3L); - pref->PutLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 3L); - pref->Flush(); - - ret = pref->GetLong(PreferencesTest::LONG_KEY, 1L); - EXPECT_EQ(ret, 3L); - ret = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 1L); - EXPECT_EQ(ret, 3L); -} - -/** - * @tc.name: NativePreferencesTest_014 - * @tc.desc: normal testcase of PutString - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_014, TestSize.Level1) -{ - pref->PutString(PreferencesTest::LONG_KEY + 'x', "test"); - pref->PutString("", "test"); - pref->Flush(); - - std::string ret = pref->GetString(PreferencesTest::LONG_KEY + 'x', "defaultValue"); - EXPECT_EQ(ret, "defaultValue"); - ret = pref->GetString("", "defaultValue"); - EXPECT_EQ(ret, "defaultValue"); - - pref->PutString(PreferencesTest::LONG_KEY, "test"); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->Flush(); - - ret = pref->GetString(PreferencesTest::LONG_KEY, "defaultValue"); - EXPECT_EQ(ret, "test"); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultValue"); - EXPECT_EQ(ret, "test"); -} - -/** - * @tc.name: NativePreferencesTest_015 - * @tc.desc: normal testcase of Delete - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_015, TestSize.Level1) -{ - pref->PutString("test", "remove"); - pref->Flush(); - - std::string ret = pref->GetString("test", "defaultValue"); - EXPECT_EQ(ret, "remove"); - - pref->Delete("test"); - pref->Flush(); - ret = pref->GetString("test", "defaultValue"); - EXPECT_EQ(ret, "defaultValue"); -} - -/** - * @tc.name: NativePreferencesTest_016 - * @tc.desc: normal testcase of RegisterPreferencesObserver - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_016, TestSize.Level1) -{ - std::shared_ptr counter = std::make_shared(); - pref->RegisterObserver(counter); - - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->Flush(); - EXPECT_EQ(static_cast(counter.get())->notifyTimes, 1); - - /* same value */ - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->Flush(); - EXPECT_EQ(static_cast(counter.get())->notifyTimes, 2); - - pref->UnRegisterObserver(counter); -} - -/** - * @tc.name: NativePreferencesTest_017 - * @tc.desc: normal testcase of UnRegisterPreferencesObserver - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_017, TestSize.Level1) -{ - std::shared_ptr counter = std::make_shared(); - pref->RegisterObserver(counter); - - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->Flush(); - EXPECT_EQ(static_cast(counter.get())->notifyTimes, 2); - - pref->UnRegisterObserver(counter); - - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 6); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test1"); - pref->Flush(); - EXPECT_EQ(static_cast(counter.get())->notifyTimes, 2); -} - -/** - * @tc.name: NativePreferencesTest_018 - * @tc.desc: normal testcase of Clear - * @tc.type: FUNC - * @tc.require: AR000CU2BN - * @tc.author: xiuhongju - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_018, TestSize.Level1) -{ - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); - pref->Flush(); - - pref->Clear(); - std::string ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); - EXPECT_EQ(ret, "defaultvalue"); - int ret1 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 0); - EXPECT_EQ(ret1, 0); - - pref->Flush(); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "defaultvalue"); - EXPECT_EQ(ret, "defaultvalue"); - ret1 = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 0); - EXPECT_EQ(ret1, 0); -} - -/** - * @tc.name: NativePreferencesTest_019 - * @tc.desc: normal testcase of GetDouble - * @tc.type: FUNC - * @tc.require: Na - * @tc.author: mang tsang - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_019, TestSize.Level1) -{ - double ret = pref->GetDouble(PreferencesTest::LONG_KEY + 'x', 35.99999); - EXPECT_EQ(ret, 35.99999); - - ret = pref->GetDouble("", 35.99999); - EXPECT_EQ(ret, 35.99999); - - pref->PutDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT, (std::numeric_limits::max)()); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "5.99"); - pref->Flush(); - - ret = pref->GetDouble(PreferencesTest::KEY_TEST_DOUBLE_ELEMENT, 3.99); - EXPECT_EQ(ret, (std::numeric_limits::max)()); - - ret = pref->GetDouble(PreferencesTest::KEY_TEST_STRING_ELEMENT, 3.99); - EXPECT_EQ(ret, 3.99); -} - -/** - * @tc.name: NativePreferencesTest_020 - * @tc.desc: normal testcase of GetDouble without defaultValue - * @tc.type: FUNC - * @tc.require: Na - * @tc.author: lijuntao - */ -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); - EXPECT_EQ(ret, (std::numeric_limits::max)()); -} - -/** - * @tc.name: NativePreferencesTest_021 - * @tc.desc: normal testcase of GetString without defaultValue - * @tc.type: FUNC - * @tc.require: Na - * @tc.author: lijuntao - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_021, TestSize.Level1) -{ - pref->PutString(PreferencesTest::LONG_KEY, "test"); - pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); - pref->Flush(); - - std::string ret = pref->GetString(PreferencesTest::LONG_KEY); - EXPECT_EQ(ret, "test"); - ret = pref->GetString(PreferencesTest::KEY_TEST_STRING_ELEMENT); - EXPECT_EQ(ret, "test"); -} - -/** - * @tc.name: NativePreferencesTest_022 - * @tc.desc: normal testcase of GetLong without defaultValue - * @tc.type: FUNC - * @tc.require: Na - * @tc.author: lijuntao - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_022, TestSize.Level1) -{ - pref->PutLong(PreferencesTest::LONG_KEY, 3L); - pref->PutLong(PreferencesTest::KEY_TEST_LONG_ELEMENT, 3L); - pref->Flush(); - - int64_t ret = pref->GetLong(PreferencesTest::LONG_KEY); - EXPECT_EQ(ret, 3L); - ret = pref->GetLong(PreferencesTest::KEY_TEST_LONG_ELEMENT); - EXPECT_EQ(ret, 3L); -} - -/** - * @tc.name: NativePreferencesTest_023 - * @tc.desc: normal testcase of GetInt without defaultValue - * @tc.type: FUNC - * @tc.require: Na - * @tc.author: lijuntao - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_023, TestSize.Level1) -{ - pref->PutInt(PreferencesTest::LONG_KEY, 3); - pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 3); - pref->Flush(); - - int32_t ret = pref->GetInt(PreferencesTest::LONG_KEY); - EXPECT_EQ(ret, 3); - ret = pref->GetInt(PreferencesTest::KEY_TEST_INT_ELEMENT); - EXPECT_EQ(ret, 3); -} - -/** - * @tc.name: NativePreferencesTest_024 - * @tc.desc: normal testcase of GetFloat without defaultValue - * @tc.type: FUNC - * @tc.require: Na - * @tc.author: lijuntao - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_024, TestSize.Level1) -{ - pref->PutFloat(PreferencesTest::LONG_KEY, 3.0f); - pref->PutFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT, 3.0f); - pref->Flush(); - - float ret = pref->GetFloat(PreferencesTest::LONG_KEY); - EXPECT_EQ(ret, 3.0f); - ret = pref->GetFloat(PreferencesTest::KEY_TEST_FLOAT_ELEMENT); - EXPECT_EQ(ret, 3.0f); -} - -/** - * @tc.name: NativePreferencesTest_025 - * @tc.desc: normal testcase of GetBool without defaultValue - * @tc.type: FUNC - * @tc.require: Na - * @tc.author: lijuntao - */ -HWTEST_F(PreferencesTest, NativePreferencesTest_025, TestSize.Level1) -{ - pref->PutBool(PreferencesTest::LONG_KEY, true); - pref->PutBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT, true); - pref->Flush(); - - bool ret = pref->GetBool(PreferencesTest::LONG_KEY); - EXPECT_EQ(ret, true); - ret = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT); - EXPECT_EQ(ret, true); -} diff --git a/relational_store/relational_store.gni b/relational_store.gni similarity index 100% rename from relational_store/relational_store.gni rename to relational_store.gni diff --git a/relational_store/README_zh.md b/relational_store/README_zh.md deleted file mode 100644 index 8cdceeb02..000000000 --- a/relational_store/README_zh.md +++ /dev/null @@ -1,54 +0,0 @@ -# 关系型数据库(Relational Database,RDB) - -## 简介 - -**关系型数据库(Relational Database,RDB)** 是一种基于关系模型来管理数据的数据库。OpenHarmony关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制。 - -OpenHarmony关系型数据库底层使用SQLite作为持久化存储引擎,支持SQLite具有的所有数据库特性,包括但不限于事务、索引、视图、触发器、外键、参数化查询和预编译SQL语句。 - -以下是几个基本概念: -- **关系型数据库** - - 创建在关系模型基础上的数据库,以行和列的形式存储数据。 - -- **结果集** - - 指用户查询之后的结果集合,可以对数据进行访问。结果集提供了灵活的数据访问方式,可以更方便的拿到用户想要的数据。 - -- **SQLite数据库** - - 一款轻量级的数据库,是遵守ACID的关系型数据库组件。它是一个开源的项目。 - -**图 1** 关系型数据库运作机制 - - -![](figures/zh-cn_关系型数据库运作机制.png) - -## 目录 - -``` -//foundation/distributeddatamgr/relational_store/ -├── frameworks # 框架层代码 -│ └── js # JS API的实现 -│ │ └── napi # napi代码实现 -│ └── native # 内部接口实现 -├── interfaces # 接口代码 -│ └── inner_api # 内部接口声明 -└── test # 测试用例 - ├── js # js用例 - └── native # C++用例 -``` - -## 约束 - -数据库中连接池的最大数量是4个,用以管理用户的读写操作。 - -为保证数据的准确性,数据库同一时间只能支持一个写操作。 - -## 相关仓 - -- [分布式数据管理子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%88%86%E5%B8%83%E5%BC%8F%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md) - -- [**distributeddatamgr\_relational_store**](https://gitee.com/openharmony/distributeddatamgr_relational_store/blob/master/README_zh.md) - -- [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite) \ No newline at end of file diff --git a/relational_store/test/js/rdb/BUILD.gn b/relational_store/test/js/rdb/BUILD.gn deleted file mode 100644 index 0d5902230..000000000 --- a/relational_store/test/js/rdb/BUILD.gn +++ /dev/null @@ -1,23 +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("//build/test.gni") - -#################################group######################################### -group("unittest") { - testonly = true - deps = [] - - deps += [ "unittest/src:unittest" ] -} -############################################################################### diff --git a/relational_store/test/js/rdb/unittest/src/config.json b/relational_store/test/js/rdb/unittest/src/config.json deleted file mode 100644 index c5d825604..000000000 --- a/relational_store/test/js/rdb/unittest/src/config.json +++ /dev/null @@ -1,60 +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": [ - "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/js/BUILD.gn b/test/js/dataability/BUILD.gn similarity index 100% rename from preferences/test/js/BUILD.gn rename to test/js/dataability/BUILD.gn diff --git a/relational_store/test/js/dataability/unittest/src/BUILD.gn b/test/js/dataability/unittest/src/BUILD.gn similarity index 100% rename from relational_store/test/js/dataability/unittest/src/BUILD.gn rename to test/js/dataability/unittest/src/BUILD.gn diff --git a/relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js b/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js similarity index 100% rename from relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js rename to test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js diff --git a/preferences/test/js/unittest/src/config.json b/test/js/dataability/unittest/src/config.json similarity index 100% rename from preferences/test/js/unittest/src/config.json rename to test/js/dataability/unittest/src/config.json diff --git a/relational_store/test/js/dataability/BUILD.gn b/test/js/rdb/BUILD.gn similarity index 100% rename from relational_store/test/js/dataability/BUILD.gn rename to test/js/rdb/BUILD.gn diff --git a/relational_store/test/js/rdb/unittest/src/BUILD.gn b/test/js/rdb/unittest/src/BUILD.gn similarity index 100% rename from relational_store/test/js/rdb/unittest/src/BUILD.gn rename to test/js/rdb/unittest/src/BUILD.gn diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js b/test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js rename to test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js b/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js rename to test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js b/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js rename to test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreChangeEncryptKeyJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreChangeEncryptKeyJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreChangeEncryptKeyJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreChangeEncryptKeyJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js b/test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js rename to test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js b/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js rename to test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js b/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js similarity index 100% rename from relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js rename to test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js diff --git a/relational_store/test/js/dataability/unittest/src/config.json b/test/js/rdb/unittest/src/config.json similarity index 100% rename from relational_store/test/js/dataability/unittest/src/config.json rename to test/js/rdb/unittest/src/config.json diff --git a/relational_store/test/native/dataability/BUILD.gn b/test/native/dataability/BUILD.gn similarity index 100% rename from relational_store/test/native/dataability/BUILD.gn rename to test/native/dataability/BUILD.gn diff --git a/relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp b/test/native/dataability/unittest/data_ability_predicates_test.cpp similarity index 100% rename from relational_store/test/native/dataability/unittest/data_ability_predicates_test.cpp rename to test/native/dataability/unittest/data_ability_predicates_test.cpp diff --git a/relational_store/test/native/rdb/BUILD.gn b/test/native/rdb/BUILD.gn similarity index 100% rename from relational_store/test/native/rdb/BUILD.gn rename to test/native/rdb/BUILD.gn diff --git a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn b/test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn similarity index 100% rename from relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn rename to test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn diff --git a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/corpus/init b/test/native/rdb/fuzztest/rdbimpl_fuzzer/corpus/init similarity index 100% rename from relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/corpus/init rename to test/native/rdb/fuzztest/rdbimpl_fuzzer/corpus/init diff --git a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/project.xml b/test/native/rdb/fuzztest/rdbimpl_fuzzer/project.xml similarity index 100% rename from relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/project.xml rename to test/native/rdb/fuzztest/rdbimpl_fuzzer/project.xml diff --git a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp b/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp similarity index 100% rename from relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp rename to test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp diff --git a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.h b/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.h similarity index 100% rename from relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.h rename to test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.h diff --git a/relational_store/test/native/rdb/unittest/common.h b/test/native/rdb/unittest/common.h similarity index 100% rename from relational_store/test/native/rdb/unittest/common.h rename to test/native/rdb/unittest/common.h diff --git a/relational_store/test/native/rdb/unittest/logger.h b/test/native/rdb/unittest/logger.h similarity index 100% rename from relational_store/test/native/rdb/unittest/logger.h rename to test/native/rdb/unittest/logger.h diff --git a/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp b/test/native/rdb/unittest/rdb_attach_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_attach_test.cpp rename to test/native/rdb/unittest/rdb_attach_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_delete_test.cpp b/test/native/rdb/unittest/rdb_delete_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_delete_test.cpp rename to test/native/rdb/unittest/rdb_delete_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp b/test/native/rdb/unittest/rdb_distributed_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp rename to test/native/rdb/unittest/rdb_distributed_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_encrypt_test.cpp b/test/native/rdb/unittest/rdb_encrypt_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_encrypt_test.cpp rename to test/native/rdb/unittest/rdb_encrypt_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp b/test/native/rdb/unittest/rdb_execute_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_execute_test.cpp rename to test/native/rdb/unittest/rdb_execute_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_helper_test.cpp b/test/native/rdb/unittest/rdb_helper_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_helper_test.cpp rename to test/native/rdb/unittest/rdb_helper_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp b/test/native/rdb/unittest/rdb_insert_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_insert_test.cpp rename to test/native/rdb/unittest/rdb_insert_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp b/test/native/rdb/unittest/rdb_open_callback_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_open_callback_test.cpp rename to test/native/rdb/unittest/rdb_open_callback_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_predicates_join_test.cpp b/test/native/rdb/unittest/rdb_predicates_join_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_predicates_join_test.cpp rename to test/native/rdb/unittest/rdb_predicates_join_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp b/test/native/rdb/unittest/rdb_predicates_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp rename to test/native/rdb/unittest/rdb_predicates_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp b/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp rename to test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp b/test/native/rdb/unittest/rdb_step_result_set_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp rename to test/native/rdb/unittest/rdb_step_result_set_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_store_concurrent_test.cpp b/test/native/rdb/unittest/rdb_store_concurrent_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_store_concurrent_test.cpp rename to test/native/rdb/unittest/rdb_store_concurrent_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp b/test/native/rdb/unittest/rdb_store_config_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp rename to test/native/rdb/unittest/rdb_store_config_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_store_interface_test.cpp b/test/native/rdb/unittest/rdb_store_interface_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_store_interface_test.cpp rename to test/native/rdb/unittest/rdb_store_interface_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp b/test/native/rdb/unittest/rdb_transaction_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp rename to test/native/rdb/unittest/rdb_transaction_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_update_test.cpp b/test/native/rdb/unittest/rdb_update_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_update_test.cpp rename to test/native/rdb/unittest/rdb_update_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_upgrade_test.cpp b/test/native/rdb/unittest/rdb_upgrade_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_upgrade_test.cpp rename to test/native/rdb/unittest/rdb_upgrade_test.cpp diff --git a/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp b/test/native/rdb/unittest/rdb_value_bucket_test.cpp similarity index 100% rename from relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp rename to test/native/rdb/unittest/rdb_value_bucket_test.cpp diff --git a/relational_store/test/native/rdb_data_share_adapter/BUILD.gn b/test/native/rdb_data_share_adapter/BUILD.gn similarity index 100% rename from relational_store/test/native/rdb_data_share_adapter/BUILD.gn rename to test/native/rdb_data_share_adapter/BUILD.gn diff --git a/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp b/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp similarity index 100% rename from relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp rename to test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp