diff --git a/data_object/frameworks/innerkitsimpl/include/communicator/softbus_adapter.h b/data_object/frameworks/innerkitsimpl/include/communicator/softbus_adapter.h index e91d39bc5882345504700ead1360830842bf9e55..4366b5a2c21a2c526f08b37b19d037cb255a35d0 100644 --- a/data_object/frameworks/innerkitsimpl/include/communicator/softbus_adapter.h +++ b/data_object/frameworks/innerkitsimpl/include/communicator/softbus_adapter.h @@ -34,8 +34,7 @@ public: SoftBusAdapter(); ~SoftBusAdapter(); static std::shared_ptr GetInstance(); - - void Init(); + // add DeviceChangeListener to watch device change; Status StartWatchDeviceChange(const AppDeviceStatusChangeListener *observer, const PipeInfo &pipeInfo); // stop DeviceChangeListener to watch device change; @@ -97,7 +96,6 @@ private: std::mutex busSessionMutex_{}; std::map busSessionMap_{}; bool flag_ = true; // only for br flag - INodeStateCb nodeStateCb_{}; ISessionListener sessionListener_{}; std::mutex statusMutex_ {}; std::map>> sessionsStatus_; diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp index 419d9ba4b18aa1b7f37e69be1172156290278079..1e1722ab1d4cba1f1c54f99fd1e4b1af639d2e56 100644 --- a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp @@ -39,7 +39,7 @@ void PutNum(void *val, uint32_t offset, uint32_t valLen, Bytes &data) uint32_t GetNum(Bytes &data, uint32_t offset, void *val, uint32_t valLen) { - uint8_t *value = (uint8_t *)val; + uint8_t *value = static_cast(val); uint32_t len = offset + valLen; uint32_t dataLen = data.size(); if (dataLen < len) { diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp index 60ad24c74f94256bb2dc305eff3c89f0bbef574c..cb9bd9fe389ece3e5947c7a61d417af391ef613b 100644 --- a/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp @@ -149,7 +149,7 @@ uint32_t FlatObjectStorageEngine::GetTable(const std::string &key, std::mapGetEntries(emptyKey, resultSet); - if (status != DistributedDB::DBStatus::OK) { + if (status != DistributedDB::DBStatus::OK || resultSet == nullptr) { LOG_INFO("FlatObjectStorageEngine::GetTable %{public}s GetEntries fail", key.c_str()); return ERR_DB_GET_FAIL; } diff --git a/data_object/frameworks/innerkitsimpl/src/communicator/app_device_handler.cpp b/data_object/frameworks/innerkitsimpl/src/communicator/app_device_handler.cpp index 2a9eaf3fe13f3299871182204d3183f728ad3d26..9518c61ea6a6c02c5dd8f0240920ca2eac220a59 100644 --- a/data_object/frameworks/innerkitsimpl/src/communicator/app_device_handler.cpp +++ b/data_object/frameworks/innerkitsimpl/src/communicator/app_device_handler.cpp @@ -31,7 +31,6 @@ AppDeviceHandler::~AppDeviceHandler() } void AppDeviceHandler::Init() { - softbusAdapter_->Init(); devManager_->RegisterDevCallback(); } diff --git a/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp b/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp index d8cb66136067525dbe6e819dbdc790144bf9121a..c14f0088852b2211f9bfa09ae34bfa7e4fcbd4ab 100644 --- a/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp +++ b/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp @@ -69,6 +69,21 @@ void DMStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) { } +class DmDeathCallback : public DmInitCallback { +public: + explicit DmDeathCallback(DevManager &devManager) : devManager_(devManager){}; + void OnRemoteDied() override; + +private: + DevManager &devManager_; +}; + +void DmDeathCallback::OnRemoteDied() +{ + LOG_INFO("dm device manager died, init it again"); + devManager_.RegisterDevCallback(); +} + void DMStateCallback::NotifyAll(const DmDeviceInfo &deviceInfo, DeviceChangeType type) { DeviceInfo di = { std::string(deviceInfo.networkId), std::string(deviceInfo.deviceName), @@ -87,7 +102,7 @@ DevManager::~DevManager() int32_t DevManager::Init() { auto &deviceManager = DeviceManager::GetInstance(); - std::shared_ptr deviceInitCallback = nullptr; + auto deviceInitCallback = std::make_shared(*this); auto deviceStateCallback = std::make_shared(SoftBusAdapter::GetInstance()); int32_t status = deviceManager.InitDeviceManager(PKG_NAME, deviceInitCallback); if (status != DM_OK) { diff --git a/data_object/frameworks/innerkitsimpl/src/communicator/softbus_adapter_standard.cpp b/data_object/frameworks/innerkitsimpl/src/communicator/softbus_adapter_standard.cpp index 8c1d9fba5dd8f4c25cb933f2623eb5ca911093a5..3a58c272684803887bcd51fe494a7ec79475bfc0 100644 --- a/data_object/frameworks/innerkitsimpl/src/communicator/softbus_adapter_standard.cpp +++ b/data_object/frameworks/innerkitsimpl/src/communicator/softbus_adapter_standard.cpp @@ -70,32 +70,6 @@ SoftBusAdapter::SoftBusAdapter() SoftBusAdapter::~SoftBusAdapter() { - LOG_INFO("begin"); - int32_t errNo = UnregNodeDeviceStateCb(&nodeStateCb_); - if (errNo != SOFTBUS_OK) { - LOG_ERROR("UnregNodeDeviceStateCb fail %{public}d", errNo); - } -} - -void SoftBusAdapter::Init() -{ - LOG_INFO("begin"); - std::thread th = std::thread([&]() { - int i = 0; - constexpr int RETRY_TIMES = 300; - while (i++ < RETRY_TIMES) { - int32_t errNo = RegNodeDeviceStateCb("ohos.objectstore", &nodeStateCb_); - if (errNo != SOFTBUS_OK) { - LOG_ERROR("RegNodeDeviceStateCb fail %{public}d, time:%{public}d", errNo, i); - std::this_thread::sleep_for(std::chrono::seconds(1)); - continue; - } - LOG_INFO("RegNodeDeviceStateCb success"); - return; - } - LOG_ERROR("Init failed %{public}d times and exit now.", RETRY_TIMES); - }); - th.detach(); } Status SoftBusAdapter::StartWatchDeviceChange( diff --git a/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/distributed_test_agent.cpp b/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/distributed_test_agent.cpp index eafae9430f55841ec145cf94a9b5a1221267559d..c8bb4766f15a8aa7104b4a84d268b54c33876e98 100644 --- a/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/distributed_test_agent.cpp +++ b/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/distributed_test_agent.cpp @@ -250,11 +250,7 @@ int DistributedTestAgent::RevokeSave(const std::string &strMsg, std::string &str if (object != nullptr) { object->PutString("name", putValue); std::vector devices = SoftBusAdapter::GetInstance()->GetDeviceList(); - std::vector deviceIds; - for (auto item : devices) { - deviceIds.push_back(item.deviceId); - } - std::string networkId = SoftBusAdapter::GetInstance()->ToNodeID(deviceIds[0]); + std::string networkId = SoftBusAdapter::GetInstance()->ToNodeID(devices[0].deviceId); object->Save(networkId); uint32_t status = object->RevokeSave(); if (status != SUCCESS) { @@ -282,11 +278,7 @@ int DistributedTestAgent::SaveRemote(const std::string &strMsg, std::string &str { if (DistributedTestAgent::objectSession_ != nullptr) { std::vector devices = SoftBusAdapter::GetInstance()->GetDeviceList(); - std::vector deviceIds; - for (auto item : devices) { - deviceIds.push_back(item.deviceId); - } - std::string networkId = SoftBusAdapter::GetInstance()->ToNodeID(deviceIds[0]); + std::string networkId = SoftBusAdapter::GetInstance()->ToNodeID(devices[0].deviceId); DistributedTestAgent::objectSession_->Save(networkId); strReturnValue = "SaveRemote succsess"; } else { diff --git a/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/objectstore_fuzzer.cpp b/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/objectstore_fuzzer.cpp index b92feb16a15a33fe24b55a1b2c2edfe4fda0c178..0c4db0eca0516b09fb2e68cce779e8b213c3bf08 100644 --- a/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/objectstore_fuzzer.cpp +++ b/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/objectstore_fuzzer.cpp @@ -193,6 +193,40 @@ bool GetComplexFuzz(const uint8_t *data, size_t size) objectStore_->DeleteObject(SESSIONID); return result; } + + +bool GetTypeFuzz(const uint8_t *data, size_t size) +{ + bool result = false; + if (SUCCESS != SetUpTestCase()) { + return false; + } + std::string skey(data, data + size); + Type val; + uint32_t ret = object_->GetType(skey, val); + if (!ret) { + result = true; + } + objectStore_->DeleteObject(SESSIONID); + return result; +} + +bool SaveFuzz(const uint8_t *data, size_t size) +{ + bool result = false; + if (SUCCESS != SetUpTestCase()) { + return false; + } + std::string skey(data, data + size); + uint32_t ret = object_->Save(skey); + if (!ret) { + result = true; + } + objectStore_->DeleteObject(SESSIONID); + return result; +} + + } /* Fuzzer entry point */ @@ -206,6 +240,8 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) OHOS::GetBooleanFuzz(data, size); OHOS::GetStringFuzz(data, size); OHOS::GetComplexFuzz(data, size); + OHOS::GetTypeFuzz(data, size); + OHOS::SaveFuzz(data, size); /* Run your code on data */ return 0; } \ No newline at end of file diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/object_store_test.cpp b/data_object/frameworks/innerkitsimpl/test/unittest/object_store_test.cpp index 39cbc362986b2bf53561d01a05e8e4111efaa7c1..c93681124a44b6cedf39fac64a5975693b76049f 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/object_store_test.cpp +++ b/data_object/frameworks/innerkitsimpl/test/unittest/object_store_test.cpp @@ -17,9 +17,15 @@ #include #include + #include "distributed_object.h" #include "distributed_objectstore.h" #include "objectstore_errors.h" +#include "store_observer.h" +#include "auto_launch_export.h" +#include "kv_store_delegate_manager.h" +#include "flat_object_store.h" +#include "distributed_objectstore_impl.h" using namespace testing::ext; using namespace OHOS::ObjectStore; @@ -32,7 +38,7 @@ static void TestSetSessionId(std::string bundleName, std::string sessionId) EXPECT_NE(nullptr, objectStore); DistributedObject *object = objectStore->CreateObject(sessionId); EXPECT_NE(nullptr, object); - + uint32_t ret = objectStore->DeleteObject(sessionId); EXPECT_EQ(SUCCESS, ret); } @@ -43,19 +49,19 @@ static void TestSaveAndRevokeSave(std::string bundleName, std::string sessionId) EXPECT_NE(nullptr, objectStore); DistributedObject *object = objectStore->CreateObject(sessionId); EXPECT_NE(nullptr, object); - + uint32_t ret = object->PutString("name", "zhangsan"); EXPECT_EQ(SUCCESS, ret); ret = object->PutDouble("salary", SALARY); EXPECT_EQ(SUCCESS, ret); ret = object->PutBoolean("isTrue", true); EXPECT_EQ(SUCCESS, ret); - + ret = object->Save("local"); EXPECT_EQ(SUCCESS, ret); ret = object->RevokeSave(); EXPECT_EQ(SUCCESS, ret); - + ret = objectStore->DeleteObject(sessionId); EXPECT_EQ(SUCCESS, ret); } @@ -99,10 +105,46 @@ HWTEST_F(NativeObjectStoreTest, DistributedObjectStore_Create_Destroy_001, TestS std::string sessionId = "123456"; DistributedObjectStore *objectStore = DistributedObjectStore::GetInstance(bundleName); EXPECT_NE(nullptr, objectStore); - + + DistributedObject *object = objectStore->CreateObject(sessionId); + EXPECT_NE(nullptr, object); + + uint32_t ret = objectStore->DeleteObject(sessionId); + EXPECT_EQ(SUCCESS, ret); +} + +/** + * @tc.name: DistributedObjectStore_Create_Destroy_002 + * @tc.desc: test Create DistributedObject and Destroy DistrbutedObject + * @tc.type: FUNC + */ +HWTEST_F(NativeObjectStoreTest, DistributedObjectStore_Create_Destroy_002, TestSize.Level1) +{ + std::string sessionId = "123456"; + + auto objectStore = new DistributedObjectStoreImpl(nullptr); + DistributedObject *object = objectStore->CreateObject(sessionId); + EXPECT_EQ(nullptr, object); +} + +/** + * @tc.name: DistributedObjectStore_Create_Destroy_003 + * @tc.desc: test Create DistributedObject and Destroy DistrbutedObject + * @tc.type: FUNC + */ +HWTEST_F(NativeObjectStoreTest, DistributedObjectStore_Create_Destroy_003, TestSize.Level1) +{ + std::string bundleName = "default"; + std::string sessionId = "123456"; + DistributedObjectStore *objectStore = DistributedObjectStore::GetInstance(bundleName); + EXPECT_NE(nullptr, objectStore); + DistributedObject *object = objectStore->CreateObject(sessionId); EXPECT_NE(nullptr, object); + DistributedObject *object2 = objectStore->CreateObject(sessionId); + EXPECT_EQ(nullptr, object2); + uint32_t ret = objectStore->DeleteObject(sessionId); EXPECT_EQ(SUCCESS, ret); } @@ -118,7 +160,7 @@ HWTEST_F(NativeObjectStoreTest, DistributedObjectStore_Get_001, TestSize.Level1) std::string sessionId = "123456"; DistributedObjectStore *objectStore = DistributedObjectStore::GetInstance(bundleName); EXPECT_NE(nullptr, objectStore); - + DistributedObject *object = objectStore->CreateObject(sessionId); EXPECT_NE(nullptr, object); @@ -222,7 +264,6 @@ HWTEST_F(NativeObjectStoreTest, DistributedObject_Boolean_001, TestSize.Level1) uint32_t ret = object->PutBoolean("isTrue", true); EXPECT_EQ(SUCCESS, ret); - bool value = false; ret = object->GetBoolean("isTrue", value); EXPECT_EQ(SUCCESS, ret); diff --git a/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h b/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h index 65d9da5c0ba65bb1a6a507fbf22b6f2434af1ea1..33b8cf7c9bf2ca6f76282114193867a8084bd5c6 100644 --- a/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h +++ b/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h @@ -31,6 +31,13 @@ namespace OHOS::ObjectStore { return; \ } \ } +#define CHECK_EQUAL_WITH_RETURN_FALSE(status, value) \ + { \ + if (status != value) { \ + LOG_ERROR("error! %{public}d %{public}d", status, value); \ + return false; \ + } \ + } #define ASSERT_MATCH_ELSE_RETURN_VOID(condition) \ { \ if (!(condition)) { \ diff --git a/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h b/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h index 6cfcda79e05ce065770a126a594afcaad2cca30a..f468b56a775b479d6d6780e62137f98f76d7b979 100644 --- a/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h +++ b/data_object/frameworks/jskitsimpl/include/adaptor/js_distributedobjectstore.h @@ -43,6 +43,7 @@ private: const std::string &sessionId, napi_value callback = nullptr); static bool CheckSyncPermission(); static void RestoreWatchers(napi_env env, JSObjectWrapper *wrapper, const std::string &objectId); + static bool GetBundleNameWithContext(napi_env env, napi_value argv, std::string &bundleName); static std::string GetBundleName(napi_env env); static bool IsSandBox(); static std::atomic sequenceNum_; diff --git a/data_object/frameworks/jskitsimpl/include/common/js_util.h b/data_object/frameworks/jskitsimpl/include/common/js_util.h index 4de08f8e13424c77e7df14cf58dc35c03e7b22d9..72b762a39a5e160ad6ced78d741d8a4950c47f37 100644 --- a/data_object/frameworks/jskitsimpl/include/common/js_util.h +++ b/data_object/frameworks/jskitsimpl/include/common/js_util.h @@ -49,16 +49,34 @@ public: static void GenerateNapiError(napi_env env, int32_t status, int32_t &errCode, std::string &errMessage); }; -#define NAPI_ASSERT_ERRCODE(env, assertion, version, err) \ +#define NAPI_ASSERT_ERRCODE(env, assertion, version, err) \ + do { \ + if (!(assertion)) { \ + if ((version) >= 9) { \ + napi_throw_error((env), std::to_string((err)->GetCode()).c_str(), (err)->GetMessage().c_str()); \ + } \ + return nullptr; \ + } \ + } while (0) + +#define CHECH_STATUS_ERRCODE(env, condition, err) \ do { \ - if (!(assertion)) { \ - if (version >= 9) { \ - napi_throw_error((env), std::to_string(err->GetCode()).c_str(), err->GetMessage().c_str()); \ - } \ + if (!(condition)) { \ + napi_throw_error((env), std::to_string((err)->GetCode()).c_str(), (err)->GetMessage().c_str()); \ return nullptr; \ } \ } while (0) +#define CHECH_STATUS_RETURN_VOID(env, condition, ctxt, info) \ + do { \ + if (!(condition)) { \ + LOG_ERROR(info); \ + (ctxt)->status = napi_generic_failure; \ + (ctxt)->message = std::string(info); \ + return; \ + } \ + } while (0) + #define LOG_ERROR_RETURN(condition, message, retVal) \ do { \ if (!(condition)) { \ diff --git a/data_object/frameworks/jskitsimpl/include/common/object_error.h b/data_object/frameworks/jskitsimpl/include/common/object_error.h index 54d8f29c50cca692563ae5b915b286d66c575607..a982e9bcb45469bc1c9b4ecc693586dfdde514bd 100644 --- a/data_object/frameworks/jskitsimpl/include/common/object_error.h +++ b/data_object/frameworks/jskitsimpl/include/common/object_error.h @@ -15,6 +15,7 @@ #ifndef OBJECT_ERROR_H #define OBJECT_ERROR_H + #include namespace OHOS { diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp index aa09b722267950d968aecee0ab6011f54bff054a..c71897fe609b47d2ccf53f6481e88606a704f976 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp @@ -228,10 +228,8 @@ napi_value JSDistributedObject::JSSave(napi_env env, napi_callback_info info) std::string deviceId; DistributedObject *object; }; - auto ctxt = std::make_shared(); std::function getCbOpe = [env, ctxt](size_t argc, napi_value *argv) { - // required 1 arguments :: CHECK_ARGS_RETURN_VOID(ctxt, argc >= 2, "arguments error", std::make_shared("1 or 2")); napi_valuetype valueType = napi_undefined; ctxt->status = napi_typeof(env, argv[0], &valueType); @@ -249,39 +247,29 @@ napi_value JSDistributedObject::JSSave(napi_env env, napi_callback_info info) ctxt->object = wrapper->GetObject(); }; ctxt->GetCbInfo(env, info, getCbOpe); - if (ctxt->status == napi_invalid_arg) { - napi_throw_error((env), std::to_string(ctxt->error->GetCode()).c_str(), ctxt->error->GetMessage().c_str()); - return nullptr; - } + CHECH_STATUS_ERRCODE(env, ctxt->status != napi_invalid_arg, ctxt->error); auto output = [env, ctxt](napi_value &result) { if (ctxt->status == napi_ok) { - ctxt->status = napi_new_instance(env, - JSDistributedObject::GetSaveResultCons(env, ctxt->object->GetSessionId(), ctxt->version, ctxt->deviceId), - 0, nullptr, &result); + std::string &sessionId = ctxt->object->GetSessionId(); + ctxt->status = napi_new_instance( + env, GetSaveResultCons(env, sessionId, ctxt->version, ctxt->deviceId), 0, nullptr, &result); CHECK_STATUS_RETURN_VOID(ctxt, "output failed!"); } }; - return NapiQueue::AsyncWork( - env, ctxt, std::string(__FUNCTION__), - [ctxt]() { - LOG_INFO("start"); - if (ctxt->object == nullptr) { - LOG_ERROR("object is null"); - ctxt->status = napi_generic_failure; - ctxt->message = std::string("object is null"); - return; - } - uint32_t status = ctxt->object->Save(ctxt->deviceId); - if (status != SUCCESS) { - LOG_ERROR("Save failed, status = %{public}d", status); - ctxt->status = napi_generic_failure; - ctxt->message = std::string("operation failed"); - return; - } - ctxt->status = napi_ok; - LOG_INFO("end"); - }, - output); + auto execute = [ctxt]() { + LOG_INFO("start"); + CHECH_STATUS_RETURN_VOID(env, ctxt->object != nullptr, ctxt, "object is null"); + uint32_t status = ctxt->object->Save(ctxt->deviceId); + if (status != SUCCESS) { + LOG_ERROR("Save failed, status = %{public}d", status); + ctxt->status = napi_generic_failure; + ctxt->message = std::string("operation failed"); + return; + } + ctxt->status = napi_ok; + LOG_INFO("end"); + }; + return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } // revokeSave(callback?:AsyncCallback): void; @@ -319,12 +307,7 @@ napi_value JSDistributedObject::JSRevokeSave(napi_env env, napi_callback_info in env, ctxt, std::string(__FUNCTION__), [ctxt]() { LOG_INFO("start"); - if (ctxt->object == nullptr) { - LOG_ERROR("object is null"); - ctxt->status = napi_generic_failure; - ctxt->message = std::string("object is null"); - return; - } + CHECH_STATUS_RETURN_VOID(env, ctxt->object != nullptr, ctxt, "object is null"); uint32_t status = ctxt->object->RevokeSave(); if (status != SUCCESS) { LOG_ERROR("Save failed, status = %{public}d", status); diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp index 1088248760de116848907fd21e4bb37ab95c5040..368a6a5cadeddf3d3086666a87180027960cb5ff 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp @@ -52,48 +52,54 @@ bool JSDistributedObjectStore::AddCallback(napi_env env, ConcurrentMap &lists) +{ + for (auto iter = lists.begin(); iter != lists.end();) { + if (*iter == nullptr) { + iter++; + continue; + } + napi_status status = napi_delete_reference(env, *iter); + CHECK_EQUAL_WITH_RETURN_FALSE(status, napi_ok); + iter = lists.erase(iter); + } + return false; +} + +bool DeleteSingleCallback(napi_env env, std::list &lists, napi_value callback) +{ + napi_value callbackTmp; + for (auto iter = lists.begin(); iter != lists.end();) { + if (*iter == nullptr) { + iter++; + continue; + } + napi_status status = napi_get_reference_value(env, *iter, &callbackTmp); + CHECK_EQUAL_WITH_RETURN_FALSE(status, napi_ok); + bool isEquals = false; + napi_strict_equals(env, callbackTmp, callback, &isEquals); + if (isEquals) { + napi_delete_reference(env, *iter); + iter = lists.erase(iter); + } else { + iter++; + } + } + return !lists.empty(); +} + bool JSDistributedObjectStore::DelCallback(napi_env env, ConcurrentMap> &callbacks, const std::string &sessionId, napi_value callback) { LOG_INFO("del callback %{public}s", sessionId.c_str()); - bool result = true; - result = callbacks.ComputeIfPresent(sessionId, [&env, callback](const std::string &key, std::list &lists) { - napi_status status; + auto execute = [&env, callback](const std::string &key, std::list &lists) { if (callback == nullptr) { - for (auto iter = lists.begin(); iter != lists.end();) { - if (*iter != nullptr) { - status = napi_delete_reference(env, *iter); - if (status != napi_ok) { - LOG_ERROR("error! %{public}d %{public}d", status, napi_ok); - return false; - } - iter = lists.erase(iter); - } else { - iter++; - } - } - return true; + return DeleteAllCallback(env, lists); } else { - napi_value callbackTmp; - for (auto iter = lists.begin(); iter != lists.end();) { - status = napi_get_reference_value(env, *iter, &callbackTmp); - if (status != napi_ok) { - LOG_ERROR("error! %{public}d %{public}d", status, napi_ok); - return false; - } - bool isEquals = false; - napi_strict_equals(env, callbackTmp, callback, &isEquals); - if (isEquals) { - napi_delete_reference(env, *iter); - iter = lists.erase(iter); - } else { - iter++; - } - } - return !lists.empty(); + return DeleteSingleCallback(env, lists, callback); } - }); - return result; + }; + return callbacks.ComputeIfPresent(sessionId, execute); } napi_value JSDistributedObjectStore::NewDistributedObject( @@ -111,7 +117,7 @@ napi_value JSDistributedObjectStore::NewDistributedObject( LOG_WARN("objectWrapper is nullptr."); return; } - auto objectWrapper = (JSObjectWrapper *)data; + auto objectWrapper = static_cast(data); if (objectWrapper->GetObject() == nullptr) { delete objectWrapper; return; @@ -170,17 +176,11 @@ napi_value JSDistributedObjectStore::JSCreateObjectSync(napi_env env, napi_callb NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); std::string bundleName = ""; if (argc > requireArgc) { - napi_valuetype objectType = napi_undefined; - status = napi_typeof(env, argv[3], &objectType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, objectType == napi_object, version, - std::make_shared("context", "Context")); - static std::shared_ptr context_ = JSAbility::GetContext(env, argv[3]); - bundleName = context_->GetBundleName(); + bool executeResult = JSDistributedObjectStore::GetBundleNameWithContext(env, argv[3], bundleName); + NAPI_ASSERT_ERRCODE(env, executeResult, version, innerError); } else { bundleName = JSDistributedObjectStore::GetBundleName(env); } - DistributedObjectStore *objectInfo = DistributedObjectStore::GetInstance(bundleName); NAPI_ASSERT_ERRCODE(env, objectInfo != nullptr, version, innerError); uint32_t result = 0; @@ -223,8 +223,10 @@ napi_value JSDistributedObjectStore::JSDestroyObjectSync(napi_env env, napi_call return nullptr; } -// function on(version: number, type: 'change', object: DistributedObject, callback: Callback): void; -// function on(version: number, type: 'status', object: DistributedObject, callback: Callback): void; +// function on(version: number, type: 'change', object: DistributedObject, +// callback: Callback): void; +// function on(version: number, type: 'status', object: DistributedObject, +// callback: Callback): void; napi_value JSDistributedObjectStore::JSOn(napi_env env, napi_callback_info info) { double version = 8; @@ -271,8 +273,10 @@ napi_value JSDistributedObjectStore::JSOn(napi_env env, napi_callback_info info) return result; } -// function off(version: number, type: 'change', object: DistributedObject, callback?: Callback): void; -// function off(version: number, type: 'status', object: DistributedObject, callback?: Callback): void; +// function off(version: number, type: 'change', object: DistributedObject, +// callback?: Callback): void; +// function off(version: number, type: 'status', object: DistributedObject, +// callback?: Callback): void; napi_value JSDistributedObjectStore::JSOff(napi_env env, napi_callback_info info) { double version = 8; @@ -320,6 +324,21 @@ napi_value JSDistributedObjectStore::JSOff(napi_env env, napi_callback_info info return result; } +bool JSDistributedObjectStore::GetBundleNameWithContext(napi_env env, napi_value argv, std::string &bundleName) +{ + napi_valuetype objectType = napi_undefined; + napi_status status = napi_typeof(env, argv, &objectType); + if (status == napi_ok && objectType == napi_object) { + std::shared_ptr context = JSAbility::GetContext(env, argv); + if (context != nullptr) { + bundleName = context->GetBundleName(); + return true; + } + } + LOG_ERROR("arguments error, context."); + return false; +} + std::string JSDistributedObjectStore::GetBundleName(napi_env env) { static std::string bundleName; @@ -365,8 +384,10 @@ void JSDistributedObjectStore::RestoreWatchers(napi_env env, JSObjectWrapper *wr } } -// function recordCallback(version: number, type: 'change', objectId: string, callback: Callback): void; -// function recordCallback(version: number, type: 'status', objectId: string, callback: Callback): void; +// function recordCallback(version: number, type: 'change', objectId: string, +// callback: Callback): void; +// function recordCallback(version: number, type: 'status', objectId: string, +// callback: Callback): void; napi_value JSDistributedObjectStore::JSRecordCallback(napi_env env, napi_callback_info info) { double version = 8; @@ -414,8 +435,10 @@ napi_value JSDistributedObjectStore::JSRecordCallback(napi_env env, napi_callbac return result; } -// function deleteCallback(version: number, type: 'change', objectId: string, callback?: Callback): void; -// function deleteCallback(version: number, type: 'status', objectId: string, callback?: Callback): void; +// function deleteCallback(version: number, type: 'change', objectId: string, +// callback?: Callback): void; +// function deleteCallback(version: number, type: 'status', objectId: string, +// callback?: Callback): void; napi_value JSDistributedObjectStore::JSDeleteCallback(napi_env env, napi_callback_info info) { double version = 8; @@ -459,7 +482,7 @@ napi_value JSDistributedObjectStore::JSDeleteCallback(napi_env env, napi_callbac status = napi_typeof(env, argv[3], &callbackType); NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); NAPI_ASSERT_ERRCODE(env, callbackType == napi_function, version, - std::make_shared("callback", "founction")); + std::make_shared("callback", "function")); if (!strcmp(CHANGE, type)) { delResult = DelCallback(env, g_changeCallBacks, objectId, argv[3]); } else if (!strcmp(STATUS, type)) { diff --git a/data_object/frameworks/jskitsimpl/src/common/js_util.cpp b/data_object/frameworks/jskitsimpl/src/common/js_util.cpp index e43d3708e3d4564282bf9cedb5ab4121a31d9504..ae82150e8284df3083b041241a267fcfffe815a6 100644 --- a/data_object/frameworks/jskitsimpl/src/common/js_util.cpp +++ b/data_object/frameworks/jskitsimpl/src/common/js_util.cpp @@ -134,7 +134,7 @@ napi_status JSUtil::GetValue(napi_env env, napi_value in, std::vector & LOG_ERROR_RETURN(status == napi_ok, "napi_get_typedarray_info failed!", napi_invalid_arg); LOG_ERROR_RETURN(type == napi_uint8_array, "is not Uint8Array!", napi_invalid_arg); LOG_ERROR_RETURN((length > 0) && (data != nullptr), "invalid data!", napi_invalid_arg); - out.assign((uint8_t *)data, ((uint8_t *)data) + length); + out.assign(static_cast(data), static_cast(data) + length); return status; } diff --git a/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp b/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp index 16514ced13774fda56a86bd36ed44a8aa634f859..4b58bab054b685c6ae8ff580f7cf862282e8f347 100644 --- a/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp +++ b/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp @@ -58,7 +58,9 @@ void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoPa argc = index; LOG_DEBUG("async callback, no promise"); } else { - LOG_DEBUG("no callback, async pormose"); + CHECK_ARGS_RETURN_VOID(this, type == napi_undefined, "arguments error!", + std::make_shared("callback", "function")); + LOG_DEBUG("no callback, async promise"); } } diff --git a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp index c32e52be96c288e21068b94ba21b599833e470e8..5b1d87241efec90d0edeeefae03367ea283eee26 100644 --- a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp +++ b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp @@ -159,7 +159,7 @@ napi_value NapiDataShareHelper::Napi_CreateDataShareHelper(napi_env env, napi_ca }; auto exec = [ctxInfo](AsyncCall::Context *ctx) { if (ctxInfo->isStageMode && ctxInfo->contextS != nullptr) { - ctxInfo->dataShareHelper = DataShareHelper::Creator(ctxInfo->contextS, ctxInfo->strUri); + ctxInfo->dataShareHelper = DataShareHelper::Creator(ctxInfo->contextS->GetToken(), ctxInfo->strUri); } else if (!ctxInfo->isStageMode && ctxInfo->contextF != nullptr) { ctxInfo->dataShareHelper = DataShareHelper::Creator(ctxInfo->contextF, ctxInfo->strUri); } diff --git a/data_share/frameworks/native/common/include/adaptor.h b/data_share/frameworks/native/common/include/adaptor.h new file mode 100644 index 0000000000000000000000000000000000000000..074ac634a8f71507e29c9680c58c6be69e1206ab --- /dev/null +++ b/data_share/frameworks/native/common/include/adaptor.h @@ -0,0 +1,32 @@ +/* + * 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 DISTRIBUTEDDATAMGR_DATA_SHARE__ADAPTOR_H +#define DISTRIBUTEDDATAMGR_DATA_SHARE__ADAPTOR_H + +#define DO_NOTHING + +#ifdef WINDOWS_PLATFORM +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING + +#elif MAC_PLATFORM +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING + +#else +#include "hitrace.h" +#define DISTRIBUTED_DATA_HITRACE(trace) HiTrace hitrace(trace) + +#endif + +#endif // DISTRIBUTEDDATAMGR_DATA_SHARE__ADAPTOR_H \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/hitrace.h b/data_share/frameworks/native/common/include/hitrace.h new file mode 100644 index 0000000000000000000000000000000000000000..11a09b7f8cee9f7266251712a351717b907e2437 --- /dev/null +++ b/data_share/frameworks/native/common/include/hitrace.h @@ -0,0 +1,40 @@ +/* + * 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 DISTRIBUTEDDATAMGR_DATA_SHARE_HITRACE_H +#define DISTRIBUTEDDATAMGR_DATA_SHARE_HITRACE_H + +#include + +#include "hitrace_meter.h" + +namespace OHOS { +namespace DataShare { +class HiTrace final { +public: + inline HiTrace(const std::string &value) + { + StartTrace(HITRACE_TAG_DISTRIBUTEDDATA, value); + } + + inline ~HiTrace() + { + FinishTrace(HITRACE_TAG_DISTRIBUTEDDATA); + } +}; +} // namespace DataShare +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/itypes_utils.h b/data_share/frameworks/native/common/include/itypes_utils.h index 5f3c6f4c60f57320be4ea78d2bf0f71eab0226d3..8cf696a6c4effabab1626ed37b93a5c9b9215b72 100644 --- a/data_share/frameworks/native/common/include/itypes_utils.h +++ b/data_share/frameworks/native/common/include/itypes_utils.h @@ -157,7 +157,7 @@ bool ITypesUtils::Marshalling(const std::vector ¶ms, Parcel &parcel) if (!parcel.WriteInt32(params.size())) { return false; } - for (auto i = 0; i < params.size(); i++) { + for (unsigned long i = 0; i < params.size(); i++) { if (!Marshalling(params[i], parcel)) { return false; } @@ -176,7 +176,7 @@ bool ITypesUtils::Unmarshalling(Parcel &parcel, std::vector ¶ms) return false; } params.resize(static_cast(size)); - for (auto i = 0; i < size; i++) { + for (size_t i = 0; i < size; i++) { T param; if (!Unmarshalling(parcel, param)) { return false; diff --git a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp b/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp index b7ffc5623b1eb0a4eeabbcd7e88f54ef5672ee25..291e0365f2835367fffa05ab37425bfecdb889fa 100644 --- a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp +++ b/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp @@ -14,11 +14,13 @@ */ #define LOG_TAG "DataShareAbsResultSet" #include "datashare_abs_result_set.h" -#include + #include +#include + +#include "adaptor.h" #include "datashare_errno.h" #include "datashare_log.h" -#include "dds_trace.h" namespace OHOS { namespace DataShare { @@ -94,7 +96,7 @@ int DataShareAbsResultSet::GoTo(int offset) int DataShareAbsResultSet::GoToFirstRow() { - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG"::") + std::string(__FUNCTION__)); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); int ret = GoToRow(0); if (ret != E_OK) { LOG_ERROR("return ret is wrong!"); diff --git a/data_share/frameworks/native/common/src/datashare_result_set.cpp b/data_share/frameworks/native/common/src/datashare_result_set.cpp index ec46da6b8695840ddecd9ae9790ff87c5a1dd557..3e8528ece1b4a0f75f2af374f09a19f30b10e9a7 100644 --- a/data_share/frameworks/native/common/src/datashare_result_set.cpp +++ b/data_share/frameworks/native/common/src/datashare_result_set.cpp @@ -15,13 +15,15 @@ #include "datashare_result_set.h" #include + #include + +#include "adaptor.h" +#include "datashare_errno.h" #include "datashare_log.h" #include "parcel.h" -#include "datashare_errno.h" #include "shared_block.h" #include "string_ex.h" -#include "dds_trace.h" namespace OHOS { namespace DataShare { @@ -155,7 +157,7 @@ int DataShareResultSet::GoToRow(int position) int DataShareResultSet::GetBlob(int columnIndex, std::vector &value) { - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG"::") + std::string(__FUNCTION__)); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); int errorCode = CheckState(columnIndex); if (errorCode != E_OK) { return errorCode; @@ -348,7 +350,7 @@ int DataShareResultSet::IsColumnNull(int columnIndex, bool &isNull) int DataShareResultSet::Close() { - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG"::") + std::string(__FUNCTION__)); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); DataShareAbsResultSet::Close(); ClosedBlock(); return E_OK; 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 index 3689f470a73662c0e43e678878d6e975594b3ef4..aba96cc15de1c6c8aa88717ed4e066b31c21f4d1 100644 --- a/data_share/frameworks/native/common/src/ishared_result_set_proxy.cpp +++ b/data_share/frameworks/native/common/src/ishared_result_set_proxy.cpp @@ -14,10 +14,12 @@ */ #include "ishared_result_set_proxy.h" + +#include "adaptor.h" #include "datashare_errno.h" -#include "iremote_proxy.h" #include "datashare_log.h" -#include "dds_trace.h" +#include "iremote_proxy.h" + namespace OHOS::DataShare { std::function( MessageParcel &parcel)> ISharedResultSet::consumerCreator_ = ISharedResultSetProxy::CreateProxy; @@ -70,7 +72,7 @@ int ISharedResultSetProxy::GetAllColumnNames(std::vector &columnNam int ISharedResultSetProxy::GetRowCount(int &count) { LOG_DEBUG("Start"); - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG"::") + std::string(__FUNCTION__)); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); if (rowCount_ >= 0) { count = rowCount_; return E_OK; diff --git a/data_share/frameworks/native/consumer/include/datashare_connection.h b/data_share/frameworks/native/consumer/include/datashare_connection.h index c88ed60c896d9c62f5be009e0ec14346e9021a26..04eda043113456a6714c9c2a9496867d0558d58a 100644 --- a/data_share/frameworks/native/consumer/include/datashare_connection.h +++ b/data_share/frameworks/native/consumer/include/datashare_connection.h @@ -30,7 +30,7 @@ using namespace AppExecFwk; class DataShareConnection : public AAFwk::AbilityConnectionStub { public: DataShareConnection(const Uri &uri) : uri_(uri) {} - virtual ~DataShareConnection() = default; + virtual ~DataShareConnection(); /** * @brief This method is called back to receive the connection result after an ability calls the @@ -58,26 +58,7 @@ public: /** * @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 try to reconnect remote extension ability. - * - * @return bool true if connected, otherwise false. - */ - bool TryReconnect(const Uri &uri, const sptr &token); + bool ConnectDataShareExtAbility(const Uri &uri, const sptr &token); /** * @brief get the proxy of datashare extension ability. @@ -91,9 +72,12 @@ public: std::mutex mutex; }; private: + void DisconnectDataShareExtAbility(); + void SetDataShareProxy(sptr proxy); + bool IsExtAbilityConnected(); + static sptr instance_; std::mutex mutex_; - std::atomic isConnected_ = {false}; sptr dataShareProxy_; ConnectCondition condition_; Uri uri_; diff --git a/data_share/frameworks/native/consumer/src/datashare_connection.cpp b/data_share/frameworks/native/consumer/src/datashare_connection.cpp index 93f0c5647f32ce8b9491adf3f397f0423ecf7122..3139eb1f9c06366d64ee140413851c364de8d372 100644 --- a/data_share/frameworks/native/consumer/src/datashare_connection.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_connection.cpp @@ -23,7 +23,7 @@ namespace OHOS { namespace DataShare { using namespace AppExecFwk; sptr DataShareConnection::instance_ = nullptr; -constexpr int WAIT_TIME = 1; +constexpr int WAIT_TIME = 3; /** * @brief This method is called back to receive the connection result after an ability calls the @@ -43,8 +43,7 @@ void DataShareConnection::OnAbilityConnectDone( return; } std::unique_lock lock(condition_.mutex); - dataShareProxy_ = iface_cast(remoteObject); - isConnected_.store(true); + SetDataShareProxy(iface_cast(remoteObject)); condition_.condition.notify_all(); LOG_DEBUG("End"); } @@ -60,33 +59,45 @@ void DataShareConnection::OnAbilityConnectDone( */ void DataShareConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) { - LOG_DEBUG("Start"); - std::unique_lock lock(condition_.mutex); - dataShareProxy_ = nullptr; - isConnected_.store(false); - condition_.condition.notify_all(); - LOG_DEBUG("End"); + auto proxy = dataShareProxy_; + { + LOG_DEBUG("Start"); + std::unique_lock lock(condition_.mutex); + SetDataShareProxy(nullptr); + condition_.condition.notify_all(); + LOG_DEBUG("End"); + } + if (proxy != nullptr && !uri_.ToString().empty()) { + LOG_INFO("uri : %{public}s disconnect,start reconnect", uri_.ToString().c_str()); + ConnectDataShareExtAbility(uri_, proxy->AsObject()); + } } /** * @brief connect remote ability of DataShareExtAbility. */ -void DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr &token) +bool DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr &token) { + if (dataShareProxy_ != nullptr) { + LOG_DEBUG("dataShareProxy has connected"); + return true; + } + LOG_DEBUG("Start"); - std::unique_lock lock(condition_.mutex); AAFwk::Want want; if (uri_.ToString().empty()) { want.SetUri(uri); } else { want.SetUri(uri_); } + std::unique_lock lock(condition_.mutex); 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("connect ability ended successfully"); } LOG_INFO("called end, ret=%{public}d", ret); + return dataShareProxy_ != nullptr; } /** @@ -94,9 +105,12 @@ void DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr< */ void DataShareConnection::DisconnectDataShareExtAbility() { + if (dataShareProxy_ == nullptr) { + LOG_DEBUG("dataShareProxy has disConnected"); + return; + } LOG_DEBUG("Start"); std::unique_lock lock(condition_.mutex); - isConnected_.store(false); ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(this); if (condition_.condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [this] { return dataShareProxy_ == nullptr; })) { @@ -112,22 +126,6 @@ void DataShareConnection::DisconnectDataShareExtAbility() */ bool DataShareConnection::IsExtAbilityConnected() { - return isConnected_.load(); -} - -/** - * @brief check whether connected to remote extension ability. - * - * @return bool true if connected, otherwise false. - */ -bool DataShareConnection::TryReconnect(const Uri &uri, const sptr &token) -{ - LOG_INFO("Reconnect begin"); - ConnectDataShareExtAbility(uri, token); - if (dataShareProxy_ == nullptr) { - LOG_ERROR("Reconnect failed"); - DisconnectDataShareExtAbility(); - } return dataShareProxy_ != nullptr; } @@ -135,5 +133,16 @@ sptr DataShareConnection::GetDataShareProxy() { return dataShareProxy_; } + +void DataShareConnection::SetDataShareProxy(sptr proxy) +{ + dataShareProxy_ = proxy; +} + +DataShareConnection::~DataShareConnection() +{ + uri_ = Uri(""); + DisconnectDataShareExtAbility(); +} } // 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 index 17b8803546fff5e298162eb5a8a3396418f92e2e..b0f483af0e31aa59baede3032021f7830580b476 100644 --- a/data_share/frameworks/native/consumer/src/datashare_helper.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_helper.cpp @@ -30,16 +30,12 @@ const std::string SCHEME_DATASHARE = "datashare"; constexpr int INVALID_VALUE = -1; } // namespace -std::mutex DataShareHelper::oplock_; -std::mutex DataShareHelper::deathlock_; - -DataShareHelper::DataShareHelper(const sptr &token, - const Uri &uri, const sptr &dataShareProxy, sptr dataShareConnection) +DataShareHelper::DataShareHelper(const sptr &token, const Uri &uri, + sptr dataShareConnection) { - LOG_DEBUG("Start"); + LOG_INFO("DataShareHelper::DataShareHelper start"); token_ = token; uri_ = uri; - dataShareProxy_ = dataShareProxy; dataShareConnection_ = dataShareConnection; } @@ -54,42 +50,6 @@ DataShareHelper::DataShareHelper(const sptr &token, const Uri &ur DataShareHelper::~DataShareHelper() { - if (callerDeathRecipient_ != nullptr) { - dataShareProxy_->AsObject()->RemoveDeathRecipient(callerDeathRecipient_); - callerDeathRecipient_ = nullptr; - } -} - -void DataShareHelper::AddDataShareDeathRecipient(const sptr &token) -{ - LOG_DEBUG("Start"); - if (token == nullptr) { - LOG_INFO("token is nullptr"); - return; - } - std::lock_guard lock_l(deathlock_); - if (callerDeathRecipient_ != nullptr) { - LOG_INFO("exist callerDeathRecipient_."); - return; - } - - callerDeathRecipient_ = - new DataShareDeathRecipient(std::bind(&DataShareHelper::OnSchedulerDied, this, std::placeholders::_1)); - token->AddDeathRecipient(callerDeathRecipient_); -} - -void DataShareHelper::OnSchedulerDied(const wptr &remote) -{ - LOG_DEBUG("Start"); - std::lock_guard lock_l(deathlock_); - if (callerDeathRecipient_ != nullptr) { - if (dataShareProxy_ != nullptr) { - dataShareProxy_->AsObject()->RemoveDeathRecipient(callerDeathRecipient_); - } - callerDeathRecipient_ = nullptr; - } - dataShareProxy_ = nullptr; - dataShareConnection_->ConnectDataShareExtAbility(uri_, token_); } /** @@ -114,28 +74,6 @@ std::shared_ptr DataShareHelper::Creator( 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_DEBUG("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 @@ -169,25 +107,20 @@ std::shared_ptr DataShareHelper::Creator(const sptr dataShareConnection = new (std::nothrow) DataShareConnection(uri); - if (!dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->ConnectDataShareExtAbility(uri, token); - } - sptr dataShareProxy = dataShareConnection->GetDataShareProxy(); - if (dataShareProxy == nullptr) { - LOG_ERROR("Invalid dataShareProxy"); - if (dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->DisconnectDataShareExtAbility(); - } + if (dataShareConnection == nullptr) { + LOG_ERROR("create dataShareConnection failed"); + return nullptr; + } + if (!dataShareConnection->ConnectDataShareExtAbility(uri, token)) { + LOG_ERROR("connect failed"); return nullptr; } DataShareHelper *ptrDataShareHelper = - new (std::nothrow) DataShareHelper(token, uri, dataShareProxy, dataShareConnection); + new (std::nothrow) DataShareHelper(token, uri, dataShareConnection); if (ptrDataShareHelper == nullptr) { LOG_ERROR("create DataShareHelper failed"); - if (dataShareConnection->IsExtAbilityConnected()) { - dataShareConnection->DisconnectDataShareExtAbility(); - } + dataShareConnection = nullptr; return nullptr; } @@ -202,11 +135,7 @@ std::shared_ptr DataShareHelper::Creator(const sptrIsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - dataShareProxy_ = nullptr; + LOG_INFO("Release Start"); dataShareConnection_ = nullptr; uri_ = Uri(""); return true; @@ -224,15 +153,21 @@ std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::stri { LOG_DEBUG("Start"); std::vector matchedMIMEs; - if (!CheckUriParam(uri)) { + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return matchedMIMEs; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return matchedMIMEs; } - matchedMIMEs = dataShareProxy_->GetFileTypes(uri, mimeTypeFilter); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + matchedMIMEs = proxy->GetFileTypes(uri, mimeTypeFilter); + } return matchedMIMEs; } @@ -251,15 +186,21 @@ int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) { LOG_DEBUG("Start"); int fd = INVALID_VALUE; - if (!CheckUriParam(uri)) { + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return fd; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return fd; } - fd = dataShareProxy_->OpenFile(uri, mode); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + fd = proxy->OpenFile(uri, mode); + } return fd; } @@ -279,15 +220,21 @@ int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) { LOG_DEBUG("Start"); int fd = INVALID_VALUE; - if (!CheckUriParam(uri)) { + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return fd; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return fd; } - fd = dataShareProxy_->OpenRawFile(uri, mode); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + fd = proxy->OpenRawFile(uri, mode); + } return fd; } @@ -312,15 +259,21 @@ int DataShareHelper::Insert(Uri &uri, const DataShareValuesBucket &value) } return service->Insert(uri.ToString(), value); } - if (!CheckUriParam(uri)) { + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return index; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return index; } - index = dataShareProxy_->Insert(uri, value); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + index = proxy->Insert(uri, value); + } return index; } @@ -333,8 +286,7 @@ int DataShareHelper::Insert(Uri &uri, const DataShareValuesBucket &value) * * @return Returns the number of data records updated. */ -int DataShareHelper::Update( - Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) +int DataShareHelper::Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) { LOG_DEBUG("Start"); int index = INVALID_VALUE; @@ -347,15 +299,22 @@ int DataShareHelper::Update( } return service->Update(uri.ToString(), predicates, value); } - if (!CheckUriParam(uri)) { + + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return index; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return index; } - index = dataShareProxy_->Update(uri, predicates, value); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + index = proxy->Update(uri, predicates, value); + } return index; } @@ -380,15 +339,22 @@ int DataShareHelper::Delete(Uri &uri, const DataSharePredicates &predicates) } return service->Delete(uri.ToString(), predicates); } - if (!CheckUriParam(uri)) { + + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return index; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return index; } - index = dataShareProxy_->Delete(uri, predicates); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + index = proxy->Delete(uri, predicates); + } return index; } @@ -415,15 +381,22 @@ std::shared_ptr DataShareHelper::Query( } return service->Query(uri.ToString(), predicates, columns); } - if (!CheckUriParam(uri)) { + + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return resultset; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return resultset; } - resultset = dataShareProxy_->Query(uri, predicates, columns); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + resultset = proxy->Query(uri, predicates, columns); + } return resultset; } @@ -439,15 +412,22 @@ std::string DataShareHelper::GetType(Uri &uri) { LOG_DEBUG("Start"); std::string type; - if (!CheckUriParam(uri)) { + + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return type; } - if (!TryReconnect(uri_, token_)) { + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return type; } - type = dataShareProxy_->GetType(uri); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + type = proxy->GetType(uri); + } return type; } @@ -463,68 +443,22 @@ int DataShareHelper::BatchInsert(Uri &uri, const std::vectorConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return ret; } - ret = dataShareProxy_->BatchInsert(uri, values); - return ret; -} - -bool DataShareHelper::CheckUriParam(const Uri &uri) -{ - LOG_DEBUG("Start"); - Uri checkUri(uri.ToString()); - if (!CheckOhosUri(checkUri)) { - LOG_ERROR("CheckOhosUri uri failed"); - return false; - } - - if (uri_.ToString().empty()) { - if (!CheckOhosUri(uri_)) { - LOG_ERROR("CheckOhosUri uri_ failed"); - return false; - } - - std::vector checkSegments; - checkUri.GetPathSegments(checkSegments); - - std::vector segments; - uri_.GetPathSegments(segments); - - if (checkSegments[0] != segments[0]) { - LOG_ERROR("The datashare in uri doesn't equal the one in uri_."); - return false; - } + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + ret = proxy->BatchInsert(uri, values); } - return true; -} - -bool DataShareHelper::CheckOhosUri(const Uri &uri) -{ - LOG_DEBUG("Start"); - Uri checkUri(uri.ToString()); - if (checkUri.GetScheme() != SCHEME_DATASHARE) { - LOG_ERROR("uri is not a datashare one."); - return false; - } - - std::vector segments; - checkUri.GetPathSegments(segments); - if (segments.empty()) { - LOG_ERROR("There is no segments in the uri."); - return false; - } - - if (checkUri.GetPath() == "") { - LOG_ERROR("The path in the uri is empty."); - return false; - } - return true; + return ret; } /** @@ -535,10 +469,7 @@ bool DataShareHelper::CheckOhosUri(const Uri &uri) */ void DataShareHelper::RegisterObserver(const Uri &uri, const sptr &dataObserver) { - LOG_DEBUG("Start"); - if (!CheckUriParam(uri)) { - return; - } + LOG_INFO("Start"); if (dataObserver == nullptr) { LOG_ERROR("dataObserver is nullptr"); return; @@ -551,36 +482,23 @@ void DataShareHelper::RegisterObserver(const Uri &uri, const sptr 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("input uri's path is not equal the one the observer used"); - return; - } - dataShareProxy_ = datashare->second; - } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return; + } + + if (!connection->ConnectDataShareExtAbility(uri, token_)) { + LOG_ERROR("connect failed"); + return; } - if (dataShareProxy_ == nullptr) { - LOG_ERROR("dataShareProxy_ is nullptr"); - registerMap_.erase(dataObserver); - uriMap_.erase(dataObserver); + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy has disconnected"); return; } - dataShareProxy_->RegisterObserver(uri, dataObserver); + proxy->RegisterObserver(uri, dataObserver); } /** @@ -591,14 +509,12 @@ void DataShareHelper::RegisterObserver(const Uri &uri, const sptr &dataObserver) { - LOG_DEBUG("Start"); - if (!CheckUriParam(uri)) { - return; - } + LOG_INFO("Start"); if (dataObserver == nullptr) { LOG_ERROR("dataObserver is nullptr"); return; } + if (isDataShareService_) { LOG_DEBUG("DataShareService mode."); if (!UnregObserver(uri, dataObserver)) { @@ -607,37 +523,17 @@ void DataShareHelper::UnregisterObserver(const Uri &uri, const sptr 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("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("dataShareProxy_ is nullptr"); + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); return; } - - dataShareProxy_->UnregisterObserver(uri, dataObserver); - if (uri_.ToString().empty()) { - if (dataShareConnection_->IsExtAbilityConnected()) { - dataShareConnection_->DisconnectDataShareExtAbility(); - } - dataShareProxy_ = nullptr; + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareConnection_->GetDataShareProxy() is nullptr"); + return; } - registerMap_.erase(dataObserver); - uriMap_.erase(dataObserver); + proxy->UnregisterObserver(uri, dataObserver); } /** @@ -648,15 +544,21 @@ void DataShareHelper::UnregisterObserver(const Uri &uri, const sptrConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); return; } - dataShareProxy_->NotifyChange(uri); + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + proxy->NotifyChange(uri); + } } /** @@ -674,17 +576,23 @@ void DataShareHelper::NotifyChange(const Uri &uri) Uri DataShareHelper::NormalizeUri(Uri &uri) { LOG_DEBUG("Start"); - Uri urivalue(""); - if (!CheckUriParam(uri)) { - return urivalue; + Uri uriValue(""); + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return uriValue; } - if (!TryReconnect(uri_, token_)) { - return urivalue; + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return uriValue; } - urivalue = dataShareProxy_->NormalizeUri(uri); - return urivalue; + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + uriValue = proxy->NormalizeUri(uri); + } + return uriValue; } /** @@ -700,37 +608,23 @@ Uri DataShareHelper::NormalizeUri(Uri &uri) Uri DataShareHelper::DenormalizeUri(Uri &uri) { LOG_DEBUG("Start"); - Uri urivalue(""); - if (!CheckUriParam(uri)) { - return urivalue; + Uri uriValue(""); + auto connection = dataShareConnection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return uriValue; } - if (!TryReconnect(uri_, token_)) { - return urivalue; + if (!connection->ConnectDataShareExtAbility(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return uriValue; } - urivalue = dataShareProxy_->DenormalizeUri(uri); - return urivalue; -} - -bool DataShareHelper::TryReconnect(const Uri &uri, const sptr &token) -{ - if (dataShareConnection_->IsExtAbilityConnected()) { - return true; + auto proxy = connection->GetDataShareProxy(); + if (proxy != nullptr) { + uriValue = proxy->DenormalizeUri(uri); } - - if (!dataShareConnection_->TryReconnect(uri, token)) { - return false; - } - - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - if (dataShareProxy_ == nullptr) { - LOG_ERROR("Invalid dataShareProxy"); - return false; - } - - AddDataShareDeathRecipient(dataShareProxy_->AsObject()); - return true; + return uriValue; } bool DataShareHelper::RegObserver (const Uri &uri, const sptr &dataObserver) @@ -760,19 +654,5 @@ bool DataShareHelper::UnregObserver (const Uri &uri, const sptr &remote) -{ - LOG_DEBUG("Start"); - if (handler_) { - handler_(remote); - } -} - -DataShareDeathRecipient::DataShareDeathRecipient(RemoteDiedHandler handler) : handler_(handler) -{} - -DataShareDeathRecipient::~DataShareDeathRecipient() -{} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/interfaces/inner_api/common/BUILD.gn b/data_share/interfaces/inner_api/common/BUILD.gn index faa6ef0645354f1bffff87b5160a6f29718ab6fe..2c5e5c6d739552ccb9b263e12a028bd647022138 100644 --- a/data_share/interfaces/inner_api/common/BUILD.gn +++ b/data_share/interfaces/inner_api/common/BUILD.gn @@ -30,7 +30,6 @@ ohos_shared_library("datashare_common") { "${datashare_base_path}/interfaces/inner_api/common/include", "${datashare_base_path}/interfaces/inner_api/consumer/include", "${datashare_base_path}/interfaces/inner_api/provider/include", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter/include/dfx", ] sources = [ diff --git a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h index a75a09b784f5b5c1fc8c3c4a11d2df7743c55542..0106451b57369e068cc44b1dc64812fd30302231 100644 --- a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h +++ b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h @@ -23,7 +23,6 @@ #include "context.h" #include "datashare_connection.h" -#include "appkit/ability_runtime/context/context.h" #include "idatashare.h" #include "uri.h" #include "datashare_operation.h" @@ -52,18 +51,6 @@ public: */ 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 @@ -235,41 +222,16 @@ public: Uri DenormalizeUri(Uri &uri); private: - DataShareHelper(const sptr &token, const Uri &uri, const sptr &dataShareProxy, + DataShareHelper(const sptr &token, const Uri &uri, const sptr dataShareConnection); DataShareHelper(const sptr &token, const Uri &uri); - void AddDataShareDeathRecipient(const sptr &token); - void OnSchedulerDied(const wptr &remote); - bool CheckUriParam(const Uri &uri); - bool CheckOhosUri(const Uri &uri); - bool TryReconnect(const Uri &uri, const sptr &token); bool isDataShareService_ = false; sptr token_ = {}; Uri uri_ = Uri(""); - sptr dataShareProxy_ = nullptr; - static std::mutex oplock_; - static std::mutex deathlock_; - sptr callerDeathRecipient_ = nullptr; - std::map, sptr> registerMap_; - std::map, std::string> uriMap_; sptr dataShareConnection_ = nullptr; static bool RegObserver (const Uri &uri, const sptr &dataObserver); static bool UnregObserver (const Uri &uri, const sptr &dataObserver); }; - -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/datamgr_service/services/distributeddataservice/service/test/crypto_manager_test.cpp b/datamgr_service/services/distributeddataservice/service/test/crypto_manager_test.cpp index a78020761ca1deef628312729da7642591afd3ca..c2c40ce4f6ead77b5b541c3cd80310298fe4aef3 100644 --- a/datamgr_service/services/distributeddataservice/service/test/crypto_manager_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/crypto_manager_test.cpp @@ -82,19 +82,6 @@ HWTEST_F(CryptoManagerTest, CheckRootKey, TestSize.Level0) EXPECT_EQ(errCode, CryptoManager::ErrCode::SUCCESS); } -/** -* @tc.name: Encrypt001 -* @tc.desc: encrypt random key; -* @tc.type: FUNC -* @tc.require: -* @tc.author: zuojiangjiang -*/ -HWTEST_F(CryptoManagerTest, Encrypt001, TestSize.Level0) -{ - auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey); - EXPECT_EQ(encryptKey.size(), ENCRYPT_KEY_LENGTH); - encryptKey.assign(encryptKey.size(), 0); -} /** * @tc.name: Encrypt002 @@ -126,33 +113,3 @@ HWTEST_F(CryptoManagerTest, DecryptKey001, TestSize.Level0) encryptKey.assign(encryptKey.size(), 0); } -/** -* @tc.name: DecryptKey002 -* @tc.desc: decrypt the key, the source key is not encrypt; -* @tc.type: FUNC -* @tc.require: -* @tc.author: zuojiangjiang -*/ -HWTEST_F(CryptoManagerTest, DecryptKey002, TestSize.Level0) -{ - std::vector key; - auto result = CryptoManager::GetInstance().Decrypt(randomKey, key); - EXPECT_FALSE(result); - EXPECT_TRUE(key.empty()); -} - -/** -* @tc.name: DecryptKey003 -* @tc.desc: decrypt the key, the source key is empty; -* @tc.type: FUNC -* @tc.require: -* @tc.author: zuojiangjiang -*/ -HWTEST_F(CryptoManagerTest, DecryptKey003, TestSize.Level0) -{ - std::vector srcKey {}; - std::vector key; - auto result = CryptoManager::GetInstance().Decrypt(srcKey, key); - EXPECT_FALSE(result); - EXPECT_TRUE(key.empty()); -} \ No newline at end of file diff --git a/kv_store/frameworks/CMakeLists.txt b/kv_store/frameworks/CMakeLists.txt index c23f773b6e95b16fa3ba445d419a6897efe706bc..004e2d70d2348a67e7531405a31e9b419bab2687 100644 --- a/kv_store/frameworks/CMakeLists.txt +++ b/kv_store/frameworks/CMakeLists.txt @@ -35,6 +35,7 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../datamgr_service/services/d include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../datamgr_service/services/distributeddataservice/adapter/include/permission) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../datamgr_service/services/distributeddataservice/adapter/include/security) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../datamgr_service/services/distributeddataservice/adapter/include/utils) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../datamgr_service/services/distributeddataservice/service/crypto/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../frameworks/libs/distributeddb/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../frameworks/libs/distributeddb/interfaces/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../frameworks/libs/distributeddb/interfaces/include/relational) diff --git a/preferences/CMakeLists.txt b/preferences/CMakeLists.txt index dd571584fc0efc86294a7beab8c8e1e4e70bed4f..e94d81513cde74d07a384c382527d18417e4c93b 100644 --- a/preferences/CMakeLists.txt +++ b/preferences/CMakeLists.txt @@ -11,9 +11,9 @@ set(MOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../mock) add_definitions(-DNAPI_EXPERIMENTAL) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/src preferences_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/src preferences_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/src preferences_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/common/src preferences_src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) diff --git a/preferences/bundle.json b/preferences/bundle.json index 374ff05ca1e2805c11a98e94ff265b51869cd698..97399b304157895a038a4925165dd228a391c541 100644 --- a/preferences/bundle.json +++ b/preferences/bundle.json @@ -76,7 +76,6 @@ "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" @@ -85,7 +84,8 @@ ], "test": [ "//foundation/distributeddatamgr/preferences/test/native:unittest", - "//foundation/distributeddatamgr/preferences/test/js:unittest" + "//foundation/distributeddatamgr/preferences/test/js:unittest", + "//foundation/distributeddatamgr/preferences/test/native/fuzztest/preferences_fuzzer:PreferencesFuzzTest" ] } } diff --git a/preferences/frameworks/js/napi/common/include/async_call.h b/preferences/frameworks/js/common/include/async_call.h similarity index 90% rename from preferences/frameworks/js/napi/common/include/async_call.h rename to preferences/frameworks/js/common/include/async_call.h index 75c4123784a513ae4e1f1536fa9165127dbfbf13..423981623c00836b60d8a4c149a5871c06312b2b 100644 --- a/preferences/frameworks/js/napi/common/include/async_call.h +++ b/preferences/frameworks/js/common/include/async_call.h @@ -1,121 +1,123 @@ -/* - * 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 PRE_JS_NAPI_ASYNC_CALL_H -#define PRE_JS_NAPI_ASYNC_CALL_H - -#include -#include - -#include "js_logger.h" -#include "js_utils.h" -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "napi_preferences_error.h" - -namespace OHOS { -namespace AppDataMgrJsKit { - -class AsyncCall final { -public: - class Context { - public: - int apiversion; - std::shared_ptr error; - napi_env _env = nullptr; - void *boundObj = nullptr; - 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)); - } - - void SetError(std::shared_ptr err) - { - error = err; - } - - // input function - virtual int operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) - { - if (input_ == nullptr) { - return OK; - } - return input_(env, argc, argv, self); - } - - // output function - virtual int operator()(napi_env env, napi_value &result) - { - if (output_ == nullptr) { - result = nullptr; - return OK; - } - return output_(env, result); - } - - //execute function - virtual void Exec() - { - if (exec_ == nullptr) { - return; - } - 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); - static void SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr error, int apiversion); - - AsyncContext *context_ = nullptr; - napi_env env_ = nullptr; -}; -} // namespace AppDataMgrJsKit -} // namespace OHOS -#endif +/* + * 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 PRE_JS_NAPI_ASYNC_CALL_H +#define PRE_JS_NAPI_ASYNC_CALL_H + +#include +#include + +#include "js_logger.h" +#include "js_utils.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "napi_preferences_error.h" + +namespace OHOS { +namespace PreferencesJsKit { + +class AsyncCall final { +public: + class Context { + public: + int apiversion; + std::shared_ptr error; + napi_env _env = nullptr; + void *boundObj = nullptr; + using InputAction = std::function; + using OutputAction = std::function; + using ExecAction = std::function; + Context(InputAction input, OutputAction output) + : apiversion(0), 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)); + } + + void SetError(std::shared_ptr err) + { + error = err; + } + + // input function + virtual int operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) + { + if (input_ == nullptr) { + return OK; + } + return input_(env, argc, argv, self); + } + + // output function + virtual int operator()(napi_env env, napi_value &result) + { + if (output_ == nullptr) { + result = nullptr; + return OK; + } + return output_(env, result); + } + + // execute function + virtual void Exec() + { + if (exec_ == nullptr) { + return; + } + 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); + static void SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr error, int apiversion); + + AsyncContext *context_ = nullptr; + napi_env env_ = nullptr; +}; +} // namespace PreferencesJsKit +} // namespace OHOS +#endif diff --git a/preferences/frameworks/js/napi/common/include/js_ability.h b/preferences/frameworks/js/common/include/js_ability.h similarity index 95% rename from preferences/frameworks/js/napi/common/include/js_ability.h rename to preferences/frameworks/js/common/include/js_ability.h index 3d4efae4241236fd83936d03c6cf2598717c982c..6cd73314f2858e5a7c23447f22b77577362ed6a9 100644 --- a/preferences/frameworks/js/napi/common/include/js_ability.h +++ b/preferences/frameworks/js/common/include/js_ability.h @@ -25,7 +25,7 @@ #include "napi_base_context.h" namespace OHOS { -namespace AppDataMgrJsKit { +namespace PreferencesJsKit { class Context { public: explicit Context(std::shared_ptr stageContext); @@ -42,7 +42,7 @@ public: static bool CheckContext(napi_env env, napi_callback_info info); static std::shared_ptr GetContext(napi_env env, napi_value object); }; -} // namespace AppDataMgrJsKit +} // namespace PreferencesJsKit } // namespace OHOS #endif // DISTRIBUTEDDATAMGR_APPDATAMGR_JSABILITY_H diff --git a/preferences/frameworks/js/napi/common/include/js_logger.h b/preferences/frameworks/js/common/include/js_logger.h similarity index 90% rename from preferences/frameworks/js/napi/common/include/js_logger.h rename to preferences/frameworks/js/common/include/js_logger.h index 3da9e39a93207a741f7c18de46c437399faf3f4b..73e75147060a6205a8bf80d937635b683f5ca7f7 100644 --- a/preferences/frameworks/js/napi/common/include/js_logger.h +++ b/preferences/frameworks/js/common/include/js_logger.h @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef PRE_JSKIT_LOGGER_H -#define PRE_JSKIT_LOGGER_H - -#include -#include - -#include "hilog/log.h" - -namespace OHOS { -namespace AppDataMgrJsKit { -static const OHOS::HiviewDFX::HiLogLabel PREFIX_LABEL = { LOG_CORE, 0xD001650, "AppDataMgrJsKit" }; -#define LOG_DEBUG(...) ((void)OHOS::HiviewDFX::HiLog::Debug(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_INFO(...) ((void)OHOS::HiviewDFX::HiLog::Info(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_WARN(...) ((void)OHOS::HiviewDFX::HiLog::Warn(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_ERROR(...) ((void)OHOS::HiviewDFX::HiLog::Error(PREFIX_LABEL, __VA_ARGS__)) -#define LOG_FATAL(...) ((void)OHOS::HiviewDFX::HiLog::Fatal(PREFIX_LABEL, __VA_ARGS__)) -} // namespace AppDataMgrJsKit -} // namespace OHOS - -#endif +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef PRE_JSKIT_LOGGER_H +#define PRE_JSKIT_LOGGER_H + +#include +#include + +#include "hilog/log.h" + +namespace OHOS { +namespace PreferencesJsKit { +static const OHOS::HiviewDFX::HiLogLabel PREFIX_LABEL = { LOG_CORE, 0xD001653, "PreferencesJsKit" }; +#define LOG_DEBUG(...) ((void)OHOS::HiviewDFX::HiLog::Debug(PREFIX_LABEL, __VA_ARGS__)) +#define LOG_INFO(...) ((void)OHOS::HiviewDFX::HiLog::Info(PREFIX_LABEL, __VA_ARGS__)) +#define LOG_WARN(...) ((void)OHOS::HiviewDFX::HiLog::Warn(PREFIX_LABEL, __VA_ARGS__)) +#define LOG_ERROR(...) ((void)OHOS::HiviewDFX::HiLog::Error(PREFIX_LABEL, __VA_ARGS__)) +#define LOG_FATAL(...) ((void)OHOS::HiviewDFX::HiLog::Fatal(PREFIX_LABEL, __VA_ARGS__)) +} // namespace PreferencesJsKit +} // namespace OHOS + +#endif diff --git a/preferences/frameworks/js/common/include/js_observer.h b/preferences/frameworks/js/common/include/js_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..d9d3255d014300f79705d8c803ea3fe4e5f45189 --- /dev/null +++ b/preferences/frameworks/js/common/include/js_observer.h @@ -0,0 +1,37 @@ +/* + * 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 OHOS_JS_OBSERVER_H +#define OHOS_JS_OBSERVER_H + +#include +#include "uv_queue.h" + +namespace OHOS::PreferencesJsKit { +class JSObserver : public std::enable_shared_from_this { +public: + JSObserver(std::shared_ptr uvQueue, napi_value callback); + virtual ~JSObserver(); + napi_ref GetCallback(); + +protected: + void AsyncCall(UvQueue::NapiArgsGenerator genArgs = UvQueue::NapiArgsGenerator()); + +private: + std::shared_ptr uvQueue_; + napi_ref callback_; +}; +} // namespace OHOS::PreferencesJsKit +#endif // OHOS_JS_OBSERVER_H diff --git a/preferences/frameworks/js/napi/common/include/js_utils.h b/preferences/frameworks/js/common/include/js_utils.h similarity index 94% rename from preferences/frameworks/js/napi/common/include/js_utils.h rename to preferences/frameworks/js/common/include/js_utils.h index b39452d01050ea0a8e33e8bcac6e84ae72e23e41..49907b1b677f17868ccc12be100a41925133f6ee 100644 --- a/preferences/frameworks/js/napi/common/include/js_utils.h +++ b/preferences/frameworks/js/common/include/js_utils.h @@ -26,7 +26,7 @@ #include "napi/native_node_api.h" namespace OHOS { -namespace AppDataMgrJsKit { +namespace PreferencesJsKit { class JSUtils final { public: static constexpr int OK = 0; @@ -51,8 +51,10 @@ public: static int32_t Convert2JSStringArr(napi_env env, std::vector value, napi_value &output); static int32_t Convert2JSBoolArr(napi_env env, std::vector value, napi_value &output); static int32_t Convert2JSDoubleArr(napi_env env, std::vector value, napi_value &output); + + static bool Equals(napi_env env, napi_value value, napi_ref copy); }; -} // namespace AppDataMgrJsKit +} // namespace PreferencesJsKit } // namespace OHOS #endif // DISTRIBUTEDDATAMGR_APPDATAMGR_JSUTILS_H diff --git a/preferences/frameworks/js/napi/common/include/napi_async_proxy.h b/preferences/frameworks/js/common/include/napi_async_proxy.h similarity index 99% rename from preferences/frameworks/js/napi/common/include/napi_async_proxy.h rename to preferences/frameworks/js/common/include/napi_async_proxy.h index 71e6d5c4bb26687721e169d53c63ff106e7008aa..3c99ffd71bbe56e0259a061546e59821ccb257f5 100644 --- a/preferences/frameworks/js/napi/common/include/napi_async_proxy.h +++ b/preferences/frameworks/js/common/include/napi_async_proxy.h @@ -22,7 +22,7 @@ #include "securec.h" namespace OHOS { -namespace AppDataMgrJsKit { +namespace PreferencesJsKit { constexpr int MAX_INPUT_COUNT = 10; constexpr int OK = 0; constexpr int ERR = -1; @@ -162,6 +162,6 @@ public: private: T *asyncContext; }; -} // namespace AppDataMgrJsKit +} // namespace PreferencesJsKit } // namespace OHOS #endif diff --git a/preferences/frameworks/js/napi/common/include/napi_preferences_error.h b/preferences/frameworks/js/common/include/napi_preferences_error.h similarity index 86% rename from preferences/frameworks/js/napi/common/include/napi_preferences_error.h rename to preferences/frameworks/js/common/include/napi_preferences_error.h index 810f13400ebf8fab8ffb843c9a433ca5746962ab..ae0a5f7a6c2fdf4eb4cf16f3a010a14b23afd6c2 100644 --- a/preferences/frameworks/js/napi/common/include/napi_preferences_error.h +++ b/preferences/frameworks/js/common/include/napi_preferences_error.h @@ -1,126 +1,127 @@ -/* - * 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 PRE_JS_NAPI_ERROR_H -#define PRE_JS_NAPI_ERROR_H - -#include "js_logger.h" - -namespace OHOS { -namespace AppDataMgrJsKit { -constexpr int MAX_INPUT_COUNT = 10; -constexpr int OK = 0; -constexpr int ERR = -1; - -constexpr int E_PARAM_ERROR = 401; -constexpr int E_PREFERENCES_ERROR = 15500010; - -#define PRE_NAPI_ASSERT_BASE(env, assertion, error, retVal) \ - do { \ - if (!(assertion)) { \ - LOG_ERROR("throw error: code = %{public}d , message = %{public}s", error->GetCode(), \ - error->GetMessage().c_str()); \ - napi_throw_error((env), std::to_string(error->GetCode()).c_str(), error->GetMessage().c_str()); \ - return retVal; \ - } \ - } while (0) - -#define PRE_NAPI_ASSERT(env, assertion, error) PRE_NAPI_ASSERT_BASE(env, assertion, error, nullptr) - -#define PRE_NAPI_ASSERT_RETURN_VOID(env, assertion, error) \ - PRE_NAPI_ASSERT_BASE(env, assertion, error, NAPI_RETVAL_NOTHING) - -#define PRE_ASYNC_PARAM_CHECK_FUNCTION(theCall) \ - do { \ - int err = (theCall); \ - if (err != OK) { \ - return err; \ - } \ - } while (0) - -#define PRE_CHECK_RETURN_NULLPTR(assertion) \ - do { \ - if (!(assertion)) { \ - return nullptr; \ - } \ - } while (0) - -#define PRE_CHECK_RETURN_CALL_RESULT(assertion, theCall) \ - do { \ - if (!(assertion)) { \ - (theCall); \ - return ERR; \ - } \ - } while (0) - -class Error { -public: - virtual ~Error(){}; - virtual std::string GetMessage() = 0; - virtual int GetCode() = 0; -}; - -class ParamTypeError : public Error { -public: - ParamTypeError(const std::string &name, const std::string &wantType) : name(name), wantType(wantType){}; - std::string GetMessage() override - { - return "Parameter error. The type of '" + name + "' must be " + wantType; - }; - int GetCode() override - { - return E_PARAM_ERROR; - }; - -private: - std::string name; - std::string wantType; -}; - -class ParamNumError : public Error { -public: - ParamNumError(const std::string &wantNum) : wantNum(wantNum){}; - std::string GetMessage() override - { - return "Parameter error. Need " + wantNum + " parameters!"; - }; - int GetCode() override - { - return E_PARAM_ERROR; - }; - -private: - std::string apiname; - std::string wantNum; -}; - -class DeleteError : public Error { -public: - DeleteError() = default; - std::string GetMessage() override - { - return "Failed to delete preferences file."; - }; - int GetCode() override - { - return E_PREFERENCES_ERROR; - }; - -private: - std::string apiname; -}; -} // namespace AppDataMgrJsKit -} // namespace OHOS - -#endif // PRE_JS_NAPI_ERROR_H +/* + * 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 PRE_JS_NAPI_ERROR_H +#define PRE_JS_NAPI_ERROR_H + +#include "js_logger.h" + +namespace OHOS { +namespace PreferencesJsKit { +constexpr int MAX_INPUT_COUNT = 10; +constexpr int OK = 0; +constexpr int ERR = -1; + +constexpr int E_PARAM_ERROR = 401; +constexpr int E_PREFERENCES_ERROR = 15500010; + +#define PRE_NAPI_ASSERT_BASE(env, assertion, error, retVal) \ + do { \ + if (!(assertion)) { \ + LOG_ERROR("throw error: code = %{public}d , message = %{public}s", \ + (error)->GetCode(), (error)->GetMessage().c_str()); \ + napi_throw_error((env), std::to_string((error)->GetCode()).c_str(), \ + (error)->GetMessage().c_str()); \ + return retVal; \ + } \ + } while (0) + +#define PRE_NAPI_ASSERT(env, assertion, error) PRE_NAPI_ASSERT_BASE(env, assertion, error, nullptr) + +#define PRE_NAPI_ASSERT_RETURN_VOID(env, assertion, error) \ + PRE_NAPI_ASSERT_BASE(env, assertion, error, NAPI_RETVAL_NOTHING) + +#define PRE_ASYNC_PARAM_CHECK_FUNCTION(theCall) \ + do { \ + int err = (theCall); \ + if (err != OK) { \ + return err; \ + } \ + } while (0) + +#define PRE_CHECK_RETURN_NULLPTR(assertion) \ + do { \ + if (!(assertion)) { \ + return nullptr; \ + } \ + } while (0) + +#define PRE_CHECK_RETURN_CALL_RESULT(assertion, theCall) \ + do { \ + if (!(assertion)) { \ + (theCall); \ + return ERR; \ + } \ + } while (0) + +class Error { +public: + virtual ~Error(){}; + virtual std::string GetMessage() = 0; + virtual int GetCode() = 0; +}; + +class ParamTypeError : public Error { +public: + ParamTypeError(const std::string &name, const std::string &wantType) : name(name), wantType(wantType){}; + std::string GetMessage() override + { + return "Parameter error. The type of '" + name + "' must be " + wantType; + }; + int GetCode() override + { + return E_PARAM_ERROR; + }; + +private: + std::string name; + std::string wantType; +}; + +class ParamNumError : public Error { +public: + ParamNumError(const std::string &wantNum) : wantNum(wantNum){}; + std::string GetMessage() override + { + return "Parameter error. Need " + wantNum + " parameters!"; + }; + int GetCode() override + { + return E_PARAM_ERROR; + }; + +private: + std::string apiname; + std::string wantNum; +}; + +class DeleteError : public Error { +public: + DeleteError() = default; + std::string GetMessage() override + { + return "Failed to delete preferences file."; + }; + int GetCode() override + { + return E_PREFERENCES_ERROR; + }; + +private: + std::string apiname; +}; +} // namespace PreferencesJsKit +} // namespace OHOS + +#endif // PRE_JS_NAPI_ERROR_H diff --git a/preferences/frameworks/js/napi/common/include/napi_uv_queue.h b/preferences/frameworks/js/common/include/uv_queue.h similarity index 58% rename from preferences/frameworks/js/napi/common/include/napi_uv_queue.h rename to preferences/frameworks/js/common/include/uv_queue.h index b59c1cb28473b11368aec3d4bacee02b7c6c5634..14c7fbdf6d506fad74e57a9b63483ca5dc80b259 100644 --- a/preferences/frameworks/js/napi/common/include/napi_uv_queue.h +++ b/preferences/frameworks/js/common/include/uv_queue.h @@ -12,36 +12,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef NAPI_UV_QUEUE_H -#define NAPI_UV_QUEUE_H - +#ifndef OHOS_UV_QUEUE_H +#define OHOS_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::RdbJsKit { -class NapiUvQueue { - using NapiArgsGenerator = std::function; - +namespace OHOS::PreferencesJsKit { +class UvQueue final { public: - NapiUvQueue(napi_env env, napi_value callback); - - virtual ~NapiUvQueue(); - - bool operator==(napi_value value); - - void CallFunction(NapiArgsGenerator genArgs = NapiArgsGenerator()); + using NapiArgsGenerator = std::function; + using NapiCallbackGetter = std::function; + UvQueue(napi_env env); + ~UvQueue(); + napi_env GetEnv(); + void AsyncCall(NapiCallbackGetter getter, NapiArgsGenerator genArgs = NapiArgsGenerator()); private: + struct UvEntry { + napi_env env; + NapiCallbackGetter callback; + NapiArgsGenerator args; + }; napi_env env_ = nullptr; - napi_ref callback_ = nullptr; - NapiArgsGenerator args; - uv_loop_s *loop_ = nullptr; - - static constexpr int MAX_CALLBACK_ARG_NUM = 6; + uv_loop_s* loop_ = nullptr; }; -} // namespace OHOS::RdbJsKit -#endif \ No newline at end of file +} // namespace OHOS::PreferencesJsKit +#endif // OHOS_UV_QUEUE_H diff --git a/preferences/frameworks/js/napi/common/mock/include/js_ability.h b/preferences/frameworks/js/common/mock/include/js_ability.h similarity index 95% rename from preferences/frameworks/js/napi/common/mock/include/js_ability.h rename to preferences/frameworks/js/common/mock/include/js_ability.h index 6f6c324358b0542ff7dce72cf9e7b54bcddf37fe..faebbfe7350fb0e56363f708f67acfcdad748342 100644 --- a/preferences/frameworks/js/napi/common/mock/include/js_ability.h +++ b/preferences/frameworks/js/common/mock/include/js_ability.h @@ -23,7 +23,7 @@ #include "napi/native_node_api.h" namespace OHOS { -namespace AppDataMgrJsKit { +namespace PreferencesJsKit { class Context { public: explicit Context(); @@ -39,7 +39,7 @@ public: static bool CheckContext(napi_env env, napi_callback_info info); static std::shared_ptr GetContext(napi_env env, napi_value object); }; -} // namespace AppDataMgrJsKit +} // namespace PreferencesJsKit } // namespace OHOS #endif // DISTRIBUTEDDATAMGR_APPDATAMGR_JSABILITY_H diff --git a/preferences/frameworks/js/napi/common/mock/src/js_ability.cpp b/preferences/frameworks/js/common/mock/src/js_ability.cpp similarity index 95% rename from preferences/frameworks/js/napi/common/mock/src/js_ability.cpp rename to preferences/frameworks/js/common/mock/src/js_ability.cpp index 288d69467736c5d83d5aa46fcc9a0f6390117de9..6872a620834b52b1ba465de8ef38ebbc8c5722a7 100644 --- a/preferences/frameworks/js/napi/common/mock/src/js_ability.cpp +++ b/preferences/frameworks/js/common/mock/src/js_ability.cpp @@ -20,7 +20,7 @@ #include "js_logger.h" namespace OHOS { -namespace AppDataMgrJsKit { +namespace PreferencesJsKit { Context::Context() { std::string baseDir = ""; @@ -54,5 +54,5 @@ std::shared_ptr JSAbility::GetContext(napi_env env, napi_value value) { return std::make_shared(); } -} // namespace AppDataMgrJsKit +} // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/src/async_call.cpp b/preferences/frameworks/js/common/src/async_call.cpp similarity index 95% rename from preferences/frameworks/js/napi/common/src/async_call.cpp rename to preferences/frameworks/js/common/src/async_call.cpp index 9179a845144bc0b6861b029ecbf01e4432be85ac..f3534a4affd3d0c062e30595c1664ea29ee74041 100644 --- a/preferences/frameworks/js/napi/common/src/async_call.cpp +++ b/preferences/frameworks/js/common/src/async_call.cpp @@ -1,169 +1,169 @@ -/* - * 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 "js_logger.h" - -namespace OHOS { -namespace AppDataMgrJsKit { -AsyncCall::AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr context) : env_(env) -{ - context->_env = env; - size_t argc = MAX_INPUT_COUNT; - napi_value self = nullptr; - napi_value argv[MAX_INPUT_COUNT] = { nullptr }; - NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - - context_ = new AsyncContext(); - 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; - } - // int -->input_(env, argc, argv, self) - int status = (*context)(env, argc, argv, self); - // if input return is not ok, then napi_throw_error context error - PRE_NAPI_ASSERT_RETURN_VOID(env, status == OK, context->error); - 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::SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr error, int apiversion) -{ - napi_create_object(env, businessError); - //if error is not inner error, and api version greater 8 - if (error != nullptr || apiversion > 8) { - napi_value code = nullptr; - napi_value msg = nullptr; - napi_create_int32(env, error->GetCode(), &code); - napi_create_string_utf8(env, error->GetMessage().c_str(), NAPI_AUTO_LENGTH, &msg); - napi_set_named_property(env, *businessError, "code", code); - napi_set_named_property(env, *businessError, "message", msg); - } -} - -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; - int outStatus = ERR; - // if async execute status is not napi_ok then un-execute out function - if (status == napi_ok) { - outStatus = (*context->ctx)(env, output); - } - napi_value result[ARG_BUTT] = { 0 }; - // if out function status is ok then async renturn output data, else return error. - if (outStatus == 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 businessError = nullptr; - SetBusinessError(env, &businessError, context->ctx->error, context->ctx->apiversion); - result[ARG_ERROR] = businessError; - napi_get_undefined(env, &result[ARG_DATA]); - } - if (context->defer != nullptr) { - // promise - if (status == napi_ok && outStatus == 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; -} -} // namespace AppDataMgrJsKit +/* + * 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 "js_logger.h" + +namespace OHOS { +namespace PreferencesJsKit { +AsyncCall::AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr context) : env_(env) +{ + context->_env = env; + size_t argc = MAX_INPUT_COUNT; + napi_value self = nullptr; + napi_value argv[MAX_INPUT_COUNT] = { nullptr }; + NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); + + context_ = new AsyncContext(); + 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; + } + // int -->input_(env, argc, argv, self) + int status = (*context)(env, argc, argv, self); + // if input return is not ok, then napi_throw_error context error + PRE_NAPI_ASSERT_RETURN_VOID(env, status == OK, context->error); + 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::SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr error, int apiversion) +{ + napi_create_object(env, businessError); + // if error is not inner error, and api version greater 8 + if (error != nullptr || apiversion > 8) { + napi_value code = nullptr; + napi_value msg = nullptr; + napi_create_int32(env, error->GetCode(), &code); + napi_create_string_utf8(env, error->GetMessage().c_str(), NAPI_AUTO_LENGTH, &msg); + napi_set_named_property(env, *businessError, "code", code); + napi_set_named_property(env, *businessError, "message", msg); + } +} + +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; + int outStatus = ERR; + // if async execute status is not napi_ok then un-execute out function + if (status == napi_ok) { + outStatus = (*context->ctx)(env, output); + } + napi_value result[ARG_BUTT] = { 0 }; + // if out function status is ok then async renturn output data, else return error. + if (outStatus == 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 businessError = nullptr; + SetBusinessError(env, &businessError, context->ctx->error, context->ctx->apiversion); + result[ARG_ERROR] = businessError; + napi_get_undefined(env, &result[ARG_DATA]); + } + if (context->defer != nullptr) { + // promise + if (status == napi_ok && outStatus == 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; +} +} // namespace PreferencesJsKit } // namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/js/napi/common/src/js_ability.cpp b/preferences/frameworks/js/common/src/js_ability.cpp similarity index 97% rename from preferences/frameworks/js/napi/common/src/js_ability.cpp rename to preferences/frameworks/js/common/src/js_ability.cpp index 5bfd2a4de696fd240bed1713d09d9f1fb2476ad2..ae825a7da8ebe4a02a1631fe41b8d574ff05b6ec 100644 --- a/preferences/frameworks/js/napi/common/src/js_ability.cpp +++ b/preferences/frameworks/js/common/src/js_ability.cpp @@ -19,7 +19,7 @@ #include "js_logger.h" namespace OHOS { -namespace AppDataMgrJsKit { +namespace PreferencesJsKit { Context::Context(std::shared_ptr stageContext) { preferencesDir_ = stageContext->GetPreferencesDir(); @@ -78,5 +78,5 @@ std::shared_ptr JSAbility::GetContext(napi_env env, napi_value value) } return std::make_shared(abilityContext); } -} // namespace AppDataMgrJsKit +} // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/common/src/js_observer.cpp b/preferences/frameworks/js/common/src/js_observer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ffc738cc5f650afce55c86fb4ac95c223c340180 --- /dev/null +++ b/preferences/frameworks/js/common/src/js_observer.cpp @@ -0,0 +1,57 @@ +/* + * 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_observer.h" + +namespace OHOS::PreferencesJsKit { +JSObserver::JSObserver(std::shared_ptr uvQueue, napi_value callback) + : uvQueue_(uvQueue) +{ + napi_create_reference(uvQueue_->GetEnv(), callback, 1, &callback_); +} + +JSObserver::~JSObserver() +{ + if (callback_ == nullptr) { + return ; + } + napi_delete_reference(uvQueue_->GetEnv(), callback_); + callback_ = nullptr; +} + +napi_ref JSObserver::GetCallback() +{ + return callback_; +} + +void JSObserver::AsyncCall(UvQueue::NapiArgsGenerator genArgs) +{ + if (callback_ == nullptr) { + return; + } + + uvQueue_->AsyncCall( + [observer = shared_from_this()](napi_env env) -> napi_value { + // the lambda run in js main thread, so it serial run with Clear(), so we can use no lock. + if (observer->callback_ == nullptr) { + return nullptr; + } + napi_value callback = nullptr; + napi_get_reference_value(env, observer->callback_, &callback); + return callback; + }, + genArgs); +} +} // namespace OHOS::DistributedKVStore diff --git a/preferences/frameworks/js/napi/common/src/js_utils.cpp b/preferences/frameworks/js/common/src/js_utils.cpp similarity index 94% rename from preferences/frameworks/js/napi/common/src/js_utils.cpp rename to preferences/frameworks/js/common/src/js_utils.cpp index 1378858b29b281bc119dfdde29ada92996ca5073..738a60bc23f6576f169ac5d5f2258eccdc23b28c 100644 --- a/preferences/frameworks/js/napi/common/src/js_utils.cpp +++ b/preferences/frameworks/js/common/src/js_utils.cpp @@ -22,7 +22,7 @@ #endif namespace OHOS { -namespace AppDataMgrJsKit { +namespace PreferencesJsKit { int32_t JSUtils::Convert2String(napi_env env, napi_value jsStr, std::string &output) { char *str = new char[MAX_VALUE_LENGTH + 1]; @@ -140,10 +140,23 @@ int32_t JSUtils::Convert2DoubleVector(napi_env env, napi_value value, std::vecto return OK; } +bool JSUtils::Equals(napi_env env, napi_value value, napi_ref copy) +{ + if (copy == nullptr) { + return (value == nullptr); + } + + napi_value copyValue = nullptr; + napi_get_reference_value(env, copy, ©Value); + + bool isEquals = false; + napi_strict_equals(env, value, copyValue, &isEquals); + return isEquals; +} + int32_t JSUtils::Convert2JSValue(napi_env env, std::string value, napi_value &output) { - std::string tempStr = std::string(value); - if (napi_create_string_utf8(env, tempStr.c_str(), tempStr.size(), &output) != napi_ok) { + if (napi_create_string_utf8(env, value.c_str(), value.size(), &output) != napi_ok) { LOG_ERROR("Convert2JSValue create JS string failed"); return ERR; } @@ -236,5 +249,5 @@ int32_t JSUtils::Convert2JSStringArr(napi_env env, std::vector valu } return OK; } -} // namespace AppDataMgrJsKit +} // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/common/src/napi_uv_queue.cpp b/preferences/frameworks/js/common/src/uv_queue.cpp similarity index 38% rename from preferences/frameworks/js/napi/common/src/napi_uv_queue.cpp rename to preferences/frameworks/js/common/src/uv_queue.cpp index f9f54934d56e61496e5a6fb482a0c24e6af80b3b..34917cc543bd18b4308e2399a0fb3181b5906143 100644 --- a/preferences/frameworks/js/napi/common/src/napi_uv_queue.cpp +++ b/preferences/frameworks/js/common/src/uv_queue.cpp @@ -12,63 +12,72 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "uv_queue.h" -#include "napi_uv_queue.h" -#include "uv.h" -#include "js_logger.h" +#include -using OHOS::AppDataMgrJsKit::PREFIX_LABEL; +#include "js_logger.h" -namespace OHOS::RdbJsKit { -NapiUvQueue::NapiUvQueue(napi_env env, napi_value callback) +namespace OHOS::PreferencesJsKit { +constexpr size_t MAX_CALLBACK_ARG_NUM = 6; +UvQueue::UvQueue(napi_env env) : env_(env) { - napi_create_reference(env, callback, 1, &callback_); - napi_get_uv_event_loop(env, &loop_); + if (env != nullptr) { + napi_get_uv_event_loop(env, &loop_); + } } -NapiUvQueue::~NapiUvQueue() +UvQueue::~UvQueue() { - napi_delete_reference(env_, callback_); + LOG_DEBUG("no memory leak for queue-callback"); + env_ = nullptr; } -bool NapiUvQueue::operator==(napi_value value) +void UvQueue::AsyncCall(NapiCallbackGetter getter, NapiArgsGenerator genArgs) { - napi_value callback = nullptr; - napi_get_reference_value(env_, callback_, &callback); - - bool isEquals = false; - napi_strict_equals(env_, value, callback, &isEquals); - return isEquals; -} + if (loop_ == nullptr || !getter) { + LOG_ERROR("loop_ or callback is nullptr"); + return; + } -void NapiUvQueue::CallFunction(NapiArgsGenerator genArgs) -{ uv_work_t* work = new (std::nothrow) uv_work_t; if (work == nullptr) { + LOG_ERROR("no memory for uv_work_t"); return; } - work->data = this; - this->args = std::move(genArgs); - - uv_queue_work(loop_, work, [](uv_work_t* work) {}, [](uv_work_t* work, int st) { - auto queue = static_cast(work->data); + work->data = new UvEntry{ env_, getter, std::move(genArgs) }; + uv_queue_work( + loop_, work, [](uv_work_t* work) {}, + [](uv_work_t* work, int uvstatus) { + std::shared_ptr entry(static_cast(work->data), [work](UvEntry *data) { + delete data; + delete work; + }); + napi_value method = entry->callback(entry->env); + if (method == nullptr) { + LOG_ERROR("the callback is invalid, maybe is cleared!"); + return ; + } int argc = 0; napi_value argv[MAX_CALLBACK_ARG_NUM] = { nullptr }; - if (queue->args) { - queue->args(queue->env_, argc, argv); + if (entry->args) { + argc = MAX_CALLBACK_ARG_NUM; + entry->args(entry->env, argc, argv); } - - napi_value callback = nullptr; - napi_get_reference_value(queue->env_, queue->callback_, &callback); + LOG_DEBUG("queue uv_after_work_cb"); napi_value global = nullptr; - napi_get_global(queue->env_, &global); + napi_get_global(entry->env, &global); napi_value result; - napi_status status = napi_call_function(queue->env_, global, callback, argc, argv, &result); + napi_status status = napi_call_function(entry->env, global, method, argc, argv, &result); if (status != napi_ok) { - LOG_ERROR("napi_call_function failed, status=%{public}d", status); + LOG_ERROR("notify data change failed status:%{public}d.", status); } - delete work; }); } -} // namespace OHOS::RdbJsKit \ No newline at end of file + +napi_env UvQueue::GetEnv() +{ + return env_; +} +} // namespace OHOS::DistributedKVStore diff --git a/preferences/frameworks/js/napi/include/napi_preferences.h b/preferences/frameworks/js/napi/include/napi_preferences.h index 3b42774dbd9238f21a0d41dcf2212ea2637b25ca..3e23a35835c6558ae814e10fbcd54bfe4a05cfd0 100644 --- a/preferences/frameworks/js/napi/include/napi_preferences.h +++ b/preferences/frameworks/js/napi/include/napi_preferences.h @@ -18,10 +18,13 @@ #include +#include + +#include "js_observer.h" #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" -#include "napi_uv_queue.h" +#include "napi_preferences_observer.h" #include "preferences.h" #include "preferences_helper.h" @@ -48,18 +51,17 @@ private: static napi_value UnRegisterObserver(napi_env env, napi_callback_info info); static napi_value GetAll(napi_env env, napi_callback_info info); + bool HasRegisteredObserver(napi_value callback); + void RegisteredObserver(napi_value callback); + void UnRegisteredObserver(napi_value callback); + std::shared_ptr value_; napi_env env_; napi_ref wrapper_; - std::shared_ptr observer_; -}; -class PreferencesObserverImpl - : public OHOS::NativePreferences::PreferencesObserver, public OHOS::RdbJsKit::NapiUvQueue { -public: - PreferencesObserverImpl(napi_env env, napi_value callback); - virtual ~PreferencesObserverImpl(); - void OnChange(const std::string &key) override; + std::mutex listMutex_ {}; + std::list> dataObserver_; + std::shared_ptr uvQueue_; }; } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/include/napi_preferences_observer.h b/preferences/frameworks/js/napi/include/napi_preferences_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..fa94732c61d85464b0b95badf800de3efd00d471 --- /dev/null +++ b/preferences/frameworks/js/napi/include/napi_preferences_observer.h @@ -0,0 +1,35 @@ +/* + * 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 DISTRIBUTEDDATAMGR_PREFERENCES_NAPI_PREFERENCES_OBSERVER_H +#define DISTRIBUTEDDATAMGR_PREFERENCES_NAPI_PREFERENCES_OBSERVER_H + +#include "napi/native_api.h" +#include "preferences_observer.h" +#include "js_observer.h" + +namespace OHOS { +namespace PreferencesJsKit { +class JSPreferencesObserver + : public OHOS::NativePreferences::PreferencesObserver + , public JSObserver { +public: + JSPreferencesObserver(std::shared_ptr uvQueue, napi_value callback); + virtual ~JSPreferencesObserver() = default; + void OnChange(const std::string &key) override; +}; +} // namespace PreferencesJsKit +} // namespace OHOS +#endif //DISTRIBUTEDDATAMGR_PREFERENCES_NAPI_PREFERENCES_OBSERVER_H diff --git a/preferences/frameworks/js/napi/include/napi_storage.h b/preferences/frameworks/js/napi/include/napi_storage.h index a02ed714616a1d8b3c5b951fd531a4e6dc2c6bd8..57334fc8afb54ed718712eb55b5b6cfb3ec6b674 100644 --- a/preferences/frameworks/js/napi/include/napi_storage.h +++ b/preferences/frameworks/js/napi/include/napi_storage.h @@ -18,15 +18,18 @@ #include +#include + +#include "js_observer.h" #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" -#include "napi_uv_queue.h" +#include "napi_preferences_observer.h" #include "preferences.h" #include "preferences_helper.h" namespace OHOS { -namespace SystemStorageJsKit { +namespace PreferencesJsKit { class StorageProxy { public: static void Init(napi_env env, napi_value exports); @@ -53,18 +56,16 @@ private: static napi_value RegisterObserver(napi_env env, napi_callback_info info); static napi_value UnRegisterObserver(napi_env env, napi_callback_info info); + bool HasRegisteredObserver(napi_value callback); + void RegisterObserver(napi_value callback); + void UnRegisterObserver(napi_value callback); + std::shared_ptr value_; napi_env env_; napi_ref wrapper_; - std::shared_ptr observer_; -}; - -class StorageObserverImpl - : public OHOS::NativePreferences::PreferencesObserver, public OHOS::RdbJsKit::NapiUvQueue { -public: - StorageObserverImpl(napi_env env, napi_value callback); - virtual ~StorageObserverImpl(); - void OnChange(const std::string &key) override; + std::mutex listMutex_ {}; + std::shared_ptr uvQueue_; + std::list> dataObserver_; }; } // namespace PreferencesJsKit } // namespace OHOS diff --git a/preferences/frameworks/js/napi/include/napi_storage_helper.h b/preferences/frameworks/js/napi/include/napi_storage_helper.h index e27a4e3481e43f55ecb9a537c9be79a605b99206..a12013337ccec94c848d3094e03355e5615ff770 100644 --- a/preferences/frameworks/js/napi/include/napi_storage_helper.h +++ b/preferences/frameworks/js/napi/include/napi_storage_helper.h @@ -20,7 +20,7 @@ #include "napi/native_node_api.h" namespace OHOS { -namespace SystemStorageJsKit { +namespace PreferencesJsKit { napi_value InitPreferenceHelper(napi_env env, napi_value exports); } } // namespace OHOS diff --git a/preferences/frameworks/js/napi/include/napi_system_storage.h b/preferences/frameworks/js/napi/include/napi_system_storage.h index c1d746ecaf2bb9c2e28daefd528f358be0133967..6543d0d9eaff54fb6ceb1b26261424da395b73ec 100644 --- a/preferences/frameworks/js/napi/include/napi_system_storage.h +++ b/preferences/frameworks/js/napi/include/napi_system_storage.h @@ -20,8 +20,8 @@ #include "napi/native_node_api.h" namespace OHOS { -namespace SystemStorageJsKit { +namespace PreferencesJsKit { napi_value InitSystemStorage(napi_env env, napi_value exports); -} // namespace SystemStorageJsKit +} // namespace PreferencesJsKit } // 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_storage.cpp b/preferences/frameworks/js/napi/src/entry_point_storage.cpp index 021eb92e4269bd3cb275dd41caa4cf466f6196a6..e8aa30071777e05e1a54fbec20290ceedc82cbd2 100644 --- a/preferences/frameworks/js/napi/src/entry_point_storage.cpp +++ b/preferences/frameworks/js/napi/src/entry_point_storage.cpp @@ -17,7 +17,7 @@ #include "napi_storage.h" #include "napi_storage_helper.h" -using namespace OHOS::SystemStorageJsKit; +using namespace OHOS::PreferencesJsKit; EXTERN_C_START /* diff --git a/preferences/frameworks/js/napi/src/entry_point_system_storage.cpp b/preferences/frameworks/js/napi/src/entry_point_system_storage.cpp index c12b835d816c48259050addbb366615685da3025..79263993a7421a09391a8c5e5d5819603787bcb0 100644 --- a/preferences/frameworks/js/napi/src/entry_point_system_storage.cpp +++ b/preferences/frameworks/js/napi/src/entry_point_system_storage.cpp @@ -22,7 +22,7 @@ EXTERN_C_START */ static napi_value Init(napi_env env, napi_value exports) { - OHOS::SystemStorageJsKit::InitSystemStorage(env, exports); + OHOS::PreferencesJsKit::InitSystemStorage(env, exports); return exports; } EXTERN_C_END diff --git a/preferences/frameworks/js/napi/src/napi_preferences.cpp b/preferences/frameworks/js/napi/src/napi_preferences.cpp index 2ba08fe51706861c511e2211021b5338df5a2b2a..3ea3e6df3698a3eb0bcd0720ebc34f04f2490830 100644 --- a/preferences/frameworks/js/napi/src/napi_preferences.cpp +++ b/preferences/frameworks/js/napi/src/napi_preferences.cpp @@ -14,11 +14,12 @@ */ #include "napi_preferences.h" -#include + +#include #include +#include #include -#include "adaptor.h" #include "async_call.h" #include "js_logger.h" #include "js_utils.h" @@ -26,10 +27,9 @@ #include "preferences.h" #include "preferences_errno.h" #include "preferences_value.h" +#include "securec.h" using namespace OHOS::NativePreferences; -using namespace OHOS::AppDataMgrJsKit; -using namespace OHOS::RdbJsKit; namespace OHOS { namespace PreferencesJsKit { @@ -40,14 +40,15 @@ struct PreferencesAysncContext : public AsyncCall::Context { std::string key; PreferencesValue defValue = PreferencesValue((int)0); std::map allElements; - bool hasKey; + bool hasKey = false; std::list keysModified; std::vector> preferencesObservers; PreferencesAysncContext() : Context(nullptr, nullptr) { } - PreferencesAysncContext(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) + PreferencesAysncContext(InputAction input, OutputAction output) + : Context(std::move(input), std::move(output)) { } virtual ~PreferencesAysncContext(){}; @@ -66,13 +67,17 @@ struct PreferencesAysncContext : public AsyncCall::Context { static __thread napi_ref constructor_; PreferencesProxy::PreferencesProxy(std::shared_ptr &value) - : value_(value), env_(nullptr), wrapper_(nullptr) + : value_(value), env_(nullptr), wrapper_(nullptr), uvQueue_(nullptr) { } PreferencesProxy::~PreferencesProxy() { napi_delete_reference(env_, wrapper_); + for (auto& observer : dataObserver_) { + value_->UnRegisterObserver(observer); + } + dataObserver_.clear(); } void PreferencesProxy::Destructor(napi_env env, void *nativeObject, void *finalize_hint) @@ -153,17 +158,14 @@ napi_value PreferencesProxy::New(napi_env env, napi_callback_info info) NAPI_ASSERT(env, preference != nullptr, "failed to call native"); PreferencesProxy *obj = new PreferencesProxy(preference); obj->env_ = env; + obj->value_ = std::move(preference); + obj->uvQueue_ = std::make_shared(env); NAPI_CALL(env, napi_wrap(env, thiz, obj, PreferencesProxy::Destructor, nullptr, // finalize_hint &obj->wrapper_)); return thiz; } -static bool IsFloat(double input) -{ - return abs(input - floor(input)) >= 0; // DBL_EPSILON; -} - int ParseKey(const napi_env &env, const napi_value &arg, std::shared_ptr context) { // get input key @@ -356,7 +358,6 @@ int32_t GetAllExecute(std::shared_ptr context, napi_va return ERR; } } else if (value.IsString()) { - std::string tempStr = (std::string)value; if (JSUtils::Convert2JSValue(context->_env, (std::string)value, jsVal) != napi_ok) { LOG_ERROR("PreferencesProxy::GetAll get property string failed"); return ERR; @@ -614,16 +615,16 @@ napi_value PreferencesProxy::RegisterObserver(napi_env env, napi_callback_info i NAPI_CALL(env, napi_typeof(env, args[0], &type)); PRE_NAPI_ASSERT(env, type == napi_string, std::make_shared("type", "string 'change'.")); + std::string chang; + int ret = JSUtils::Convert2String(env, args[0], chang); + PRE_NAPI_ASSERT(env, ret == OK && chang == "change", std::make_shared("type", "string 'change'.")); + NAPI_CALL(env, napi_typeof(env, args[1], &type)); PRE_NAPI_ASSERT(env, type == napi_function, std::make_shared("callback", "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"); + obj->RegisteredObserver(args[1]); return nullptr; } @@ -639,36 +640,55 @@ napi_value PreferencesProxy::UnRegisterObserver(napi_env env, napi_callback_info NAPI_CALL(env, napi_typeof(env, args[0], &type)); PRE_NAPI_ASSERT(env, type == napi_string, std::make_shared("type", "string 'change'.")); + std::string chang; + int ret = JSUtils::Convert2String(env, args[0], chang); + PRE_NAPI_ASSERT(env, ret == OK && chang == "change", std::make_shared("type", "string 'change'.")); + NAPI_CALL(env, napi_typeof(env, args[1], &type)); PRE_NAPI_ASSERT(env, type == napi_function, std::make_shared("callback", "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"); + obj->UnRegisteredObserver(args[1]); + return nullptr; } -PreferencesObserverImpl::PreferencesObserverImpl(napi_env env, napi_value callback) : NapiUvQueue(env, callback) +bool PreferencesProxy::HasRegisteredObserver(napi_value callback) { + std::lock_guard lck(listMutex_); + for (auto &it : dataObserver_) { + if (JSUtils::Equals(env_, callback, it->GetCallback())) { + LOG_INFO("The observer has already subscribed."); + return true; + } + } + return false; } -PreferencesObserverImpl::~PreferencesObserverImpl() +void PreferencesProxy::RegisteredObserver(napi_value callback) { + if (!HasRegisteredObserver(callback)) { + auto observer = std::make_shared(uvQueue_, callback); + value_->RegisterObserver(observer); + dataObserver_.push_back(observer); + LOG_INFO("The observer subscribed success."); + } } -void PreferencesObserverImpl::OnChange(const std::string &key) +void PreferencesProxy::UnRegisteredObserver(napi_value callback) { - CallFunction([key](napi_env env, int &argc, napi_value *argv) { - argc = 1; - int status = JSUtils::Convert2JSValue(env, key, argv[0]); - if (status != OK) { - LOG_DEBUG("OnChange CallFunction error."); + std::lock_guard lck(listMutex_); + auto it = dataObserver_.begin(); + while (it != dataObserver_.end()) { + if (!JSUtils::Equals(env_, callback, (*it)->GetCallback())) { + ++it; + continue; // specified observer and not current iterator } - }); - LOG_DEBUG("OnChange key end"); + value_->UnRegisterObserver(*it); + it = dataObserver_.erase(it); + LOG_INFO("The observer unsubscribed success."); + } } } // 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 index db6308c9c6d9594c3ba93b79821a6919a451ef76..e89435c8bf7f0fb68452ce8f99584f7a93e2e67e 100644 --- a/preferences/frameworks/js/napi/src/napi_preferences_helper.cpp +++ b/preferences/frameworks/js/napi/src/napi_preferences_helper.cpp @@ -16,7 +16,6 @@ #include -#include "adaptor.h" #include "async_call.h" #include "js_ability.h" #include "js_logger.h" @@ -24,15 +23,15 @@ #include "napi_preferences.h" #include "napi_preferences_error.h" #include "preferences_errno.h" +#include "securec.h" using namespace OHOS::NativePreferences; -using namespace OHOS::AppDataMgrJsKit; namespace OHOS { namespace PreferencesJsKit { struct HelperAysncContext : public AsyncCall::Context { std::string path; - std::shared_ptr abilitycontext; + std::shared_ptr abilitycontext; HelperAysncContext() : Context(nullptr, nullptr) { diff --git a/preferences/frameworks/js/napi/src/napi_preferences_observer.cpp b/preferences/frameworks/js/napi/src/napi_preferences_observer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ad4f5aeb6198a7899dac74cbc81650893b7bd02 --- /dev/null +++ b/preferences/frameworks/js/napi/src/napi_preferences_observer.cpp @@ -0,0 +1,39 @@ +/* + * 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_preferences_observer.h" + +#include "js_logger.h" +#include "js_utils.h" + +namespace OHOS { +namespace PreferencesJsKit { +JSPreferencesObserver::JSPreferencesObserver(std::shared_ptr uvQueue, napi_value callback) + : JSObserver(uvQueue, callback) +{ +} + +void JSPreferencesObserver::OnChange(const std::string &key) +{ + AsyncCall([key](napi_env env, int &argc, napi_value *argv) { + argc = 1; + int status = JSUtils::Convert2JSValue(env, key, argv[0]); + if (status != JSUtils::OK) { + LOG_DEBUG("OnChange CallFunction error."); + } + }); + LOG_DEBUG("OnChange key end"); +} +} // namespace PreferencesJsKit +} // namespace OHOS \ No newline at end of file diff --git a/preferences/frameworks/js/napi/src/napi_storage.cpp b/preferences/frameworks/js/napi/src/napi_storage.cpp index 7aaa66f524e519815171c0cf6bd9ca907a613307..14098e901ccd42b782b243971efe848cd36c2df6 100644 --- a/preferences/frameworks/js/napi/src/napi_storage.cpp +++ b/preferences/frameworks/js/napi/src/napi_storage.cpp @@ -17,7 +17,7 @@ #include #include -#include +#include #include "js_logger.h" #include "js_utils.h" @@ -28,11 +28,9 @@ #include "securec.h" using namespace OHOS::NativePreferences; -using namespace OHOS::AppDataMgrJsKit; -using namespace OHOS::RdbJsKit; namespace OHOS { -namespace SystemStorageJsKit { +namespace PreferencesJsKit { #define MAX_KEY_LENGTH Preferences::MAX_KEY_LENGTH #define MAX_VALUE_LENGTH Preferences::MAX_VALUE_LENGTH @@ -45,13 +43,17 @@ struct StorageAysncContext : NapiAsyncProxy::AysncContext { static __thread napi_ref constructor_; StorageProxy::StorageProxy(std::shared_ptr &value) - : value_(value), env_(nullptr), wrapper_(nullptr) + : value_(value), env_(nullptr), wrapper_(nullptr), uvQueue_(nullptr) { } StorageProxy::~StorageProxy() { napi_delete_reference(env_, wrapper_); + for (auto& observer : dataObserver_) { + value_->UnRegisterObserver(observer); + } + dataObserver_.clear(); } void StorageProxy::Destructor(napi_env env, void *nativeObject, void *finalize_hint) @@ -129,6 +131,8 @@ napi_value StorageProxy::New(napi_env env, napi_callback_info info) NAPI_ASSERT(env, preference != nullptr, "failed to call native"); StorageProxy *obj = new StorageProxy(preference); obj->env_ = env; + obj->value_ = std::move(preference); + obj->uvQueue_ = std::make_shared(env); NAPI_CALL(env, napi_wrap(env, thiz, obj, StorageProxy::Destructor, nullptr, // finalize_hint &obj->wrapper_)); @@ -143,11 +147,6 @@ template bool CheckNumberType(double input) return true; } -static 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; @@ -524,18 +523,18 @@ napi_value StorageProxy::RegisterObserver(napi_env env, napi_callback_info info) 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_ASSERT(env, type == napi_string, "type should be 'change'"); + + std::string change; + int ret = JSUtils::Convert2String(env, args[0], change); + NAPI_ASSERT(env, ret == OK && change == "change", "type should be 'change'"); 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"); + obj->RegisterObserver(args[1]); return nullptr; } @@ -551,36 +550,55 @@ napi_value StorageProxy::UnRegisterObserver(napi_env env, napi_callback_info inf NAPI_CALL(env, napi_typeof(env, args[0], &type)); NAPI_ASSERT(env, type == napi_string, "key not string type"); + std::string change; + int ret = JSUtils::Convert2String(env, args[0], change); + NAPI_ASSERT(env, ret == OK && change == "change", "type should be 'change'"); + 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"); + obj->UnRegisterObserver(args[1]); + return nullptr; } -StorageObserverImpl::StorageObserverImpl(napi_env env, napi_value callback) : NapiUvQueue(env, callback) +bool StorageProxy::HasRegisteredObserver(napi_value callback) { + std::lock_guard lck(listMutex_); + for (auto &it : dataObserver_) { + if (JSUtils::Equals(env_, callback, it->GetCallback())) { + LOG_INFO("The observer has already subscribed."); + return true; + } + } + return false; } -StorageObserverImpl::~StorageObserverImpl() +void StorageProxy::RegisterObserver(napi_value callback) { + if (!HasRegisteredObserver(callback)) { + auto observer = std::make_shared(uvQueue_, callback); + value_->RegisterObserver(observer); + dataObserver_.push_back(observer); + LOG_INFO("The observer subscribed success."); + } } -void StorageObserverImpl::OnChange(const std::string &key) +void StorageProxy::UnRegisterObserver(napi_value callback) { - CallFunction([key](napi_env env, int &argc, napi_value *argv) { - argc = 1; - int status = JSUtils::Convert2JSValue(env, key, argv[0]); - if (status != OK) { - LOG_DEBUG("OnChange CallFunction error."); + std::lock_guard lck(listMutex_); + auto it = dataObserver_.begin(); + while (it != dataObserver_.end()) { + if (!JSUtils::Equals(env_, callback, (*it)->GetCallback())) { + ++it; + continue; // specified observer and not current iterator } - }); - LOG_DEBUG("OnChange key end"); + value_->UnRegisterObserver(*it); + it = dataObserver_.erase(it); + LOG_INFO("The observer unsubscribed success."); + } } } // 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 index 6437e2d825cdcded8163eb3b4cacac1421d6f416..e117aed44e79a38390656a3e5ad421eeaeec3631 100644 --- a/preferences/frameworks/js/napi/src/napi_storage_helper.cpp +++ b/preferences/frameworks/js/napi/src/napi_storage_helper.cpp @@ -13,19 +13,20 @@ * limitations under the License. */ #include "napi_storage_helper.h" -#include + +#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 SystemStorageJsKit { +namespace PreferencesJsKit { struct HelperAysncContext : NapiAsyncProxy::AysncContext { std::string path; }; diff --git a/preferences/frameworks/js/napi/src/napi_system_storage.cpp b/preferences/frameworks/js/napi/src/napi_system_storage.cpp index c092866a40657588802f0481ba009424f3036559..e1f0f06c575d650e87799f2b2b9edc444d59d04a 100644 --- a/preferences/frameworks/js/napi/src/napi_system_storage.cpp +++ b/preferences/frameworks/js/napi/src/napi_system_storage.cpp @@ -23,11 +23,10 @@ #include "preferences_errno.h" #include "preferences_helper.h" -using namespace OHOS::AppDataMgrJsKit; using namespace OHOS::NativePreferences; namespace OHOS { -namespace SystemStorageJsKit { +namespace PreferencesJsKit { struct AsyncContext { std::string key; std::string def; @@ -55,9 +54,9 @@ void ParseString(napi_env env, napi_value &object, const char *name, const bool 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, key); - NAPI_ASSERT_RETURN_VOID(env, enable || !key.empty(), "StorageOptions is empty."); + std::string key = ""; + int32_t ret = JSUtils::Convert2String(env, value, key); + NAPI_ASSERT_RETURN_VOID(env, enable || (ret == E_OK && !key.empty()), "StorageOptions is empty."); output = std::move(key); } } @@ -280,5 +279,5 @@ napi_value InitSystemStorage(napi_env env, napi_value exports) NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } -} // namespace SystemStorageJsKit +} // namespace PreferencesJsKit } // namespace OHOS \ No newline at end of file diff --git a/preferences/interfaces/inner_api/include/adaptor.h b/preferences/frameworks/native/include/adaptor.h similarity index 74% rename from preferences/interfaces/inner_api/include/adaptor.h rename to preferences/frameworks/native/include/adaptor.h index bcf8a55622b9924f11d9ac48fd396814b42959e2..119a9beea2883cd70ff4cb865b13e72d6e759772 100644 --- a/preferences/interfaces/inner_api/include/adaptor.h +++ b/preferences/frameworks/native/include/adaptor.h @@ -23,23 +23,35 @@ #define FILE_EXIST 0 #endif +#define DO_NOTHING + #ifdef WINDOWS_PLATFORM #include #include #define REALPATH(filePath, realPath, ...) (_fullpath(realPath, filePath, ##__VA_ARGS__)) #define MKDIR(filePath) (mkdir(filePath)) #define ACCESS(filePath) (_access(filePath, FILE_EXIST)) -#else -#include +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING + +#elif MAC_PLATFORM +#include +#include +#include #define REALPATH(filePath, realPath, ...) (realpath(filePath, realPath)) +#define MKDIR(filePath) (mkdir(filePath, FILE_MODE)) +#define ACCESS(filePath) (access(filePath, FILE_EXIST)) +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING -#ifdef MAC_PLATFORM +#else #include #include #include +#include +#include "hitrace.h" +#define REALPATH(filePath, realPath, ...) (realpath(filePath, realPath)) #define MKDIR(filePath) (mkdir(filePath, FILE_MODE)) #define ACCESS(filePath) (access(filePath, FILE_EXIST)) -#endif +#define DISTRIBUTED_DATA_HITRACE(trace) HiTrace hitrace(trace) #endif diff --git a/preferences/frameworks/native/include/hitrace.h b/preferences/frameworks/native/include/hitrace.h new file mode 100644 index 0000000000000000000000000000000000000000..50b8412243f9daa46f39084c8a7c2b7b13932e95 --- /dev/null +++ b/preferences/frameworks/native/include/hitrace.h @@ -0,0 +1,40 @@ +/* + * 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 DISTRIBUTEDDATAMGR_PREFERENCES_HITRACE_H +#define DISTRIBUTEDDATAMGR_PREFERENCES_HITRACE_H + +#include + +#include "hitrace_meter.h" + +namespace OHOS { +namespace NativePreferences { +class HiTrace final { +public: + inline HiTrace(const std::string &value) + { + StartTrace(HITRACE_TAG_DISTRIBUTEDDATA, value); + } + + inline ~HiTrace() + { + FinishTrace(HITRACE_TAG_DISTRIBUTEDDATA); + } +}; +} // namespace NativePreferences +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/preferences/interfaces/inner_api/include/preferences_xml_utils.h b/preferences/frameworks/native/include/preferences_xml_utils.h similarity index 100% rename from preferences/interfaces/inner_api/include/preferences_xml_utils.h rename to preferences/frameworks/native/include/preferences_xml_utils.h diff --git a/preferences/frameworks/native/src/preferences_helper.cpp b/preferences/frameworks/native/src/preferences_helper.cpp index 56de2648a8d418aacee30104c75b054ac0563d5a..3c8e09923d7f8fee1eaa5f67338fc80276ee367a 100644 --- a/preferences/frameworks/native/src/preferences_helper.cpp +++ b/preferences/frameworks/native/src/preferences_helper.cpp @@ -22,7 +22,6 @@ #include #include "adaptor.h" - #include "logger.h" #include "preferences.h" #include "preferences_errno.h" @@ -93,6 +92,7 @@ std::string PreferencesHelper::GetRealPath(const std::string &path, int &errorCo std::shared_ptr PreferencesHelper::GetPreferences(const std::string &path, int &errCode) { + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::string realPath = GetRealPath(path, errCode); if (realPath == "" || errCode != E_OK) { return nullptr; @@ -116,6 +116,7 @@ std::shared_ptr PreferencesHelper::GetPreferences(const std::string int PreferencesHelper::DeletePreferences(const std::string &path) { + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); int errCode = E_OK; std::string realPath = GetRealPath(path, errCode); if (realPath == "" || errCode != E_OK) { @@ -144,6 +145,7 @@ int PreferencesHelper::DeletePreferences(const std::string &path) int PreferencesHelper::RemovePreferencesFromCache(const std::string &path) { + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); int errCode = E_OK; std::string realPath = GetRealPath(path, errCode); if (realPath == "" || errCode != E_OK) { diff --git a/preferences/frameworks/native/src/preferences_impl.cpp b/preferences/frameworks/native/src/preferences_impl.cpp index 25692cc242f385231392307d9a1f9fbff51b1201..031669677f504da1b84b3f1fa12a8cedffb79bf4 100644 --- a/preferences/frameworks/native/src/preferences_impl.cpp +++ b/preferences/frameworks/native/src/preferences_impl.cpp @@ -489,6 +489,7 @@ int PreferencesImpl::Clear() void PreferencesImpl::Flush() { + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::shared_ptr request = commitToMemory(); request->isSyncRequest_ = false; diff --git a/preferences/interfaces/inner_api/BUILD.gn b/preferences/interfaces/inner_api/BUILD.gn index 46cc61faf1773c8b9ccbdbbc7da1a570a4e31ded..f9f84788146cd296a346edbfb2ed4441cc422820 100644 --- a/preferences/interfaces/inner_api/BUILD.gn +++ b/preferences/interfaces/inner_api/BUILD.gn @@ -66,6 +66,7 @@ ohos_shared_library("native_preferences") { external_deps = [ "c_utils:utils", "hilog_native:libhilog", + "hitrace_native:hitrace_meter", ] } diff --git a/preferences/test/native/fuzztest/preferences_fuzzer/BUILD.gn b/preferences/test/native/fuzztest/preferences_fuzzer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a93f703fbc49503434ebc7054eb4373d72f2f617 --- /dev/null +++ b/preferences/test/native/fuzztest/preferences_fuzzer/BUILD.gn @@ -0,0 +1,52 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "//foundation/distributeddatamgr/preferences/interfaces/inner_api/include", + ] +} + +##############################fuzztest########################################## +ohos_fuzztest("PreferencesFuzzTest") { + module_out_path = "preferences/impl" + + fuzz_config_file = "//foundation/distributeddatamgr/preferences/test/native/fuzztest/preferences_fuzzer" + + sources = [ "preferences_fuzzer.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "c_utils:utils", + "hilog_native:libhilog", + "ipc:ipc_core", + "preferences:native_preferences", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":PreferencesFuzzTest", + ] +} +############################################################################### diff --git a/preferences/test/native/fuzztest/preferences_fuzzer/corpus/init b/preferences/test/native/fuzztest/preferences_fuzzer/corpus/init new file mode 100644 index 0000000000000000000000000000000000000000..8eb5a7d6eb6b7d71f0c70c244e5768d62bee6ac5 --- /dev/null +++ b/preferences/test/native/fuzztest/preferences_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/preferences/test/native/fuzztest/preferences_fuzzer/preferences_fuzzer.cpp b/preferences/test/native/fuzztest/preferences_fuzzer/preferences_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..382025d9c9a68ceb1b7155609f48eca4efa68abb --- /dev/null +++ b/preferences/test/native/fuzztest/preferences_fuzzer/preferences_fuzzer.cpp @@ -0,0 +1,231 @@ +/* + * 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 "preferences_fuzzer.h" + +#include + +#include "preferences.h" +#include "preferences_errno.h" +#include "preferences_helper.h" + +using namespace OHOS::NativePreferences; + +namespace OHOS { +class PreferencesFuzzTest { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static std::shared_ptr Preferences_; + + static const std::string LONG_KEY; +}; + +std::shared_ptr PreferencesFuzzTest::Preferences_ = nullptr; + +const std::string PreferencesFuzzTest::LONG_KEY = std::string(Preferences::MAX_KEY_LENGTH, std::toupper('a')); +; + +void PreferencesFuzzTest::SetUpTestCase(void) +{ + int errCode = E_OK; + Preferences_ = PreferencesHelper::GetPreferences("/data/test/test", errCode); +} + +void PreferencesFuzzTest::TearDownTestCase(void) +{ +} + +void PreferencesFuzzTest::SetUp(void) +{ +} + +void PreferencesFuzzTest::TearDown(void) +{ +} + +bool PutIntFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + int ret = PreferencesFuzzTest::Preferences_->PutInt(skey, svalue); + if (ret != E_OK) { + return false; + } else { + return true; + } +} + +bool GetIntFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + PreferencesFuzzTest::Preferences_->PutInt(skey, svalue); + int ret = PreferencesFuzzTest::Preferences_->GetInt(skey); + if (ret != svalue) { + return false; + } else { + return true; + } +} + +bool PutStringFuzz(const uint8_t *data, size_t size) +{ + bool result = false; + std::string skey(data, data + size); + std::string svalue(data, data + size); + int ret = PreferencesFuzzTest::Preferences_->PutString(skey, svalue); + if (!ret) { + result = true; + } + return result; +} + +bool GetStringFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + std::string svalue(data, data + size); + PreferencesFuzzTest::Preferences_->PutString(skey, svalue); + std::string ret = PreferencesFuzzTest::Preferences_->GetString(skey); + if (ret != svalue) { + return false; + } else { + return true; + } +} + +bool PutBoolFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = ((size % 2) == 0); + int ret = PreferencesFuzzTest::Preferences_->PutBool(skey, svalue); + if (ret != E_OK) { + return false; + } else { + return true; + } +} + +bool GetBoolFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = ((size % 2) == 0); + PreferencesFuzzTest::Preferences_->PutBool(skey, svalue); + bool ret = PreferencesFuzzTest::Preferences_->GetBool(skey); + if (ret != svalue) { + return false; + } else { + return true; + } +} + +bool PutFloatFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + int ret = PreferencesFuzzTest::Preferences_->PutFloat(skey, svalue); + if (ret != E_OK) { + return false; + } else { + return true; + } +} + +bool GetFloatFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + PreferencesFuzzTest::Preferences_->PutFloat(skey, svalue); + bool ret = PreferencesFuzzTest::Preferences_->GetFloat(skey); + if (ret != svalue) { + return false; + } else { + return true; + } +} + +bool PutDoubleFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + int ret = PreferencesFuzzTest::Preferences_->PutDouble(skey, svalue); + if (ret != E_OK) { + return false; + } else { + return true; + } +} + +bool GetDoubleFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + PreferencesFuzzTest::Preferences_->PutDouble(skey, svalue); + bool ret = PreferencesFuzzTest::Preferences_->GetDouble(skey); + if (ret != svalue) { + return false; + } else { + return true; + } +} + +bool PutLongFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + int ret = PreferencesFuzzTest::Preferences_->PutLong(skey, svalue); + if (ret != E_OK) { + return false; + } else { + return true; + } +} + +bool GetLongFuzz(const uint8_t *data, size_t size) +{ + std::string skey(data, data + size); + auto svalue = static_cast(size); + PreferencesFuzzTest::Preferences_->PutLong(skey, svalue); + bool ret = PreferencesFuzzTest::Preferences_->GetLong(skey); + if (ret != svalue) { + return false; + } else { + return true; + } +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + OHOS::PreferencesFuzzTest::SetUpTestCase(); + OHOS::PutIntFuzz(data, size); + OHOS::GetIntFuzz(data, size); + OHOS::PutStringFuzz(data, size); + OHOS::GetStringFuzz(data, size); + OHOS::PutBoolFuzz(data, size); + OHOS::GetBoolFuzz(data, size); + OHOS::PutFloatFuzz(data, size); + OHOS::GetFloatFuzz(data, size); + OHOS::PutDoubleFuzz(data, size); + OHOS::PutLongFuzz(data, size); + OHOS::PutDoubleFuzz(data, size); + OHOS::GetLongFuzz(data, size); + return 0; +} \ No newline at end of file diff --git a/preferences/test/native/fuzztest/preferences_fuzzer/preferences_fuzzer.h b/preferences/test/native/fuzztest/preferences_fuzzer/preferences_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..36d4a5fa09b2216b4ff93b5a92737a545086037d --- /dev/null +++ b/preferences/test/native/fuzztest/preferences_fuzzer/preferences_fuzzer.h @@ -0,0 +1,22 @@ +/* + * 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_FUZZER_H +#define PREFERENCES_FUZZER_H + +#define FUZZ_PROJECT_NAME "preferences_fuzzer" + +#endif // PREFERENCES_FUZZER_H + diff --git a/preferences/test/native/fuzztest/preferences_fuzzer/project.xml b/preferences/test/native/fuzztest/preferences_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..6e8ad2cfde8f8bda4beb6cabbe7efd8bc3c54eec --- /dev/null +++ b/preferences/test/native/fuzztest/preferences_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/preferences/test/native/unittest/preferences_test.cpp b/preferences/test/native/unittest/preferences_test.cpp index 11f75047ba34bd49fa966514cfcfd16754ccc9c9..3501bc33e6525d7d6343c35e121a610de3afd37a 100644 --- a/preferences/test/native/unittest/preferences_test.cpp +++ b/preferences/test/native/unittest/preferences_test.cpp @@ -25,6 +25,7 @@ #include "preferences_errno.h" #include "preferences_helper.h" #include "preferences_observer.h" +#include "preferences_value.h" using namespace testing::ext; using namespace OHOS::NativePreferences; @@ -704,3 +705,49 @@ HWTEST_F(PreferencesTest, NativePreferencesTest_025, TestSize.Level1) ret = pref->GetBool(PreferencesTest::KEY_TEST_BOOL_ELEMENT); EXPECT_EQ(ret, true); } + +/** + * @tc.name: OperatorTest_001 + * @tc.desc: normal testcase of PreferencesValue Operator + * @tc.type: FUNC + * @tc.require: AR000CU2BN + * @tc.author: xiuhongju + */ +HWTEST_F(PreferencesTest, PreferencesValueTest_001, TestSize.Level1) +{ + int valueInt = 1; + int retInt = PreferencesValue(valueInt); + EXPECT_EQ(valueInt, retInt); + + int64_t valueInt64 = 1; + int64_t retInt64 = PreferencesValue(valueInt64); + EXPECT_EQ(valueInt64, retInt64); + + float valueFloat = 1.0; + float retFloat = PreferencesValue(valueFloat); + EXPECT_EQ(valueFloat, retFloat); + + double valueDouble = 1.0; + double retDouble = PreferencesValue(valueDouble); + EXPECT_EQ(valueDouble, retDouble); + + bool valueBool = true; + bool retBool = PreferencesValue(valueBool); + EXPECT_EQ(valueBool, retBool); + + string valueString = "test"; + string retString = PreferencesValue(valueString); + EXPECT_EQ(valueString, retString); + + std::vector valueVectorBool(2, true); + std::vector retVectorBool = PreferencesValue(valueVectorBool); + EXPECT_EQ(valueVectorBool, retVectorBool); + + std::vector valueVectorDouble(2, 1.0); + std::vector retVectorDouble = PreferencesValue(valueVectorDouble); + EXPECT_EQ(valueVectorDouble, retVectorDouble); + + std::vector valueVectorString(2, "test"); + std::vector retVectorString = PreferencesValue(valueVectorString); + EXPECT_EQ(valueVectorString, retVectorString); +} diff --git a/relational_store/frameworks/js/napi/common/mock/src/js_utils.cpp b/relational_store/frameworks/js/napi/common/mock/src/js_utils.cpp index 757f0d8d238096559f8262efd3220bca2dee9e34..dc7c10693c73e6156f4e1f9ea4206e4962fed7a3 100644 --- a/relational_store/frameworks/js/napi/common/mock/src/js_utils.cpp +++ b/relational_store/frameworks/js/napi/common/mock/src/js_utils.cpp @@ -102,6 +102,10 @@ int32_t JSUtils::Convert2StrVector(napi_env env, napi_value value, std::vector +#include + +#include "js_logger.h" +#include "js_utils.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "napi_rdb_error.h" + + +namespace OHOS { +namespace AppDataMgrJsKit { + +class AsyncCall final { +public: + class Context { + public: + int apiversion; + std::shared_ptr error; + napi_env _env = nullptr; + void *boundObj = nullptr; + 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)); + } + + void SetError(std::shared_ptr err) + { + error = err; + } + + // input function + virtual int operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) + { + if (input_ == nullptr) { + return OK; + } + return input_(env, argc, argv, self); + } + + // output function + virtual int operator()(napi_env env, napi_value &result) + { + if (output_ == nullptr) { + result = nullptr; + return OK; + } + return output_(env, result); + } + + // execute function + virtual void Exec() + { + if (exec_ == nullptr) { + return; + } + 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); + static void SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr error, int apiversion); + + AsyncContext *context_ = nullptr; + napi_env env_ = nullptr; +}; +} // namespace AppDataMgrJsKit +} // namespace OHOS +#endif diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h new file mode 100644 index 0000000000000000000000000000000000000000..3a1910dda8c9f6f2bcc137b9538367d3234a3dbb --- /dev/null +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h @@ -0,0 +1,192 @@ +/* + * 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 RDB_JS_NAPI_ERROR_H +#define RDB_JS_NAPI_ERROR_H + +#include "js_logger.h" + +namespace OHOS { +namespace AppDataMgrJsKit { +constexpr int MAX_INPUT_COUNT = 10; +constexpr int OK = 0; +constexpr int ERR = -1; +constexpr int APIVERSION_V9 = 9; +constexpr int APIVERSION_V8 = 8; + +constexpr int E_PARAM_ERROR = 401; + +constexpr int E_INNER_ERROR = 14800000; + +constexpr int E_DB_INVALID = 14800010; +constexpr int E_DB_CORRUPTED = 14800011; +constexpr int E_RESULT_GET_ERROR = 14800013; +constexpr int E_RESULT_GOTO_ERROR = 14800012; + +#define RDB_NAPI_ASSERT_BASE_FROMV9(env, assertion, error, retVal, version) \ + do { \ + if (!(assertion)) { \ + if ((error) == nullptr) { \ + LOG_ERROR("throw error: error message is empty,version= %{public}d", version); \ + napi_throw_error((env), nullptr, "error message is empty"); \ + return retVal; \ + } \ + if (((version) > (APIVERSION_V8)) || ((error->GetCode()) == (401))) { \ + LOG_ERROR("throw error: code = %{public}d , message = %{public}s, version= %{public}d", \ + error->GetCode(), error->GetMessage().c_str(), version); \ + napi_throw_error((env), std::to_string(error->GetCode()).c_str(), error->GetMessage().c_str()); \ + return retVal; \ + } \ + LOG_ERROR("nothrow error: code = %{public}d , message = %{public}s, version= %{public}d", \ + error->GetCode(), error->GetMessage().c_str(), version); \ + } \ + } while (0) + +#define RDB_NAPI_ASSERT_FROMV9(env, assertion, error, version) \ + RDB_NAPI_ASSERT_BASE_FROMV9(env, assertion, error, nullptr, version) + +#define RDB_NAPI_ASSERT_RETURN_VOID_FROMV9(env, assertion, error, version) \ + RDB_NAPI_ASSERT_BASE_FROMV9(env, assertion, error, NAPI_RETVAL_NOTHING, version) + +#define RDB_ASYNC_PARAM_CHECK_FUNCTION(theCall) \ + do { \ + int err = (theCall); \ + if (err != OK) { \ + return err; \ + } \ + } while (0) + +#define RDB_CHECK_RETURN_NULLPTR(assertion) \ + do { \ + if (!(assertion)) { \ + return nullptr; \ + } \ + } while (0) + +#define RDB_CHECK_RETURN_CALL_RESULT(assertion, theCall) \ + do { \ + if (!(assertion)) { \ + (theCall); \ + return ERR; \ + } \ + } while (0) + +class Error { +public: + virtual ~Error(){}; + virtual std::string GetMessage() = 0; + virtual int GetCode() = 0; +}; + +class InnerError : public Error { +public: + InnerError() = default; + std::string GetMessage() override + { + return "System error."; + }; + int GetCode() override + { + return E_INNER_ERROR; + }; +}; + +class ParamTypeError : public Error { +public: + ParamTypeError(const std::string &name, const std::string &wantType) : name(name), wantType(wantType){}; + std::string GetMessage() override + { + return "Parameter error. The type of '" + name + "' must be " + wantType; + }; + int GetCode() override + { + return E_PARAM_ERROR; + }; + +private: + std::string name; + std::string wantType; +}; + +class ParamNumError : public Error { +public: + ParamNumError(const std::string &wantNum) : wantNum(wantNum){}; + std::string GetMessage() override + { + return "Parameter error. Need " + wantNum + " parameters!"; + }; + int GetCode() override + { + return E_PARAM_ERROR; + }; + +private: + std::string wantNum; +}; + +class DbInvalidError : public Error { +public: + DbInvalidError() = default; + std::string GetMessage() override + { + return "Failed open database, invalid database name."; + }; + int GetCode() override + { + return E_DB_INVALID; + }; +}; + +class DbCorruptedError : public Error { +public: + DbCorruptedError() = default; + std::string GetMessage() override + { + return "Failed open database, database corrupted."; + }; + int GetCode() override + { + return E_DB_CORRUPTED; + }; +}; + +class ResultGetError : public Error { +public: + ResultGetError() = default; + std::string GetMessage() override + { + return "The column value is null or the column type is incompatible."; + }; + int GetCode() override + { + return E_RESULT_GET_ERROR; + }; +}; + +class ResultGotoError : public Error { +public: + ResultGotoError() = default; + std::string GetMessage() override + { + return "The result set is empty or the specified location is invalid."; + }; + int GetCode() override + { + return E_RESULT_GOTO_ERROR; + }; +}; +} // namespace AppDataMgrJsKit +} // namespace OHOS + +#endif // RDB_JS_NAPI_ERROR_H diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h index 530d5d0b5918d0863442e4b2bb50c28bb30ddee1..4c0c915035ac373d86e9448c884f66028ed4a22b 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -21,6 +21,7 @@ #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" +#include "napi_rdb_error.h" #include "rdb_predicates.h" namespace OHOS { @@ -28,18 +29,35 @@ namespace RdbJsKit { class RdbPredicatesProxy { public: static void Init(napi_env env, napi_value exports); - static napi_value NewInstance(napi_env env, std::shared_ptr value); + static napi_value NewInstance( + napi_env env, std::shared_ptr value, int version = AppDataMgrJsKit::APIVERSION_V8); static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); explicit RdbPredicatesProxy(std::string &tableName); std::shared_ptr GetPredicates() const; - + int apiversion = AppDataMgrJsKit::APIVERSION_V8; + private: ~RdbPredicatesProxy(); static napi_value New(napi_env env, napi_callback_info info); + static napi_value NewV9(napi_env env, napi_callback_info info); + static napi_value InnerNew(napi_env env, napi_callback_info info, int version = AppDataMgrJsKit::APIVERSION_V8); static std::shared_ptr GetNativePredicates(napi_env env, napi_callback_info info); + static RdbPredicatesProxy *ParseFieldArrayByName(napi_env env, napi_callback_info info, napi_value &thiz, + std::vector &fieldarray, const std::string fieldName, const std::string fieldType); + static RdbPredicatesProxy *ParseFieldByName( + napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, const std::string fieldName); + static RdbPredicatesProxy *ParseInt32FieldByName( + napi_env env, napi_callback_info info, napi_value &thiz, int32_t &field, const std::string fieldName); + static RdbPredicatesProxy *ParseFieldAndValueArray(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, std::vector &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, std::string &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldLowAndHigh(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, std::string &low, std::string &High); + 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); diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h index 965bee9c01f6c2f5de524d97483e55b29cd20295..a675adb7fe01e263c561b2801645ffb28c49a952 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h @@ -18,12 +18,13 @@ #include #include + #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" - -#include "rdb_helper.h" +#include "napi_rdb_error.h" #include "napi_rdb_store_observer.h" +#include "rdb_helper.h" #include "rdb_types.h" namespace OHOS { @@ -31,14 +32,19 @@ namespace RdbJsKit { class RdbStoreProxy { public: static void Init(napi_env env, napi_value exports); - static napi_value NewInstance(napi_env env, std::shared_ptr value); + static napi_value NewInstance( + napi_env env, std::shared_ptr value, int version = AppDataMgrJsKit::APIVERSION_V8); static RdbStoreProxy *GetNativeInstance(napi_env env, napi_value self); void Release(napi_env env); RdbStoreProxy(); ~RdbStoreProxy(); + int apiversion = AppDataMgrJsKit::APIVERSION_V8; private: + static napi_value InnerInitialize( + napi_env env, napi_callback_info info, int version = AppDataMgrJsKit::APIVERSION_V8); static napi_value Initialize(napi_env env, napi_callback_info info); + static napi_value InitializeV9(napi_env env, napi_callback_info info); static napi_value Delete(napi_env env, napi_callback_info info); static napi_value Update(napi_env env, napi_callback_info info); static napi_value Insert(napi_env env, napi_callback_info info); @@ -75,8 +81,8 @@ private: static constexpr int MIN_ON_EVENT_ARG_NUM = 2; static constexpr int MAX_ON_EVENT_ARG_NUM = 5; - void OnDataChangeEvent(napi_env env, size_t argc, napi_value* argv); - void OffDataChangeEvent(napi_env env, size_t argc, napi_value* argv); + void OnDataChangeEvent(napi_env env, size_t argc, napi_value *argv); + void OffDataChangeEvent(napi_env env, size_t argc, napi_value *argv); std::mutex mutex_; std::shared_ptr rdbStore_; diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h index 4900d1d83bca5f75271d8a759fcdbc3d1fa3263a..cab34be93f340347e35160d9b54cf9d9696ee2e3 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -16,6 +16,7 @@ #ifndef RDB_JSKIT_NAPI_RDB_STORE_HELPER_H #define RDB_JSKIT_NAPI_RDB_STORE_HELPER_H +#include #include #include diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h b/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h index 7c92d9c19acfdfb3afaf96dd39d8052f22af2e56..8bb74d7f7c9d46dae8589ba029c3447278ea72a6 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -17,10 +17,12 @@ #define RDB_JSKIT_NAPI_RESULT_SET_H #include + #include "abs_shared_result_set.h" #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" +#include "napi_rdb_error.h" #include "result_set_bridge.h" namespace OHOS { @@ -31,16 +33,27 @@ public: ~ResultSetProxy(); ResultSetProxy(std::shared_ptr resultSet); ResultSetProxy &operator=(std::shared_ptr resultSet); - static napi_value NewInstance(napi_env env, 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); + static napi_value NewInstance(napi_env env, std::shared_ptr resultSet, + int version = AppDataMgrJsKit::APIVERSION_V8); + static napi_value NewInstance( + napi_env env, std::shared_ptr resultSet, int version = AppDataMgrJsKit::APIVERSION_V8); + static std::shared_ptr GetNativeObject(const napi_env &env, const napi_value &arg); + static napi_value GetConstructor(napi_env env, int version); std::shared_ptr Create() override; + int apiversion = AppDataMgrJsKit::APIVERSION_V8; private: - static std::shared_ptr &GetInnerResultSet(napi_env env, napi_callback_info info); + static std::shared_ptr &GetInnerResultSet( + napi_env env, napi_callback_info info, int &version); + static ResultSetProxy *ParseInt32FieldByName( + napi_env env, napi_callback_info info, int32_t &field, const std::string fieldName); + static ResultSetProxy *ParseFieldByName( + napi_env env, napi_callback_info info, std::string &field, const std::string fieldName); + + static napi_value InnerInitialize( + napi_env env, napi_callback_info info, int version = AppDataMgrJsKit::APIVERSION_V8); static napi_value Initialize(napi_env env, napi_callback_info info); + static napi_value InitializeV9(napi_env env, napi_callback_info info); static napi_value GetAllColumnNames(napi_env env, napi_callback_info info); static napi_value GoToRow(napi_env env, napi_callback_info info); static napi_value GetColumnCount(napi_env env, napi_callback_info info); diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h index 160a99fe1cd0ba0510e3f554386a3f0a95bdf136..af8575e74bdf14d013389ee074a23ab02a6d3039 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h @@ -21,6 +21,7 @@ #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" +#include "napi_rdb_error.h" #include "rdb_predicates.h" namespace OHOS { @@ -28,18 +29,35 @@ namespace RdbJsKit { class RdbPredicatesProxy { public: static void Init(napi_env env, napi_value exports); - static napi_value NewInstance(napi_env env, std::shared_ptr value); + static napi_value NewInstance( + napi_env env, std::shared_ptr value, int version = AppDataMgrJsKit::APIVERSION_V8); static void Destructor(napi_env env, void *nativeObject, void *finalize_hint); explicit RdbPredicatesProxy(std::string &tableName); std::shared_ptr GetPredicates() const; - + int apiversion = AppDataMgrJsKit::APIVERSION_V8; + private: ~RdbPredicatesProxy(); static napi_value New(napi_env env, napi_callback_info info); + static napi_value NewV9(napi_env env, napi_callback_info info); + static napi_value InnerNew(napi_env env, napi_callback_info info, int version = AppDataMgrJsKit::APIVERSION_V8); static std::shared_ptr GetNativePredicates(napi_env env, napi_callback_info info); + static RdbPredicatesProxy *ParseFieldArrayByName(napi_env env, napi_callback_info info, napi_value &thiz, + std::vector &fieldarray, const std::string fieldName, const std::string fieldType); + static RdbPredicatesProxy *ParseFieldByName( + napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, const std::string fieldName); + static RdbPredicatesProxy *ParseInt32FieldByName( + napi_env env, napi_callback_info info, napi_value &thiz, int32_t &field, const std::string fieldName); + static RdbPredicatesProxy *ParseFieldAndValueArray(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, std::vector &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, std::string &value, const std::string valueType); + static RdbPredicatesProxy *ParseFieldLowAndHigh(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, std::string &low, std::string &High); + 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); diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h index 699b8a5b30b4093381ae78d07045b476a6a148e1..8c3e150605b12037a5438306c6dab081d0047da9 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h @@ -18,10 +18,11 @@ #include #include + #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" - +#include "napi_rdb_error.h" #include "rdb_helper.h" namespace OHOS { @@ -29,14 +30,19 @@ namespace RdbJsKit { class RdbStoreProxy { public: static void Init(napi_env env, napi_value exports); - static napi_value NewInstance(napi_env env, std::shared_ptr value); + static napi_value NewInstance( + napi_env env, std::shared_ptr value, int version = AppDataMgrJsKit::APIVERSION_V8); static RdbStoreProxy *GetNativeInstance(napi_env env, napi_value self); void Release(napi_env env); RdbStoreProxy(); ~RdbStoreProxy(); + int apiversion = AppDataMgrJsKit::APIVERSION_V8; private: + static napi_value InnerInitialize( + napi_env env, napi_callback_info info, int version = AppDataMgrJsKit::APIVERSION_V8); static napi_value Initialize(napi_env env, napi_callback_info info); + static napi_value InitializeV9(napi_env env, napi_callback_info info); static napi_value Delete(napi_env env, napi_callback_info info); static napi_value Update(napi_env env, napi_callback_info info); static napi_value Insert(napi_env env, napi_callback_info info); diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h index 3f4208e37cfe8da735f2aa2a894aab0d309641e6..d5bdcf1c54c0b5e9c776fdbab34c40f9708842d8 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h @@ -31,12 +31,20 @@ public: ~ResultSetProxy(); ResultSetProxy(std::shared_ptr resultSet); ResultSetProxy &operator=(std::shared_ptr resultSet); - static napi_value NewInstance(napi_env env, std::shared_ptr resultSet); - static napi_value GetConstructor(napi_env env); + static napi_value NewInstance(napi_env env, std::shared_ptr resultSet, int version = AppDataMgrJsKit::APIVERSION_V8); + static napi_value GetConstructor(napi_env env, int version); + int apiversion = AppDataMgrJsKit::APIVERSION_V8; private: - static std::shared_ptr &GetInnerResultSet(napi_env env, napi_callback_info info); + static std::shared_ptr &GetInnerResultSet(napi_env env, napi_callback_info info, int &version); + static ResultSetProxy *ParseInt32FieldByName( + napi_env env, napi_callback_info info, int32_t &field, const std::string fieldName); + static ResultSetProxy *ParseFieldByName( + napi_env env, napi_callback_info info, std::string &field, const std::string fieldName); + + static napi_value InnerInitialize(napi_env env, napi_callback_info info, int version = AppDataMgrJsKit::APIVERSION_V8); static napi_value Initialize(napi_env env, napi_callback_info info); + static napi_value InitializeV9(napi_env env, napi_callback_info info); static napi_value GetAllColumnNames(napi_env env, napi_callback_info info); static napi_value GoToRow(napi_env env, napi_callback_info info); static napi_value GetColumnCount(napi_env env, napi_callback_info info); diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_async_call.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_async_call.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ca526c0eaa9a2ac0ade1de95269f95e4fc5d8f3 --- /dev/null +++ b/relational_store/frameworks/js/napi/rdb/src/napi_async_call.cpp @@ -0,0 +1,179 @@ +/* + * 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_logger.h" +#include "napi_async_call.h" + +namespace OHOS { +namespace AppDataMgrJsKit { +AsyncCall::AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr context) : env_(env) +{ + context->_env = env; + size_t argc = MAX_INPUT_COUNT; + napi_value self = nullptr; + napi_value argv[MAX_INPUT_COUNT] = { nullptr }; + NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); + + context_ = new AsyncContext(); + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[argc - 1], &valueType); + if (valueType == napi_function) { + LOG_DEBUG("asyncCall set callback"); + NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, argv[argc - 1], 1, &context_->callback)); + argc = argc - 1; + } + // int -->input_(env, argc, argv, self) + int status = (*context)(env, argc, argv, self); + // if input return is not ok, then napi_throw_error context error + RDB_NAPI_ASSERT_RETURN_VOID_FROMV9(env, status == OK, context->error, context->apiversion); + 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 input throw error , then context_->ctx is nullptr, then return nullptr, worker stop; + if ((context_ == nullptr) || (context_->ctx == nullptr)) { + LOG_DEBUG("context_ or context_->ctx is null"); + return nullptr; + } + LOG_DEBUG("async call exec begin"); + 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); + // create async work, execute function is OnExecute, complete function is OnComplete + napi_create_async_work(env, nullptr, resource, AsyncCall::OnExecute, AsyncCall::OnComplete, context_, &work); + context_->work = work; + context_ = nullptr; + // add async work to execute queue + napi_queue_async_work(env, work); + LOG_DEBUG("async call exec end"); + return promise; +} + +// sync call, no used. +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::SetBusinessError(napi_env env, napi_value *businessError, std::shared_ptr error, int apiversion) +{ + napi_value code = nullptr; + napi_value msg = nullptr; + napi_create_object(env, businessError); + if (apiversion < APIVERSION_V9) { + napi_create_string_utf8(env, "async error.", NAPI_AUTO_LENGTH, &msg); + napi_set_named_property(env, *businessError, "message", msg); + return; + } + // if error is not inner error + if (error != nullptr && error->GetCode() != E_INNER_ERROR) { + napi_create_int32(env, error->GetCode(), &code); + napi_create_string_utf8(env, error->GetMessage().c_str(), NAPI_AUTO_LENGTH, &msg); + napi_set_named_property(env, *businessError, "code", code); + napi_set_named_property(env, *businessError, "message", msg); + } +} + +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; + int outStatus = ERR; + // if async execute status is not napi_ok then un-execute out function + if (status == napi_ok) { + outStatus = (*context->ctx)(env, output); + } + napi_value result[ARG_BUTT] = { 0 }; + // if out function status is ok then async renturn output data, else return error. + if (outStatus == 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 businessError = nullptr; + SetBusinessError(env, &businessError, context->ctx->error, context->ctx->apiversion); + result[ARG_ERROR] = businessError; + napi_get_undefined(env, &result[ARG_DATA]); + } + if (context->defer != nullptr) { + // promise + if (status == napi_ok && outStatus == 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; +} +} // namespace AppDataMgrJsKit +} // namespace OHOS \ No newline at end of file diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp index defa27ef9bcf9e1acaec17a9223965f7b0c21deb..068a0c0a20cc591d1ea25b8f17b9a5f5661c6f7d 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_const_properties.cpp @@ -20,7 +20,6 @@ using OHOS::DistributedRdb::SyncMode; using OHOS::DistributedRdb::SubscribeMode; -using OHOS::NativeRdb::DatabaseFileSecurityLevel; #endif namespace OHOS::RdbJsKit { @@ -64,10 +63,10 @@ static napi_value ExportSecurityLevel(napi_env env) napi_value securityLevel = nullptr; napi_create_object(env, &securityLevel); - for (int32_t i = 1; i < static_cast(DatabaseFileSecurityLevel::LAST); i++) { - (void)SetNamedProperty(env, securityLevel, NativeRdb::DatabaseFileSecurityLabel[i], - static_cast(static_cast(i))); - } + (void) SetNamedProperty(env, securityLevel, "S1", (int32_t)NativeRdb::SecurityLevel::S1); + (void) SetNamedProperty(env, securityLevel, "S2", (int32_t)NativeRdb::SecurityLevel::S2); + (void) SetNamedProperty(env, securityLevel, "S3", (int32_t)NativeRdb::SecurityLevel::S3); + (void) SetNamedProperty(env, securityLevel, "S4", (int32_t)NativeRdb::SecurityLevel::S4); napi_object_freeze(env, securityLevel); return securityLevel; } diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp index da6b17fcee66cb775ad2265bf65f6591fb81a951..f0d52ba1cc7c0ecea41834f6a1a7b1577c4dfc01 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_predicates.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,10 +13,10 @@ * limitations under the License. */ -#include "napi_rdb_predicates.h" - #include "js_logger.h" #include "js_utils.h" +#include "napi_rdb_error.h" +#include "napi_rdb_predicates.h" using namespace OHOS::NativeRdb; using namespace OHOS::AppDataMgrJsKit; @@ -85,17 +85,34 @@ void RdbPredicatesProxy::Init(napi_env env, napi_value exports) napi_value cons; NAPI_CALL_RETURN_VOID(env, napi_define_class(env, "RdbPredicates", NAPI_AUTO_LENGTH, New, nullptr, sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons)); - NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, cons, 1, &constructor_)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, exports, "RdbPredicates", cons)); SetGlobalNamedProperty(env, "RdbPredicatesConstructor", cons); + + napi_value consV9; + NAPI_CALL_RETURN_VOID(env, napi_define_class(env, "RdbPredicatesV9", NAPI_AUTO_LENGTH, NewV9, nullptr, + sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &consV9)); + NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, consV9, 1, &constructor_)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, exports, "RdbPredicatesV9", consV9)); + + SetGlobalNamedProperty(env, "RdbPredicatesConstructorV9", consV9); LOG_DEBUG("RdbPredicatesProxy::Init end"); } napi_value RdbPredicatesProxy::New(napi_env env, napi_callback_info info) { + return InnerNew(env, info, APIVERSION_V8); +} + +napi_value RdbPredicatesProxy::NewV9(napi_env env, napi_callback_info info) +{ + return InnerNew(env, info, APIVERSION_V9); +} + +napi_value RdbPredicatesProxy::InnerNew(napi_env env, napi_callback_info info, int version) +{ + LOG_DEBUG("RdbPredicatesProxy::New begin."); napi_value new_target; NAPI_CALL(env, napi_get_new_target(env, info, &new_target)); bool is_constructor = (new_target != nullptr); @@ -108,8 +125,11 @@ napi_value RdbPredicatesProxy::New(napi_env env, napi_callback_info info) if (is_constructor) { napi_valuetype valueType; NAPI_CALL(env, napi_typeof(env, args[0], &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "Table name should be a string."); + RDB_NAPI_ASSERT_FROMV9( + env, valueType == napi_string, std::make_shared("name", "a non empty string."), version); std::string tableName = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT_FROMV9( + env, !tableName.empty(), std::make_shared("name", "a non empty string."), version); auto *proxy = new RdbPredicatesProxy(tableName); proxy->env_ = env; NAPI_CALL(env, napi_wrap(env, thiz, proxy, RdbPredicatesProxy::Destructor, nullptr, &proxy->wrapper_)); @@ -129,15 +149,15 @@ napi_value RdbPredicatesProxy::New(napi_env env, napi_callback_info info) return output; } -napi_value RdbPredicatesProxy::NewInstance(napi_env env, std::shared_ptr value) +napi_value RdbPredicatesProxy::NewInstance(napi_env env, std::shared_ptr value, int version) { + LOG_DEBUG("RdbPredicatesProxy::NewInstance begin."); napi_value cons; napi_status status = napi_get_reference_value(env, constructor_, &cons); if (status != napi_ok) { LOG_ERROR("RdbPredicatesProxy::NewInstance get constructor failed! napi_status:%{public}d!", status); return nullptr; } - size_t argc = 1; napi_value args[1] = { JSUtils::Convert2JSValue(env, value->GetTableName()) }; napi_value instance = nullptr; @@ -154,6 +174,7 @@ napi_value RdbPredicatesProxy::NewInstance(napi_env env, std::shared_ptrpredicates_ = std::move(value); + proxy->apiversion = APIVERSION_V8; LOG_DEBUG("RdbPredicatesProxy::NewInstance end"); return instance; } @@ -177,537 +198,592 @@ RdbPredicatesProxy::RdbPredicatesProxy(std::string &tableName) std::shared_ptr RdbPredicatesProxy::GetNativePredicates(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::GetNativePredicates begin."); RdbPredicatesProxy *predicatesProxy = nullptr; napi_value thiz; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); - LOG_DEBUG("RdbPredicatesProxy::GetNativePredicates end"); return predicatesProxy->predicates_; } -napi_value RdbPredicatesProxy::EqualTo(napi_env env, napi_callback_info info) +RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldArrayByName(napi_env env, napi_callback_info info, napi_value &thiz, + std::vector &fieldarray, const std::string fieldName, const std::string fieldType) +{ + size_t argc = 1; + napi_value args[1] = { nullptr }; + napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); + RdbPredicatesProxy *predicatesProxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); + int version = predicatesProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), version); + + fieldarray = JSUtils::Convert2StrVector(env, args[0]); + RDB_NAPI_ASSERT_FROMV9(env, fieldarray.size() >= 0, + std::make_shared(fieldName, "a " + fieldType + " array."), version); + return predicatesProxy; +} + +RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldByName( + napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, const std::string fieldName) +{ + size_t argc = 1; + napi_value args[1] = { 0 }; + napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); + RdbPredicatesProxy *predicatesProxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); + int version = predicatesProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), version); + + field = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), + std::make_shared(fieldName, "a non empty string."), version); + return predicatesProxy; +} + +RdbPredicatesProxy *RdbPredicatesProxy::ParseInt32FieldByName( + napi_env env, napi_callback_info info, napi_value &thiz, int32_t &field, const std::string fieldName) +{ + size_t argc = 1; + napi_value args[1] = { 0 }; + napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); + RdbPredicatesProxy *predicatesProxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); + int version = predicatesProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), version); + + napi_status status = napi_get_value_int32(env, args[0], &field); + RDB_NAPI_ASSERT_FROMV9(env, status == napi_ok, + std::make_shared(fieldName, "a number."), version); + return predicatesProxy; +} + +RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValueArray(napi_env env, napi_callback_info info, + napi_value &thiz, std::string &field, std::vector &value, const std::string valueType) { - napi_value thiz; size_t argc = 2; napi_value args[2] = { 0 }; napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc > 0, "RdbPredicatesProxy::EqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->EqualTo(field, value); - LOG_DEBUG("RdbPredicatesProxy::EqualTo end"); - return thiz; + RdbPredicatesProxy *predicatesProxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); + int version = predicatesProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 2, std::make_shared("2"), version); + + field = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), + std::make_shared("field", "a non empty string."), version); + + value = JSUtils::Convert2StrVector(env, args[1]); + RDB_NAPI_ASSERT_FROMV9(env, value.size() >= 0, + std::make_shared("value", "a " + valueType + " array."), version); + return predicatesProxy; } -napi_value RdbPredicatesProxy::NotEqualTo(napi_env env, napi_callback_info info) +RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValue(napi_env env, napi_callback_info info, napi_value &thiz, + std::string &field, std::string &value, const std::string valueType) { - 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 > 0, "RdbPredicatesProxy::NotEqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->NotEqualTo(field, value); - LOG_DEBUG("RdbPredicatesProxy::NotEqualTo end"); + RdbPredicatesProxy *predicatesProxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); + int version = predicatesProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 2, std::make_shared("2"), version); + + field = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), + std::make_shared("field", "a non empty string."), version); + + value = JSUtils::ConvertAny2String(env, args[1]); + return predicatesProxy; +} + +RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldLowAndHigh( + napi_env env, napi_callback_info info, napi_value &thiz, std::string &field, std::string &low, std::string &high) +{ + size_t argc = 3; + napi_value args[3] = { 0 }; + napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); + RdbPredicatesProxy *predicatesProxy = nullptr; + napi_unwrap(env, thiz, reinterpret_cast(&predicatesProxy)); + int version = predicatesProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 3, std::make_shared("3"), version); + + field = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), + std::make_shared("field", "a non empty string."), version); + + low = JSUtils::ConvertAny2String(env, args[1]); + RDB_NAPI_ASSERT_FROMV9(env, !low.empty(), + std::make_shared("low", "a non empty ValueType."), version); + + high = JSUtils::ConvertAny2String(env, args[2]); + RDB_NAPI_ASSERT_FROMV9(env, !high.empty(), + std::make_shared("high", "a non empty ValueType."), version); + + LOG_DEBUG("Check field, low and high ok"); + return predicatesProxy; +} + +napi_value RdbPredicatesProxy::EqualTo(napi_env env, napi_callback_info info) +{ + LOG_DEBUG("RdbPredicatesProxy::EqualTo begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->EqualTo(field, value); + return thiz; +} + +napi_value RdbPredicatesProxy::NotEqualTo(napi_env env, napi_callback_info info) +{ + LOG_DEBUG("RdbPredicatesProxy::NotEqualTo begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->NotEqualTo(field, value); return thiz; } napi_value RdbPredicatesProxy::BeginWrap(napi_env env, napi_callback_info info) { - napi_value thiz; + LOG_DEBUG("RdbPredicatesProxy::BeginWrap begin."); + napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); GetNativePredicates(env, info)->BeginWrap(); - LOG_DEBUG("RdbPredicatesProxy::BeginWrap end"); return thiz; } napi_value RdbPredicatesProxy::EndWrap(napi_env env, napi_callback_info info) { - napi_value thiz; + LOG_DEBUG("RdbPredicatesProxy::EndWrap begin."); + napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); GetNativePredicates(env, info)->EndWrap(); - LOG_DEBUG("RdbPredicatesProxy::EndWrap end"); return thiz; } napi_value RdbPredicatesProxy::Or(napi_env env, napi_callback_info info) { - napi_value thiz; + LOG_DEBUG("RdbPredicatesProxy::Or begin."); + napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); GetNativePredicates(env, info)->Or(); - LOG_DEBUG("RdbPredicatesProxy::Or end"); return thiz; } napi_value RdbPredicatesProxy::And(napi_env env, napi_callback_info info) { - napi_value thiz; + LOG_DEBUG("RdbPredicatesProxy::And begin."); + napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); GetNativePredicates(env, info)->And(); - LOG_DEBUG("RdbPredicatesProxy::And end"); return thiz; } napi_value RdbPredicatesProxy::Contains(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::Contains Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->Contains(field, value); - LOG_DEBUG("RdbPredicatesProxy::Contains end"); + LOG_DEBUG("RdbPredicatesProxyV9::Contains begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->Contains(field, value); return thiz; } napi_value RdbPredicatesProxy::BeginsWith(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::BeginsWith Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->BeginsWith(field, value); - LOG_DEBUG("RdbPredicatesProxy::BeginsWith end"); + LOG_DEBUG("RdbPredicatesProxy::BeginsWith begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->BeginsWith(field, value); return thiz; } napi_value RdbPredicatesProxy::EndsWith(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::EndsWith Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->EndsWith(field, value); - LOG_DEBUG("RdbPredicatesProxy::EndsWith end"); + LOG_DEBUG("RdbPredicatesProxy::EndsWith begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->EndsWith(field, value); return thiz; } napi_value RdbPredicatesProxy::IsNull(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::IsNull Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->IsNull(field); - LOG_DEBUG("RdbPredicatesProxy::IsNull end"); + LOG_DEBUG("RdbPredicatesProxy::IsNull begin."); + napi_value thiz = nullptr; + std::string field = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, field, "field"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->IsNull(field); return thiz; } napi_value RdbPredicatesProxy::IsNotNull(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::IsNotNull Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->IsNotNull(field); - LOG_DEBUG("RdbPredicatesProxy::IsNotNull end"); + LOG_DEBUG("RdbPredicatesProxy::IsNotNull begin."); + napi_value thiz = nullptr; + std::string field = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, field, "field"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->IsNotNull(field); return thiz; } napi_value RdbPredicatesProxy::Like(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::Like Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->Like(field, value); - LOG_DEBUG("RdbPredicatesProxy::Like end"); + LOG_DEBUG("RdbPredicatesProxy::Like begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->Like(field, value); return thiz; } napi_value RdbPredicatesProxy::Glob(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::Glob Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->Glob(field, value); - LOG_DEBUG("RdbPredicatesProxy::Glob end"); + LOG_DEBUG("RdbPredicatesProxy::Glob begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->Glob(field, value); return thiz; } napi_value RdbPredicatesProxy::Between(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::Between Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string low = JSUtils::ConvertAny2String(env, args[1]); - std::string high = JSUtils::ConvertAny2String(env, args[2]); - GetNativePredicates(env, info)->Between(field, low, high); - LOG_DEBUG("RdbPredicatesProxy::Between end"); + LOG_DEBUG("RdbPredicatesProxy::Between begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string low = ""; + std::string high = ""; + auto predicatesProxy = ParseFieldLowAndHigh(env, info, thiz, field, low, high); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->Between(field, low, high); return thiz; } napi_value RdbPredicatesProxy::NotBetween(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::NotBetween Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string low = JSUtils::ConvertAny2String(env, args[1]); - std::string high = JSUtils::ConvertAny2String(env, args[2]); - GetNativePredicates(env, info)->NotBetween(field, low, high); - LOG_DEBUG("RdbPredicatesProxy::NotBetween end"); + LOG_DEBUG("RdbPredicatesProxy::NotBetween begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string low = ""; + std::string high = ""; + auto predicatesProxy = ParseFieldLowAndHigh(env, info, thiz, field, low, high); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->NotBetween(field, low, high); return thiz; } napi_value RdbPredicatesProxy::GreaterThan(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::GreaterThan Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->GreaterThan(field, value); - LOG_DEBUG("RdbPredicatesProxy::GreaterThan end"); + LOG_DEBUG("RdbPredicatesProxy::GreaterThan begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->GreaterThan(field, value); return thiz; } napi_value RdbPredicatesProxy::LessThan(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::LessThan Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->LessThan(field, value); - LOG_DEBUG("RdbPredicatesProxy::LessThan end"); + LOG_DEBUG("RdbPredicatesProxy::LessThan begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + auto predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->LessThan(field, value); return thiz; } napi_value RdbPredicatesProxy::GreaterThanOrEqualTo(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::GreaterThanOrEqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->GreaterThanOrEqualTo(field, value); - LOG_DEBUG("RdbPredicatesProxy::GreaterThanOrEqualTo end"); + LOG_DEBUG("RdbPredicatesProxy::GreaterThanOrEqualTo begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + RdbPredicatesProxy *predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->GreaterThanOrEqualTo(field, value); return thiz; } napi_value RdbPredicatesProxy::LessThanOrEqualTo(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::LessThanOrEqualTo Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::string value = JSUtils::ConvertAny2String(env, args[1]); - GetNativePredicates(env, info)->LessThanOrEqualTo(field, value); - LOG_DEBUG("RdbPredicatesProxy::LessThanOrEqualTo end"); + LOG_DEBUG("RdbPredicatesProxy::LessThanOrEqualTo begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::string value = ""; + RdbPredicatesProxy *predicatesProxy = ParseFieldAndValue(env, info, thiz, field, value, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->LessThanOrEqualTo(field, value); return thiz; } napi_value RdbPredicatesProxy::OrderByAsc(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::OrderByAsc Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->OrderByAsc(field); - LOG_DEBUG("RdbPredicatesProxy::OrderByAsc end"); + LOG_DEBUG("RdbPredicatesProxy::OrderByAsc begin."); + napi_value thiz = nullptr; + std::string field = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, field, "field"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->OrderByAsc(field); return thiz; } napi_value RdbPredicatesProxy::OrderByDesc(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::OrderByDesc Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->OrderByDesc(field); - LOG_DEBUG("RdbPredicatesProxy::OrderByDesc end"); + LOG_DEBUG("RdbPredicatesProxy::OrderByDesc begin."); + napi_value thiz = nullptr; + std::string field = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, field, "field"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->OrderByDesc(field); return thiz; } napi_value RdbPredicatesProxy::Distinct(napi_env env, napi_callback_info info) { - napi_value thiz; + LOG_DEBUG("RdbPredicatesProxy::Distinct begin."); + napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); GetNativePredicates(env, info)->Distinct(); - LOG_DEBUG("RdbPredicatesProxy::Distinct end"); return thiz; } napi_value RdbPredicatesProxy::Limit(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::Limit Invalid argvs!"); + LOG_DEBUG("RdbPredicatesProxy::Limit begin."); + napi_value thiz = nullptr; int32_t limit = 0; - napi_get_value_int32(env, args[0], &limit); - GetNativePredicates(env, info)->Limit(limit); - LOG_DEBUG("RdbPredicatesProxy::Limit end"); + auto predicatesProxy = ParseInt32FieldByName(env, info, thiz, limit, "value"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->Limit(limit); return thiz; } napi_value RdbPredicatesProxy::Offset(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::Offset Invalid argvs!"); + LOG_DEBUG("RdbPredicatesProxy::Offset begin."); + napi_value thiz = nullptr; int32_t offset = 0; - napi_get_value_int32(env, args[0], &offset); - GetNativePredicates(env, info)->Offset(offset); - LOG_DEBUG("RdbPredicatesProxy::Offset end"); + auto predicatesProxy = ParseInt32FieldByName(env, info, thiz, offset, "rowOffset"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->Offset(offset); return thiz; } napi_value RdbPredicatesProxy::GroupBy(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::GroupBy Invalid argvs!"); - std::vector fields = JSUtils::Convert2StrVector(env, args[0]); - GetNativePredicates(env, info)->GroupBy(fields); - LOG_DEBUG("RdbPredicatesProxy::GroupBy end"); + LOG_DEBUG("RdbPredicatesProxy::GroupBy begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::vector fields; + auto predicatesProxy = ParseFieldArrayByName(env, info, thiz, fields, "fields", "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->GroupBy(fields); return thiz; } napi_value RdbPredicatesProxy::IndexedBy(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::IndexedBy Invalid argvs!"); - std::string indexName = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->IndexedBy(indexName); - LOG_DEBUG("RdbPredicatesProxy::IndexedBy end"); + LOG_DEBUG("RdbPredicatesProxy::IndexedBy begin."); + napi_value thiz = nullptr; + std::string indexName = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, indexName, "fields"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->IndexedBy(indexName); return thiz; } napi_value RdbPredicatesProxy::In(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::In Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::vector values = JSUtils::Convert2StrVector(env, args[1]); - GetNativePredicates(env, info)->In(field, values); - LOG_DEBUG("RdbPredicatesProxy::In end"); + LOG_DEBUG("RdbPredicatesProxy::In begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::vector values; + auto predicatesProxy = ParseFieldAndValueArray(env, info, thiz, field, values, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->In(field, values); return thiz; } napi_value RdbPredicatesProxy::NotIn(napi_env env, napi_callback_info info) { - 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 > 0, "RdbPredicatesProxy::NotIn Invalid argvs!"); - std::string field = JSUtils::Convert2String(env, args[0]); - std::vector values = JSUtils::Convert2StrVector(env, args[1]); - GetNativePredicates(env, info)->NotIn(field, values); - LOG_DEBUG("RdbPredicatesProxy::NotIn end"); + LOG_DEBUG("RdbPredicatesProxy::NotIn begin."); + napi_value thiz = nullptr; + std::string field = ""; + std::vector values; + auto predicatesProxy = ParseFieldAndValueArray(env, info, thiz, field, values, "ValueType"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->NotIn(field, values); return thiz; } napi_value RdbPredicatesProxy::Using(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::Using begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::Using Invalid argvs!"); - auto fields = JSUtils::Convert2StrVector(env, args[0]); - GetNativePredicates(env, info)->Using(fields); - LOG_DEBUG("RdbPredicatesProxy::Using end"); + std::vector fields; + auto predicatesProxy = ParseFieldArrayByName(env, info, thiz, fields, "fields", "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->Using(fields); return thiz; } napi_value RdbPredicatesProxy::LeftOuterJoin(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::LeftOuterJoin begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::LeftOuterJoin Invalid argvs!"); - std::string tablename = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->LeftOuterJoin(tablename); - LOG_DEBUG("RdbPredicatesProxy::LeftOuterJoin end"); + std::string tablename = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, tablename, "tablename"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->LeftOuterJoin(tablename); return thiz; } napi_value RdbPredicatesProxy::InnerJoin(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::InnerJoin begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::InnerJoin Invalid argvs!"); - std::string tablename = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->InnerJoin(tablename); - LOG_DEBUG("RdbPredicatesProxy::InnerJoin end"); + std::string tablename = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, tablename, "tablename"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->InnerJoin(tablename); return thiz; } napi_value RdbPredicatesProxy::On(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::On begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::On Invalid argvs!"); - auto clauses = JSUtils::Convert2StrVector(env, args[0]); - GetNativePredicates(env, info)->On(clauses); - LOG_DEBUG("RdbPredicatesProxy::On end"); + std::vector clauses; + auto predicatesProxy = ParseFieldArrayByName(env, info, thiz, clauses, "clauses", "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->On(clauses); return thiz; } napi_value RdbPredicatesProxy::Clear(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::Clear begin."); napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); GetNativePredicates(env, info)->Clear(); - LOG_DEBUG("RdbPredicatesProxy::Clear end"); return thiz; } napi_value RdbPredicatesProxy::CrossJoin(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::CrossJoin begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::CrossJoin Invalid argvs!"); - std::string tablename = JSUtils::Convert2String(env, args[0]); - GetNativePredicates(env, info)->CrossJoin(tablename); - LOG_DEBUG("RdbPredicatesProxy::CrossJoin end"); + std::string tablename = ""; + auto predicatesProxy = ParseFieldByName(env, info, thiz, tablename, "tablename"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->CrossJoin(tablename); return thiz; } napi_value RdbPredicatesProxy::GetJoinCount(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::GetJoinCount begin."); napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); int errCode = GetNativePredicates(env, info)->GetJoinCount(); - LOG_DEBUG("RdbPredicatesProxy::GetJoinCount end"); return JSUtils::Convert2JSValue(env, errCode); } napi_value RdbPredicatesProxy::SetJoinCount(napi_env env, napi_callback_info info) { - napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::SetJoinCount Invalid argvs!"); + LOG_DEBUG("RdbPredicatesProxy::SetJoinCount begin."); + napi_value thiz; int32_t joinCount = 0; - napi_get_value_int32(env, args[0], &joinCount); - GetNativePredicates(env, info)->SetJoinCount(joinCount); - LOG_DEBUG("RdbPredicatesProxy::SetJoinCount end"); + RdbPredicatesProxy *predicatesProxy = ParseInt32FieldByName(env, info, thiz, joinCount, "joinCount"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->SetJoinCount(joinCount); return thiz; } napi_value RdbPredicatesProxy::GetJoinTypes(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::GetJoinTypes begin."); napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); auto joinTypes = GetNativePredicates(env, info)->GetJoinTypes(); - LOG_DEBUG("RdbPredicatesProxy::GetJoinTypes end"); return JSUtils::Convert2JSValue(env, joinTypes); } napi_value RdbPredicatesProxy::GetJoinTableNames(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::GetJoinTableNames begin."); napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); auto joinTableNames = GetNativePredicates(env, info)->GetJoinTableNames(); - LOG_DEBUG("RdbPredicatesProxy::GetJoinTableNames end"); return JSUtils::Convert2JSValue(env, joinTableNames); + ; } napi_value RdbPredicatesProxy::GetJoinConditions(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::GetJoinConditions begin."); napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); auto joinConditions = GetNativePredicates(env, info)->GetJoinConditions(); - LOG_DEBUG("RdbPredicatesProxy::GetJoinConditions end"); return JSUtils::Convert2JSValue(env, joinConditions); + ; } napi_value RdbPredicatesProxy::SetJoinConditions(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::SetJoinConditions begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::SetJoinConditions Invalid argvs!"); - auto joinConditions = JSUtils::Convert2StrVector(env, args[0]); - GetNativePredicates(env, info)->SetJoinConditions(joinConditions); - LOG_DEBUG("RdbPredicatesProxy::SetJoinConditions end"); + std::vector joinConditions; + RdbPredicatesProxy *predicatesProxy = + ParseFieldArrayByName(env, info, thiz, joinConditions, "joinConditions", "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->SetJoinConditions(joinConditions); return thiz; } napi_value RdbPredicatesProxy::SetJoinTableNames(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::SetJoinTableNames begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::SetJoinTableNames Invalid argvs!"); - auto joinNames = JSUtils::Convert2StrVector(env, args[0]); - GetNativePredicates(env, info)->SetJoinTableNames(joinNames); - LOG_DEBUG("RdbPredicatesProxy::SetJoinTableNames end"); + std::vector joinNames; + RdbPredicatesProxy *predicatesProxy = ParseFieldArrayByName(env, info, thiz, joinNames, "joinNames", "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->SetJoinTableNames(joinNames); return thiz; } napi_value RdbPredicatesProxy::SetJoinTypes(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::SetJoinTypes begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { 0 }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::SetJoinTypes Invalid argvs!"); - auto joinTypes = JSUtils::Convert2StrVector(env, args[0]); - GetNativePredicates(env, info)->SetJoinTypes(joinTypes); - LOG_DEBUG("RdbPredicatesProxy::SetJoinTypes end"); + std::vector joinTypes; + RdbPredicatesProxy *predicatesProxy = ParseFieldArrayByName(env, info, thiz, joinTypes, "joinTypes", "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->SetJoinTypes(joinTypes); return thiz; } @@ -719,23 +795,21 @@ std::shared_ptr RdbPredicatesProxy::GetPredicates() co #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) napi_value RdbPredicatesProxy::InDevices(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::InDevices begin."); napi_value thiz = nullptr; - size_t argc = 1; - napi_value args[1] = { nullptr }; - napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); - NAPI_ASSERT(env, argc == 1, "RdbPredicatesProxy::InDevices Invalid args!"); - auto devices = JSUtils::Convert2StrVector(env, args[0]); - GetNativePredicates(env, info)->InDevices(devices); - LOG_DEBUG("RdbPredicatesProxy::InDevices end"); + std::vector devices; + RdbPredicatesProxy *predicatesProxy = ParseFieldArrayByName(env, info, thiz, devices, "devices", "string"); + RDB_CHECK_RETURN_NULLPTR(predicatesProxy != nullptr); + predicatesProxy->predicates_->InDevices(devices); return thiz; } napi_value RdbPredicatesProxy::InAllDevices(napi_env env, napi_callback_info info) { + LOG_DEBUG("RdbPredicatesProxy::InAllDevices begin."); napi_value thiz = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr); GetNativePredicates(env, info)->InAllDevices(); - LOG_DEBUG("RdbPredicatesProxy::InAllDevices end"); return thiz; } #endif diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp index 21181bd15d40e4e1b86da0715f020151136ec2c8..062bd3597fb9955ccf73d39984d718b865a5e385 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp @@ -13,14 +13,16 @@ * limitations under the License. */ -#include "napi_rdb_store.h" - #include +#include +#include #include "js_logger.h" #include "js_utils.h" -#include "napi_async_proxy.h" +#include "napi_async_call.h" +#include "napi_rdb_error.h" #include "napi_rdb_predicates.h" +#include "napi_rdb_store.h" #include "napi_result_set.h" #include "rdb_errno.h" #include "securec.h" @@ -47,23 +49,9 @@ struct PredicatesProxy { std::shared_ptr predicates_; }; #endif -class RdbStoreContext : public NapiAsyncProxy::AysncContext { -public: - RdbStoreContext() : AysncContext(), predicatesProxy(nullptr), valuesBucket(nullptr), rowId(0), enumArg(0) - { - valuesBucket = new ValuesBucket(); - } - - virtual ~RdbStoreContext() - { - auto *obj = reinterpret_cast(boundObj); - if (obj != nullptr) { - obj->Release(env); - } - delete valuesBucket; - } - - void BindArgs(napi_env env, napi_value arg); +struct RdbStoreContext : public AsyncCall::Context { + bool isNapiString = false; + int BindArgs(napi_env env, napi_value arg); std::string device; std::string tableName; std::vector tablesName; @@ -73,7 +61,7 @@ public: std::string sql; RdbPredicatesProxy *predicatesProxy; std::vector columns; - ValuesBucket *valuesBucket; + ValuesBucket valuesBucket; std::vector valuesBuckets; std::map numberMaps; std::vector bindArgs; @@ -94,17 +82,42 @@ public: DistributedRdb::SyncResult syncResult; #endif std::shared_ptr rdbPredicates = nullptr; + + RdbStoreContext() : Context(nullptr, nullptr), predicatesProxy(nullptr), rowId(0), enumArg(0) + { + } + RdbStoreContext(InputAction input, OutputAction output) + : Context(std::move(input), std::move(output)), predicatesProxy(nullptr), rowId(0), enumArg(0) + { + } + virtual ~RdbStoreContext() + { + auto *obj = reinterpret_cast(boundObj); + if (obj != nullptr) { + obj->Release(_env); + } + } + + int operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) override + { + return Context::operator()(env, argc, argv, self); + } + int operator()(napi_env env, napi_value &result) override + { + return Context::operator()(env, result); + } }; static __thread napi_ref constructor_ = nullptr; +static __thread napi_ref constructorV9_ = nullptr; -void RdbStoreContext::BindArgs(napi_env env, napi_value arg) +int RdbStoreContext::BindArgs(napi_env env, napi_value arg) { bindArgs.clear(); uint32_t arrLen = 0; napi_get_array_length(env, arg, &arrLen); if (arrLen == 0) { - return; + return OK; } for (size_t i = 0; i < arrLen; ++i) { napi_value element; @@ -113,19 +126,19 @@ void RdbStoreContext::BindArgs(napi_env env, napi_value arg) napi_typeof(env, element, &type); switch (type) { case napi_boolean: { - bool value = false; - napi_status status = napi_get_value_bool(env, element, &value); - if (status == napi_ok) { - bindArgs.push_back(ValueObject(value)); - } - } break; + bool value = false; + napi_status status = napi_get_value_bool(env, element, &value); + if (status == napi_ok) { + bindArgs.push_back(ValueObject(value)); + } + } break; case napi_number: { - double value; - napi_status status = napi_get_value_double(env, element, &value); - if (status == napi_ok) { - bindArgs.push_back(ValueObject(value)); - } - } break; + double value; + napi_status status = napi_get_value_double(env, element, &value); + if (status == napi_ok) { + bindArgs.push_back(ValueObject(value)); + } + } break; case napi_null: bindArgs.push_back(ValueObject()); break; @@ -139,6 +152,7 @@ void RdbStoreContext::BindArgs(napi_env env, napi_value arg) break; } } + return OK; } RdbStoreProxy::RdbStoreProxy() @@ -191,14 +205,18 @@ void RdbStoreProxy::Init(napi_env env, napi_value exports) #endif }; napi_value cons = nullptr; - napi_define_class(env, "RdbStore", NAPI_AUTO_LENGTH, Initialize, nullptr, - sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons); + NAPI_CALL_RETURN_VOID(env, napi_define_class(env, "RdbStore", NAPI_AUTO_LENGTH, Initialize, nullptr, + sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons)); + NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, cons, 1, &constructor_)); + + NAPI_CALL_RETURN_VOID(env, napi_define_class(env, "RdbStoreV9", NAPI_AUTO_LENGTH, InitializeV9, nullptr, + sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons)); + NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, cons, 1, &constructorV9_)); - napi_create_reference(env, cons, 1, &constructor_); LOG_DEBUG("Init RdbStoreProxy end"); } -napi_value RdbStoreProxy::Initialize(napi_env env, napi_callback_info info) +napi_value RdbStoreProxy::InnerInitialize(napi_env env, napi_callback_info info, int version) { napi_value self; NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &self, nullptr)); @@ -211,6 +229,7 @@ napi_value RdbStoreProxy::Initialize(napi_env env, napi_callback_info info) delete proxy; }; auto *proxy = new RdbStoreProxy(); + proxy->apiversion = version; napi_status status = napi_wrap(env, self, proxy, finalize, nullptr, &proxy->ref_); if (status != napi_ok) { LOG_ERROR("RdbStoreProxy::Initialize napi_wrap failed! code:%{public}d!", status); @@ -223,10 +242,26 @@ napi_value RdbStoreProxy::Initialize(napi_env env, napi_callback_info info) return self; } -napi_value RdbStoreProxy::NewInstance(napi_env env, std::shared_ptr value) +napi_value RdbStoreProxy::Initialize(napi_env env, napi_callback_info info) +{ + return InnerInitialize(env, info, APIVERSION_V8); +} + +napi_value RdbStoreProxy::InitializeV9(napi_env env, napi_callback_info info) +{ + return InnerInitialize(env, info, APIVERSION_V9); +} + +napi_value RdbStoreProxy::NewInstance(napi_env env, std::shared_ptr value, int version) { napi_value cons; - napi_status status = napi_get_reference_value(env, constructor_, &cons); + napi_status status; + if (version > APIVERSION_V8) { + status = napi_get_reference_value(env, constructorV9_, &cons); + } else { + status = napi_get_reference_value(env, constructor_, &cons); + } + if (status != napi_ok) { LOG_ERROR("RdbStoreProxy::NewInstance get constructor failed! code:%{public}d!", status); return nullptr; @@ -246,6 +281,7 @@ napi_value RdbStoreProxy::NewInstance(napi_env env, std::shared_ptrrdbStore_ = std::move(value); + proxy->apiversion = version; return instance; } @@ -281,36 +317,46 @@ void RdbStoreProxy::Release(napi_env env) } if (status != napi_ok) { - LOG_ERROR("RdbStoreProxy::Release napi_reference_unref failed! code:%{public}d!, count:%{public}u", - status, count); + LOG_ERROR( + "RdbStoreProxy::Release napi_reference_unref failed! code:%{public}d!, count:%{public}u", status, count); } } -void ParseThis(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +void ParserThis(const napi_env &env, const napi_value &self, std::shared_ptr context) { - asyncContext->boundObj = RdbStoreProxy::GetNativeInstance(env, arg); - LOG_DEBUG("ParseThis end"); + RdbStoreProxy *obj = RdbStoreProxy::GetNativeInstance(env, self); + context->apiversion = obj->apiversion; + context->boundObj = obj; + LOG_DEBUG("ParserThis RdbStoreProxy is v%{public}d", obj->apiversion); } -void ParseTableName(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseTableName(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->tableName = JSUtils::Convert2String(env, arg); + context->tableName = JSUtils::Convert2String(env, arg); + std::shared_ptr paramError = std::make_shared("table", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!context->tableName.empty(), context->SetError(paramError)); + LOG_DEBUG("ParseTableName end"); + return OK; } -void ParseDevice(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseDevice(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->device = JSUtils::Convert2String(env, arg); + context->device = JSUtils::Convert2String(env, arg); + std::shared_ptr paramError = std::make_shared("device", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!context->device.empty(), context->SetError(paramError)); + LOG_DEBUG("ParseDevice end"); + return OK; } -void ParseTablesName(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseTablesName(const napi_env &env, const napi_value &arg, std::shared_ptr context) { uint32_t arrLen = 0; napi_get_array_length(env, arg, &arrLen); - if (arrLen == 0) { - return; - } + std::shared_ptr paramError = std::make_shared("tables", "a string array."); + RDB_CHECK_RETURN_CALL_RESULT(arrLen >= 0, context->SetError(paramError)); + for (uint32_t i = 0; i < arrLen; ++i) { napi_value element; napi_get_element(env, arg, i, &element); @@ -318,122 +364,162 @@ void ParseTablesName(const napi_env &env, const napi_value &arg, RdbStoreContext napi_typeof(env, element, &type); if (type == napi_string) { std::string table = JSUtils::Convert2String(env, element); - asyncContext->tablesName.push_back(table); + context->tablesName.push_back(table); } } LOG_DEBUG("ParseTablesName end"); + return OK; } -void ParseEnumArg(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseSyncModeArg(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - napi_get_value_int32(env, arg, &asyncContext->enumArg); - LOG_DEBUG("ParseEnumArg end"); + napi_get_value_int32(env, arg, &context->enumArg); + std::shared_ptr paramError = std::make_shared("mode", "a SyncMode."); + RDB_CHECK_RETURN_CALL_RESULT(context->enumArg == 0 || context->enumArg == 1, context->SetError(paramError)); + + LOG_DEBUG("ParseSyncModeArg end"); + return OK; } -void ParsePredicates(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParsePredicates(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - bool result = false; napi_value global = nullptr; napi_status status = napi_get_global(env, &global); - NAPI_ASSERT_RETURN_VOID(env, status == napi_ok, "get napi global failed"); - napi_value rdbPredicatesConstructor = nullptr; - status = napi_get_named_property(env, global, "RdbPredicatesConstructor", &rdbPredicatesConstructor); - NAPI_ASSERT_RETURN_VOID(env, status == napi_ok, "get RdbPredicates constructor failed"); - status = napi_instanceof(env, arg, rdbPredicatesConstructor, &result); - if ((status == napi_ok) && (result != false)) { + std::shared_ptr paramError = std::make_shared("predicates", "an RdbPredicates."); + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok, context->SetError(paramError)); + + bool result = false; + napi_value RdbPredicatesConstructor = nullptr; + status = napi_get_named_property(env, global, "RdbPredicatesConstructor", &RdbPredicatesConstructor); + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok, context->SetError(paramError)); + status = napi_instanceof(env, arg, RdbPredicatesConstructor, &result); + + napi_value RdbPredicatesConstructorV9 = nullptr; + napi_status statusv9 = + napi_get_named_property(env, global, "RdbPredicatesConstructorV9", &RdbPredicatesConstructorV9); + RDB_CHECK_RETURN_CALL_RESULT(statusv9 == napi_ok, context->SetError(paramError)); + bool resultv9 = false; + statusv9 = napi_instanceof(env, arg, RdbPredicatesConstructorV9, &resultv9); + + LOG_DEBUG("Parse RDB Predicates status=%{public}d, result=%{public}d,statusv9=%{public}d, resultv9=%{public}d", + status, result, statusv9, resultv9); + if ((status == napi_ok && result != false) || (statusv9 == napi_ok && resultv9 != false)) { LOG_DEBUG("Parse RDB Predicates"); - napi_unwrap(env, arg, reinterpret_cast(&asyncContext->predicatesProxy)); - asyncContext->tableName = asyncContext->predicatesProxy->GetPredicates()->GetTableName(); - asyncContext->rdbPredicates = asyncContext->predicatesProxy->GetPredicates(); + napi_unwrap(env, arg, reinterpret_cast(&context->predicatesProxy)); + context->tableName = context->predicatesProxy->GetPredicates()->GetTableName(); + context->rdbPredicates = context->predicatesProxy->GetPredicates(); } else { LOG_DEBUG("Parse DataShare Predicates"); #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) PredicatesProxy *proxy = nullptr; napi_unwrap(env, arg, reinterpret_cast(&proxy)); std::shared_ptr dsPredicates = proxy->predicates_; - asyncContext->rdbPredicates = std::make_shared( - RdbDataShareAdapter::RdbUtils::ToPredicates(*dsPredicates, asyncContext->tableName)); + LOG_ERROR("dsPredicates is null ? %{public}d", (dsPredicates == nullptr)); + paramError = std::make_shared("predicates", "an DataShare Predicates."); + RDB_CHECK_RETURN_CALL_RESULT(dsPredicates != nullptr, context->SetError(paramError)); + context->rdbPredicates = std::make_shared( + RdbDataShareAdapter::RdbUtils::ToPredicates(*dsPredicates, context->tableName)); #endif } LOG_DEBUG("ParsePredicates end"); + return OK; } -void ParseNewKey(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseNewKey(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->newKey = JSUtils::Convert2U8Vector(env, arg); + context->newKey = JSUtils::Convert2U8Vector(env, arg); LOG_DEBUG("ParseNewKey end"); + return OK; } -void ParseDestName(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseSrcName(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->destName = JSUtils::Convert2String(env, arg); - LOG_DEBUG("DestName end"); -} + context->srcName = JSUtils::Convert2String(env, arg); + std::shared_ptr paramError = std::make_shared("srcName", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!context->srcName.empty(), context->SetError(paramError)); -void ParseSrcName(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) -{ - asyncContext->srcName = JSUtils::Convert2String(env, arg); LOG_DEBUG("ParseSrcName end"); + return OK; } -void ParseColumns(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseColumns(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->columns = JSUtils::Convert2StrVector(env, arg); + context->columns = JSUtils::Convert2StrVector(env, arg); LOG_DEBUG("ParseColumns end"); + return OK; } -void ParseWhereClause(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseWhereClause(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->whereClause = JSUtils::Convert2String(env, arg); + context->whereClause = JSUtils::Convert2String(env, arg); + std::shared_ptr paramError = std::make_shared("whereClause", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!context->whereClause.empty(), context->SetError(paramError)); + LOG_DEBUG("ParseWhereClause end"); + return OK; } -void ParseAlias(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseAlias(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->aliasName = JSUtils::Convert2String(env, arg); + context->aliasName = JSUtils::Convert2String(env, arg); + std::shared_ptr paramError = std::make_shared("aliasName", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!context->aliasName.empty(), context->SetError(paramError)); + LOG_DEBUG("ParseAlias end"); + return OK; } -void ParsePath(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParsePath(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->pathName = JSUtils::Convert2String(env, arg); + context->pathName = JSUtils::Convert2String(env, arg); + std::shared_ptr paramError = std::make_shared("pathName", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!context->pathName.empty(), context->SetError(paramError)); + LOG_DEBUG("ParsePath end"); + return OK; } -void ParseWhereArgs(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseWhereArgs(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->whereArgs = JSUtils::Convert2StrVector(env, arg); + context->whereArgs = JSUtils::Convert2StrVector(env, arg); LOG_DEBUG("ParseWhereArgs end"); + return OK; } -void ParseSelectionArgs(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseSelectionArgs(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->selectionArgs = JSUtils::Convert2StrVector(env, arg); + context->selectionArgs = JSUtils::Convert2StrVector(env, arg); LOG_DEBUG("ParseSelectionArgs end"); + return OK; } -void ParseSql(const napi_env &env, const napi_value &arg, RdbStoreContext *asyncContext) +int ParseSql(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - asyncContext->sql = JSUtils::Convert2String(env, arg, false); + context->sql = JSUtils::Convert2String(env, arg, false); + std::shared_ptr paramError = std::make_shared("sql", "a non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!context->sql.empty(), context->SetError(paramError)); + LOG_DEBUG("ParseSql end"); + return OK; } -void ParseValuesBucket(const napi_env &env, const napi_value &arg, RdbStoreContext *context) +int ParseValuesBucket(const napi_env &env, const napi_value &arg, std::shared_ptr context) { napi_value keys = 0; napi_get_property_names(env, arg, &keys); uint32_t arrLen = 0; napi_status status = napi_get_array_length(env, keys, &arrLen); - if (status != napi_ok) { - LOG_DEBUG("ValuesBucket errr"); - return; - } + std::shared_ptr paramError = std::make_shared("values", "a ValuesBucket."); + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok, context->SetError(paramError)); + for (size_t i = 0; i < arrLen; ++i) { napi_value key; status = napi_get_element(env, keys, i, &key); if (status != napi_ok) { LOG_DEBUG("ValuesBucket get_element errr"); } + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok, context->SetError(paramError)); + std::string keyStr = JSUtils::Convert2String(env, key); napi_value value; napi_get_property(env, arg, key, &value); @@ -441,54 +527,55 @@ void ParseValuesBucket(const napi_env &env, const napi_value &arg, RdbStoreConte napi_typeof(env, value, &valueType); if (valueType == napi_string) { std::string valueString = JSUtils::Convert2String(env, value, false); - context->valuesBucket->PutString(keyStr, valueString); + context->valuesBucket.PutString(keyStr, valueString); LOG_DEBUG("ValueObject type napi_string"); } else if (valueType == napi_number) { double valueNumber; napi_get_value_double(env, value, &valueNumber); - context->valuesBucket->PutDouble(keyStr, valueNumber); + context->valuesBucket.PutDouble(keyStr, valueNumber); LOG_DEBUG("ValueObject type napi_number"); } else if (valueType == napi_boolean) { bool valueBool = false; napi_get_value_bool(env, value, &valueBool); - context->valuesBucket->PutBool(keyStr, valueBool); + context->valuesBucket.PutBool(keyStr, valueBool); LOG_DEBUG("ValueObject type napi_boolean"); } else if (valueType == napi_null) { - context->valuesBucket->PutNull(keyStr); + context->valuesBucket.PutNull(keyStr); LOG_DEBUG("ValueObject type napi_null"); } else if (valueType == napi_object) { - context->valuesBucket->PutBlob(keyStr, JSUtils::Convert2U8Vector(env, value)); + context->valuesBucket.PutBlob(keyStr, JSUtils::Convert2U8Vector(env, value)); LOG_DEBUG("ValueObject type napi_object"); } else { LOG_WARN("valuesBucket error"); } } LOG_DEBUG("ParseValuesBucket end"); + return OK; } -void ParseValuesBuckets(const napi_env &env, const napi_value &arg, RdbStoreContext *context) +int ParseValuesBuckets(const napi_env &env, const napi_value &arg, std::shared_ptr context) { bool isArray = false; napi_is_array(env, arg, &isArray); + std::shared_ptr paramError = std::make_shared("values", "a ValuesBucket array."); if (!isArray) { context->insertNum = -1; - LOG_ERROR("input is not an array"); - return; + RDB_CHECK_RETURN_CALL_RESULT(isArray, context->SetError(paramError)); } uint32_t arrLen = 0; napi_status status = napi_get_array_length(env, arg, &arrLen); - if (status != napi_ok && arrLen < 0) { - LOG_ERROR("get array length error"); - return; - } + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok || arrLen >= 0, context->SetError(paramError)); + for (uint32_t i = 0; i < arrLen; ++i) { napi_value obj = nullptr; status = napi_get_element(env, arg, i, &obj); - NAPI_ASSERT_RETURN_VOID(env, status == napi_ok, "ParseValuesBuckets get element error."); + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok || arrLen >= 0, context->SetError(paramError)); + ParseValuesBucket(env, obj, context); - context->valuesBuckets.push_back(*(context->valuesBucket)); - context->valuesBucket->Clear(); + context->valuesBuckets.push_back(context->valuesBucket); + context->valuesBucket.Clear(); } + return OK; } bool IsNapiString(napi_env env, napi_callback_info info) @@ -511,361 +598,450 @@ bool IsNapiString(napi_env env, napi_callback_info info) napi_value RdbStoreProxy::Insert(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Insert start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseTableName); - parsers.push_back(ParseValuesBucket); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Insert", - [](RdbStoreContext *context) { - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int64_t rowId = 0; - LOG_DEBUG("RdbStoreProxy::Insert Async"); - int errCode = obj->rdbStore_->Insert(rowId, context->tableName, *(context->valuesBucket)); - context->rowId = rowId; - LOG_DEBUG("RdbStoreProxy::Insert errCode is: %{public}d", errCode); - return errCode; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_create_int64(context->env, context->rowId, &output); - LOG_DEBUG("RdbStoreProxy::Insert end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBucket(env, argv[1], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int64_t rowId = 0; + LOG_DEBUG("RdbStoreProxy::Insert Async"); + int errCode = obj->rdbStore_->Insert(rowId, context->tableName, context->valuesBucket); + context->rowId = rowId; + LOG_DEBUG("RdbStoreProxy::Insert errCode is: %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_create_int64(env, context->rowId, &result); + LOG_DEBUG("RdbStoreProxy::Insert end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::BatchInsert(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::BatchInsert start."); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseTableName); - parsers.push_back(ParseValuesBuckets); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "BatchInsert", - [](RdbStoreContext *context) { - LOG_INFO("RdbStoreProxy::BatchInsert Async."); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - if (context->insertNum == -1) { - return E_OK; - } - int64_t outInsertNum = 0; - int errCode = obj->rdbStore_->BatchInsert(outInsertNum, context->tableName, context->valuesBuckets); - context->insertNum = outInsertNum; - return errCode; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_create_int64(context->env, context->insertNum, &output); - LOG_DEBUG("RdbStoreProxy::BatchInsert end."); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBuckets(env, argv[1], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_INFO("RdbStoreProxy::BatchInsert Async."); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + if (context->insertNum == -1) { + return E_OK; + } + int64_t outInsertNum = 0; + int errCode = obj->rdbStore_->BatchInsert(outInsertNum, context->tableName, context->valuesBuckets); + context->insertNum = outInsertNum; + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_create_int64(env, context->insertNum, &result); + LOG_DEBUG("RdbStoreProxy::BatchInsert end."); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Delete(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Delete start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - if (IsNapiString(env, info)) { - parsers.push_back(ParseTableName); - } - parsers.push_back(ParsePredicates); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Delete", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Delete Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int deletedRows = 0; - int errCode = obj->rdbStore_->Delete(deletedRows, *(context->rdbPredicates)); - context->rowId = deletedRows; - LOG_DEBUG("RdbStoreProxy::Delete errCode is: %{public}d", errCode); - return errCode; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_create_int64(context->env, context->rowId, &output); - LOG_DEBUG("RdbStoreProxy::Delete end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + context->isNapiString = IsNapiString(env, info); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + if (context->isNapiString) { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[1], context)); + } else { + std::shared_ptr paramNumError = std::make_shared("1 or 2"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[0], context)); + } + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Delete Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int deletedRows = 0; + int errCode = obj->rdbStore_->Delete(deletedRows, *(context->rdbPredicates)); + context->rowId = deletedRows; + LOG_DEBUG("RdbStoreProxy::Delete errCode is: %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_create_int64(env, context->rowId, &result); + LOG_DEBUG("RdbStoreProxy::Delete end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Update(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Update start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - if (IsNapiString(env, info)) { - parsers.push_back(ParseTableName); - } - parsers.push_back(ParseValuesBucket); - parsers.push_back(ParsePredicates); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Update", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Update Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int changedRows = 0; - int errCode = - obj->rdbStore_->Update(changedRows, *(context->valuesBucket), *(context->rdbPredicates)); - context->rowId = changedRows; - LOG_DEBUG("RdbStoreProxy::Update errCode is: %{public}d", errCode); - return errCode; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_create_int64(context->env, context->rowId, &output); - LOG_DEBUG("RdbStoreProxy::Update end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + context->isNapiString = IsNapiString(env, info); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + if (context->isNapiString) { + std::shared_ptr paramNumError = std::make_shared("3 or 4"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 3 || argc == 4, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBucket(env, argv[1], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[2], context)); + } else { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBucket(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[1], context)); + } + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Update Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int changedRows = 0; + int errCode = obj->rdbStore_->Update(changedRows, context->valuesBucket, *(context->rdbPredicates)); + context->rowId = changedRows; + LOG_DEBUG("RdbStoreProxy::Update errCode is: %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_create_int64(env, context->rowId, &result); + LOG_DEBUG("RdbStoreProxy::Update end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Query(napi_env env, napi_callback_info info) { - LOG_DEBUG("RdbStoreProxy::Query start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - if (IsNapiString(env, info)) { - parsers.push_back(ParseTableName); - } - parsers.push_back(ParsePredicates); - parsers.push_back(ParseColumns); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Query", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Query Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + auto context = std::make_shared(); + context->isNapiString = IsNapiString(env, info); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + if (context->isNapiString) { + std::shared_ptr paramNumError = std::make_shared("1, 2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[1], context)); + if (argc > 2) { + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseColumns(env, argv[2], context)); + } + } else { + std::shared_ptr paramNumError = std::make_shared("1 or 2"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[0], context)); + if (argc > 1) { + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseColumns(env, argv[1], context)); + } + } + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - context->resultSet_value = obj->rdbStore_->Query(*(context->rdbPredicates), context->columns); - LOG_DEBUG("RdbStoreProxy::Query result is nullptr ? %{public}d", (context->resultSet_value == nullptr)); - return (context->resultSet_value != nullptr) ? OK : ERR; + context->resultSet_value = obj->rdbStore_->Query(*(context->rdbPredicates), context->columns); + LOG_DEBUG("RdbStoreProxy::Query result is nullptr ? %{public}d", (context->resultSet_value == nullptr)); + return (context->resultSet_value != nullptr) ? OK : ERR; #else - context->resultSet = obj->rdbStore_->Query(*(context->rdbPredicates), context->columns); - LOG_DEBUG("RdbStoreProxy::Query result is nullptr ? %{public}d", (context->resultSet == nullptr)); - return (context->resultSet != nullptr) ? OK : ERR; + context->resultSet = obj->rdbStore_->Query(*(context->rdbPredicates), context->columns); + LOG_DEBUG("RdbStoreProxy::Query result is nullptr ? %{public}d", (context->resultSet == nullptr)); + return (context->resultSet != nullptr) ? OK : ERR; #endif - }, - [](RdbStoreContext *context, napi_value &output) { + }; + auto output = [context](napi_env env, napi_value &result) -> int { #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - output = ResultSetProxy::NewInstance( - context->env, std::shared_ptr(context->resultSet_value.release())); + result = ResultSetProxy::NewInstance( + env, std::shared_ptr(context->resultSet_value.release()), context->apiversion); #else - output = ResultSetProxy::NewInstance( - context->env, std::shared_ptr(context->resultSet.release())); + result = ResultSetProxy::NewInstance( + env, std::shared_ptr(context->resultSet.release()), context->apiversion); #endif - LOG_DEBUG("RdbStoreProxy::Query end"); - return (output != nullptr) ? OK : ERR; - }); + return (result != nullptr) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) napi_value RdbStoreProxy::RemoteQuery(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::RemoteQuery start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseDevice); - parsers.push_back(ParseTableName); - parsers.push_back(ParsePredicates); - parsers.push_back(ParseColumns); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "RemoteQuery", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::RemoteQuery Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - context->newResultSet = - obj->rdbStore_->RemoteQuery(context->device, *(context->rdbPredicates), context->columns); - LOG_DEBUG("RdbStoreProxy::RemoteQuery result is nullptr ? %{public}d", (context->newResultSet == nullptr)); - return (context->newResultSet != nullptr) ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - if (context->newResultSet == nullptr) { - LOG_DEBUG("RdbStoreProxy::RemoteQuery result is nullptr"); - return ERR; - } - output = ResultSetProxy::NewInstance(context->env, context->newResultSet); - LOG_DEBUG("RdbStoreProxy::RemoteQuery end"); - return (output != nullptr) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("4 or 5"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 4 || argc == 5, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseDevice(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[1], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[2], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseColumns(env, argv[3], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::RemoteQuery Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + context->newResultSet = + obj->rdbStore_->RemoteQuery(context->device, *(context->rdbPredicates), context->columns); + LOG_DEBUG("RdbStoreProxy::RemoteQuery result is nullptr ? %{public}d", (context->newResultSet == nullptr)); + return (context->newResultSet != nullptr) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + if (context->newResultSet == nullptr) { + LOG_DEBUG("RdbStoreProxy::RemoteQuery result is nullptr"); + return ERR; + } + result = ResultSetProxy::NewInstance(env, context->newResultSet, context->apiversion); + LOG_DEBUG("RdbStoreProxy::RemoteQuery end"); + return (result != nullptr) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } #endif napi_value RdbStoreProxy::QuerySql(napi_env env, napi_callback_info info) { - LOG_DEBUG("RdbStoreProxy::QuerySql start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseSql); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("1, 2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSql(env, argv[0], context)); + if (argc > 1) { #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - parsers.push_back(ParseColumns); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseColumns(env, argv[1], context)); #else - parsers.push_back(ParseSelectionArgs); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSelectionArgs(env, argv[1], context)); #endif - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "QuerySql", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::QuerySql Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + } + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - context->resultSet_value = obj->rdbStore_->QueryByStep(context->sql, context->columns); - LOG_ERROR("RdbStoreProxy::QuerySql is nullptr ? %{public}d ", context->resultSet_value == nullptr); - return (context->resultSet_value != nullptr) ? OK : ERR; + context->resultSet_value = obj->rdbStore_->QueryByStep(context->sql, context->columns); + LOG_ERROR("RdbStoreProxy::QuerySql is nullptr ? %{public}d ", context->resultSet_value == nullptr); + return (context->resultSet_value != nullptr) ? OK : ERR; #else - context->resultSet = obj->rdbStore_->QuerySql(context->sql, context->selectionArgs); - LOG_DEBUG("RdbStoreProxy::QuerySql is nullptr ? %{public}d", (context->resultSet == nullptr)); - return (context->resultSet != nullptr) ? OK : ERR; + std::string selectionArgs = ","; + for (int i = 0; i < context->selectionArgs.size(); i++) { + selectionArgs += context->selectionArgs[i]; + } + LOG_DEBUG( + "RdbStoreProxy::QuerySql sql=%{public}s, args=%{public}s", context->sql.c_str(), selectionArgs.c_str()); + context->resultSet = obj->rdbStore_->QuerySql(context->sql, context->selectionArgs); + LOG_DEBUG("RdbStoreProxy::QuerySql is nullptr ? %{public}d", (context->resultSet == nullptr)); + return (context->resultSet != nullptr) ? OK : ERR; #endif - }, - [](RdbStoreContext *context, napi_value &output) { + }; + auto output = [context](napi_env env, napi_value &result) -> int { #if defined(WINDOWS_PLATFORM) || defined(MAC_PLATFORM) - output = ResultSetProxy::NewInstance( - context->env, std::shared_ptr(context->resultSet_value.release())); + result = ResultSetProxy::NewInstance( + env, std::shared_ptr(context->resultSet_value.release()), context->apiversion); #else - output = ResultSetProxy::NewInstance( - context->env, std::shared_ptr(context->resultSet.release())); + result = ResultSetProxy::NewInstance( + env, std::shared_ptr(context->resultSet.release()), context->apiversion); #endif - LOG_DEBUG("RdbStoreProxy::QuerySql end"); - return (output != nullptr) ? OK : ERR; - }); + return (result != nullptr) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); +} + +int ParseBindArgs(const napi_env &env, const napi_value &arg, std::shared_ptr context) +{ + context->BindArgs(env, arg); + return OK; } napi_value RdbStoreProxy::ExecuteSql(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::ExecuteSql start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseSql); - parsers.push_back( - [](const napi_env &env, const napi_value &arg, RdbStoreContext *ctx) { ctx->BindArgs(env, arg); }); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "ExecuteSql", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::ExecuteSql Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int errCode = obj->rdbStore_->ExecuteSql(context->sql, context->bindArgs); - LOG_DEBUG("RdbStoreProxy::ExecuteSql errCode is: %{public}d", errCode); - return errCode; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_get_undefined(context->env, &output); - LOG_DEBUG("RdbStoreProxy::ExecuteSql end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("1, 2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSql(env, argv[0], context)); + if (argc > 1) { + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseBindArgs(env, argv[1], context)); + } + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::ExecuteSql Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int errCode = obj->rdbStore_->ExecuteSql(context->sql, context->bindArgs); + LOG_DEBUG("RdbStoreProxy::ExecuteSql errCode is: %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_get_undefined(env, &result); + LOG_DEBUG("RdbStoreProxy::ExecuteSql end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Count(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Count start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParsePredicates); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Count", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Count Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - std::int64_t temp = 0; - int errCode = obj->rdbStore_->Count(temp, *(context->predicatesProxy->GetPredicates())); - context->rowId = temp; - LOG_DEBUG("RdbStoreProxy::Count errCode is: %{public}d", errCode); - return errCode; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_create_int64(context->env, context->rowId, &output); - LOG_DEBUG("RdbStoreProxy::Count end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("1 or 2"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[0], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Count Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + std::int64_t temp = 0; + int errCode = obj->rdbStore_->Count(temp, *(context->predicatesProxy->GetPredicates())); + context->rowId = temp; + LOG_DEBUG("RdbStoreProxy::Count errCode is: %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_create_int64(env, context->rowId, &result); + LOG_DEBUG("RdbStoreProxy::Count end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Replace(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Replace start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseTableName); - parsers.push_back(ParseValuesBucket); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Replace", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Replace Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int64_t rowId = 0; - int errCode = obj->rdbStore_->Replace(rowId, context->tableName, *(context->valuesBucket)); - context->rowId = rowId; - LOG_DEBUG("RdbStoreProxy::Replace errCode is:%{public}d", errCode); - return errCode; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_create_int64(context->env, context->rowId, &output); - LOG_DEBUG("RdbStoreProxy::Replace end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseValuesBucket(env, argv[1], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Replace Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int64_t rowId = 0; + int errCode = obj->rdbStore_->Replace(rowId, context->tableName, context->valuesBucket); + context->rowId = rowId; + LOG_DEBUG("RdbStoreProxy::Replace errCode is:%{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_create_int64(env, context->rowId, &result); + LOG_DEBUG("RdbStoreProxy::Replace end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Backup(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Backup start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseTableName); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Backup", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Backup Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int errCode = obj->rdbStore_->Backup(context->tableName, context->newKey); - LOG_DEBUG("RdbStoreProxy::Backup errCode is: %{public}d", errCode); - return (errCode == E_OK) ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_get_undefined(context->env, &output); - LOG_DEBUG("RdbStoreProxy::Backup end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("1 or 2"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[0], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Backup Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int errCode = obj->rdbStore_->Backup(context->tableName, context->newKey); + LOG_DEBUG("RdbStoreProxy::Backup errCode is: %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_get_undefined(env, &result); + LOG_DEBUG("RdbStoreProxy::Backup end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Attach(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Attach start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseAlias); - parsers.push_back(ParsePath); - parsers.push_back(ParseNewKey); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Attach", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Attach Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int errCode = obj->rdbStore_->Attach(context->aliasName, context->pathName, context->newKey); - LOG_ERROR("RdbStoreProxy::Attach errCode is:%{public}d ", errCode); - return (errCode != E_OK) ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_get_undefined(context->env, &output); - LOG_DEBUG("RdbStoreProxy::Attach end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("3 or 4"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 3 || argc == 4, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseAlias(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePath(env, argv[1], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseNewKey(env, argv[2], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Attach Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int errCode = obj->rdbStore_->Attach(context->aliasName, context->pathName, context->newKey); + LOG_ERROR("RdbStoreProxy::Attach errCode is:%{public}d ", errCode); + return (errCode != E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_get_undefined(env, &result); + LOG_DEBUG("RdbStoreProxy::Attach end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::IsHoldingConnection(napi_env env, napi_callback_info info) @@ -954,29 +1130,34 @@ napi_value RdbStoreProxy::Commit(napi_env env, napi_callback_info info) napi_value RdbStoreProxy::QueryByStep(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::QueryByStep start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseSql); - parsers.push_back(ParseColumns); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "QueryByStep", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::QueryByStep Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - context->resultSet_value = obj->rdbStore_->QueryByStep(context->sql, context->columns); - LOG_ERROR("RdbStoreProxy::QueryByStep is nullptr ? %{public}d ", context->resultSet_value == nullptr); - return (context->resultSet_value != nullptr) ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - if (context->resultSet_value != nullptr) { - output = ResultSetProxy::NewInstance( - context->env, std::shared_ptr(context->resultSet_value.release())); - } - LOG_DEBUG("RdbStoreProxy::QueryByStep end"); - return (output != nullptr) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSql(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseColumns(env, argv[1], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::QueryByStep Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + context->resultSet_value = obj->rdbStore_->QueryByStep(context->sql, context->columns); + LOG_ERROR("RdbStoreProxy::QueryByStep is nullptr ? %{public}d ", context->resultSet_value == nullptr); + return (context->resultSet_value != nullptr) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + if (context->resultSet_value != nullptr) { + result = ResultSetProxy::NewInstance( + env, std::shared_ptr(context->resultSet_value.release()), context->apiversion); + } + LOG_DEBUG("RdbStoreProxy::QueryByStep end"); + return (result != nullptr) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::IsInTransaction(napi_env env, napi_callback_info info) @@ -1032,154 +1213,183 @@ napi_value RdbStoreProxy::SetVersion(napi_env env, napi_callback_info info) napi_value RdbStoreProxy::MarkAsCommit(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::MarkAsCommit start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "MarkAsCommit", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::MarkAsCommit Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int errCode = obj->rdbStore_->MarkAsCommit(); - LOG_ERROR("RdbStoreProxy::MarkAsCommit errCode is : %{public}d", errCode); - return (errCode == E_OK) ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_get_undefined(context->env, &output); - LOG_DEBUG("RdbStoreProxy::MarkAsCommit end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("0 or 1"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 0 || argc == 1, context->SetError(paramNumError)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::MarkAsCommit Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int errCode = obj->rdbStore_->MarkAsCommit(); + LOG_ERROR("RdbStoreProxy::MarkAsCommit errCode is : %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_get_undefined(env, &result); + LOG_DEBUG("RdbStoreProxy::MarkAsCommit end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::EndTransaction(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::EndTransaction start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "EndTranscation", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::EndTransaction Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int errCode = obj->rdbStore_->EndTransaction(); - LOG_DEBUG("RdbStoreProxy::EndTransaction errCode is : %{public}d", errCode); - return (errCode != E_OK) ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_get_undefined(context->env, &output); - LOG_DEBUG("RdbStoreProxy::EndTransaction end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("0 or 1"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 0 || argc == 1, context->SetError(paramNumError)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::EndTransaction Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int errCode = obj->rdbStore_->EndTransaction(); + LOG_DEBUG("RdbStoreProxy::EndTransaction errCode is : %{public}d", errCode); + return (errCode != E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_get_undefined(env, &result); + LOG_DEBUG("RdbStoreProxy::EndTransaction end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Restore(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Restore start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseSrcName); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Restore", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Restore Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - int errCode = 0; - errCode = obj->rdbStore_->Restore(context->srcName, context->newKey); - LOG_DEBUG("RdbStoreProxy::Restore errCode is : %{public}d", errCode); - return (errCode == E_OK) ? OK : ERR; - }, - - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_get_undefined(context->env, &output); - LOG_DEBUG("RdbStoreProxy::Restore end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("1 or 2"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSrcName(env, argv[0], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Restore Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + int errCode = 0; + errCode = obj->rdbStore_->Restore(context->srcName, context->newKey); + LOG_DEBUG("RdbStoreProxy::Restore errCode is : %{public}d", errCode); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_get_undefined(env, &result); + LOG_DEBUG("RdbStoreProxy::Restore end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) napi_value RdbStoreProxy::SetDistributedTables(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::SetDistributedTables start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseTablesName); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "SetDistributedTables", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::SetDistributedTables Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - bool res = obj->rdbStore_->SetDistributedTables(context->tablesName); - LOG_DEBUG("RdbStoreProxy::SetDistributedTables res is : %{public}d", res); - return res ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_get_undefined(context->env, &output); - LOG_DEBUG("RdbStoreProxy::SetDistributedTables end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("1 or 2"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTablesName(env, argv[0], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::SetDistributedTables Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + bool res = obj->rdbStore_->SetDistributedTables(context->tablesName); + LOG_DEBUG("RdbStoreProxy::SetDistributedTables res is : %{public}d", res); + return res ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_get_undefined(env, &result); + LOG_DEBUG("RdbStoreProxy::SetDistributedTables end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::ObtainDistributedTableName(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::ObtainDistributedTableName start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseDevice); - parsers.push_back(ParseTableName); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "ObtainDistributedTableName", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::ObtainDistributedTableName Async"); - RdbStoreProxy *obj = reinterpret_cast(context->boundObj); - auto name = obj->rdbStore_->ObtainDistributedTableName(context->device, context->tableName); - LOG_INFO("RdbStoreProxy::ObtainDistributedTableName name is empty ? : %{public}d", name.empty()); - context->tableName = name; - return name.empty() ? ERR : OK; - }, - [](RdbStoreContext *context, napi_value &output) { - napi_status status = napi_create_string_utf8( - context->env, context->tableName.c_str(), context->tableName.length(), &output); - LOG_DEBUG("RdbStoreProxy::ObtainDistributedTableName end"); - return (status == napi_ok) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseDevice(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseTableName(env, argv[1], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::ObtainDistributedTableName Async"); + RdbStoreProxy *obj = reinterpret_cast(context->boundObj); + auto name = obj->rdbStore_->ObtainDistributedTableName(context->device, context->tableName); + LOG_INFO("RdbStoreProxy::ObtainDistributedTableName name is empty ? : %{public}d", name.empty()); + context->tableName = name; + return name.empty() ? ERR : OK; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = + napi_create_string_utf8(env, context->tableName.c_str(), context->tableName.length(), &result); + LOG_DEBUG("RdbStoreProxy::ObtainDistributedTableName end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value RdbStoreProxy::Sync(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbStoreProxy::Sync start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; - parsers.push_back(ParseEnumArg); - parsers.push_back(ParsePredicates); - proxy.ParseInputs(parsers, ParseThis); - return proxy.DoAsyncWork( - "Sync", - [](RdbStoreContext *context) { - LOG_DEBUG("RdbStoreProxy::Sync Async"); - auto *obj = reinterpret_cast(context->boundObj); - SyncOption option; - option.mode = static_cast(context->enumArg); - option.isBlock = true; - bool res = obj->rdbStore_->Sync(option, *context->predicatesProxy->GetPredicates(), - [context](const SyncResult &result) { context->syncResult = result; }); - LOG_INFO("RdbStoreProxy::Sync res is : %{public}d", res); - return res ? OK : ERR; - }, - [](RdbStoreContext *context, napi_value &output) { - output = JSUtils::Convert2JSValue(context->env, context->syncResult); - LOG_DEBUG("RdbStoreProxy::Sync end"); - return (output != nullptr) ? OK : ERR; - }); + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSyncModeArg(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePredicates(env, argv[1], context)); + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) { + LOG_DEBUG("RdbStoreProxy::Sync Async"); + auto *obj = reinterpret_cast(context->boundObj); + SyncOption option; + option.mode = static_cast(context->enumArg); + option.isBlock = true; + bool res = obj->rdbStore_->Sync(option, *context->predicatesProxy->GetPredicates(), + [context](const SyncResult &result) { context->syncResult = result; }); + LOG_INFO("RdbStoreProxy::Sync res is : %{public}d", res); + return res ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + result = JSUtils::Convert2JSValue(env, context->syncResult); + LOG_DEBUG("RdbStoreProxy::Sync end"); + return (result != nullptr) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } void RdbStoreProxy::OnDataChangeEvent(napi_env env, size_t argc, napi_value *argv) @@ -1261,7 +1471,7 @@ void RdbStoreProxy::OffDataChangeEvent(napi_env env, size_t argc, napi_value *ar napi_value RdbStoreProxy::OnEvent(napi_env env, napi_callback_info info) { size_t argc = MAX_ON_EVENT_ARG_NUM; - napi_value argv[MAX_ON_EVENT_ARG_NUM] {}; + napi_value argv[MAX_ON_EVENT_ARG_NUM]{}; napi_value self = nullptr; if (napi_get_cb_info(env, info, &argc, argv, &self, nullptr) != napi_ok) { LOG_ERROR("RdbStoreProxy::OnEvent: get args failed"); @@ -1279,14 +1489,14 @@ napi_value RdbStoreProxy::OnEvent(napi_env env, napi_callback_info info) } proxy->Release(env); - LOG_ERROR("RdbStoreProxy::OnEvent end"); + LOG_INFO("RdbStoreProxy::OnEvent end"); return nullptr; } napi_value RdbStoreProxy::OffEvent(napi_env env, napi_callback_info info) { size_t argc = MAX_ON_EVENT_ARG_NUM; - napi_value argv[MAX_ON_EVENT_ARG_NUM] {}; + napi_value argv[MAX_ON_EVENT_ARG_NUM]{}; napi_value self = nullptr; if (napi_get_cb_info(env, info, &argc, argv, &self, nullptr) != napi_ok) { LOG_ERROR("RdbStoreProxy::OffEvent: get args failed"); @@ -1304,7 +1514,7 @@ napi_value RdbStoreProxy::OffEvent(napi_env env, napi_callback_info info) } proxy->Release(env); - LOG_ERROR("RdbStoreProxy::OffEvent end"); + LOG_INFO("RdbStoreProxy::OffEvent end"); return nullptr; } #endif diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp index 6174aade49950d105f6f51d55f5690c114a079cd..ba4467c466c34384ca9893639b928d5340a4b884 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -12,15 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "napi_rdb_store_helper.h" - #include +#include +#include #include "js_ability.h" #include "js_logger.h" #include "js_utils.h" -#include "napi_async_proxy.h" +#include "napi_async_call.h" +#include "napi_rdb_error.h" #include "napi_rdb_store.h" +#include "napi_rdb_store_helper.h" #include "rdb_errno.h" #include "rdb_open_callback.h" #include "rdb_store_config.h" @@ -32,6 +34,7 @@ using namespace OHOS::AppDataMgrJsKit; namespace OHOS { namespace RdbJsKit { + class OpenCallback : public OHOS::NativeRdb::RdbOpenCallback { public: OpenCallback() = default; @@ -238,157 +241,186 @@ private: std::vector> callbacks_; }; -class HelperRdbContext : public NapiAsyncProxy::AysncContext { -public: - HelperRdbContext() : AysncContext(), config(""), version(0), openCallback(), proxy(nullptr) - { - } +struct HelperRdbContext : public AsyncCall::Context { RdbStoreConfig config; int32_t version; + bool iscontext; OpenCallback openCallback; std::shared_ptr proxy; - std::shared_ptr context; + std::shared_ptr abilitycontext; + + HelperRdbContext() + : Context(nullptr, nullptr), config(""), version(0), iscontext(false), openCallback(), proxy(nullptr) + { + } + HelperRdbContext(InputAction input, OutputAction output) + : Context(std::move(input), std::move(output)), config(""), version(0), iscontext(false), openCallback(), + proxy(nullptr) + { + } + virtual ~HelperRdbContext(){}; + + int operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) override + { + return Context::operator()(env, argc, argv, self); + } + int operator()(napi_env env, napi_value &result) override + { + return Context::operator()(env, result); + } }; -void ParseContext(const napi_env &env, const napi_value &object, HelperRdbContext *asyncContext) +using ParseStoreConfigFunction = int (*)( + const napi_env &env, const napi_value &object, std::shared_ptr context); + +void ParserThis(const napi_env &env, const napi_value &self, std::shared_ptr context) +{ + napi_unwrap(env, self, &context->boundObj); +} + +int ParseContext(const napi_env &env, const napi_value &object, std::shared_ptr context) { - LOG_DEBUG("ParseContext begin"); - auto context = JSAbility::GetContext(env, object); - NAPI_ASSERT_RETURN_VOID(env, context != nullptr, "ParseContext get context failed."); - asyncContext->context = context; - LOG_DEBUG("ParseContext end"); + auto abilitycontext = JSAbility::GetContext(env, object); + std::shared_ptr paramError = std::make_shared("context", "a Context."); + RDB_CHECK_RETURN_CALL_RESULT(abilitycontext != nullptr, context->SetError(paramError)); + context->abilitycontext = abilitycontext; + return OK; } -void ParseDatabaseName(const napi_env &env, const napi_value &object, HelperRdbContext *asyncContext) +int ParseDatabaseName(const napi_env &env, const napi_value &object, std::shared_ptr context) { - LOG_DEBUG("ParseDatabaseName begin"); napi_value value; napi_get_named_property(env, object, "name", &value); - NAPI_ASSERT_RETURN_VOID(env, value != nullptr, "no database name found in config."); + std::shared_ptr paramError = std::make_shared("config", "a StoreConfig."); + RDB_CHECK_RETURN_CALL_RESULT(value != nullptr, context->SetError(paramError)); + std::string name = JSUtils::Convert2String(env, value); - NAPI_ASSERT_RETURN_VOID(env, !name.empty(), "Get database name empty."); - asyncContext->config.SetName(std::move(name)); - LOG_DEBUG("ParseDatabaseName end"); + RDB_CHECK_RETURN_CALL_RESULT(!name.empty(), context->SetError(paramError)); + context->config.SetName(std::move(name)); + return OK; } -void ParseIsEncrypt(const napi_env &env, const napi_value &object, HelperRdbContext *asyncContext) +int ParseIsEncrypt(const napi_env &env, const napi_value &object, std::shared_ptr context) { - LOG_DEBUG("ParseIsEncrypt begin"); napi_value value = nullptr; napi_get_named_property(env, object, "encrypt", &value); if (value != nullptr) { bool isEncrypt = false; JSUtils::Convert2Bool(env, value, isEncrypt); - asyncContext->config.SetEncryptStatus(isEncrypt); + context->config.SetEncryptStatus(isEncrypt); } - LOG_DEBUG("ParseIsEncrypt end"); + return OK; } -void ParseContextProperty(const napi_env &env, HelperRdbContext *asyncContext) +int ParseContextProperty(const napi_env &env, std::shared_ptr context) { - LOG_DEBUG("ParseContextProperty begin"); - if (asyncContext->context == nullptr) { - ParseContext(env, nullptr, asyncContext); // when no context as arg got from application. - NAPI_ASSERT_RETURN_VOID(env, asyncContext->context != nullptr, "Context is NULL."); + if (context->abilitycontext == nullptr) { + int status = ParseContext(env, nullptr, context); // when no context as arg got from application. + std::shared_ptr paramError = std::make_shared("context", "a Context."); + RDB_CHECK_RETURN_CALL_RESULT(status == OK, context->SetError(paramError)); } - asyncContext->config.SetModuleName(asyncContext->context->GetModuleName()); - asyncContext->config.SetArea(asyncContext->context->GetArea()); - asyncContext->config.SetBundleName(asyncContext->context->GetBundleName()); - asyncContext->config.SetUri(asyncContext->context->GetUri()); - asyncContext->config.SetReadPermission(asyncContext->context->GetReadPermission()); - asyncContext->config.SetWritePermission(asyncContext->context->GetWritePermission()); - LOG_DEBUG("ParseContextProperty end"); + context->config.SetModuleName(context->abilitycontext->GetModuleName()); + context->config.SetArea(context->abilitycontext->GetArea()); + context->config.SetBundleName(context->abilitycontext->GetBundleName()); + context->config.SetUri(context->abilitycontext->GetUri()); + context->config.SetReadPermission(context->abilitycontext->GetReadPermission()); + context->config.SetWritePermission(context->abilitycontext->GetWritePermission()); + return OK; } -void ParseDatabaseDir(const napi_env &env, HelperRdbContext *asyncContext, std::string &name) +int ParseDatabaseDir(const napi_env &env, std::shared_ptr context) { - LOG_DEBUG("ParseDatabaseDir begin"); - std::string databaseDir = asyncContext->context->GetDatabaseDir(); - NAPI_ASSERT_RETURN_VOID(env, asyncContext->context != nullptr, "Context is NULL."); + std::string databaseDir = context->abilitycontext->GetDatabaseDir(); + std::shared_ptr paramError = std::make_shared("context", "a Context."); + RDB_CHECK_RETURN_CALL_RESULT(context->abilitycontext != nullptr, context->SetError(paramError)); int errorCode = E_OK; - std::string realPath = SqliteDatabaseUtils::GetDefaultDatabasePath(databaseDir, name, errorCode); - NAPI_ASSERT_RETURN_VOID(env, errorCode == E_OK, "Get database real path failed."); - asyncContext->config.SetPath(std::move(realPath)); - LOG_DEBUG("ParseDatabaseDir end"); + std::string databaseName = context->config.GetName(); + std::string realPath = SqliteDatabaseUtils::GetDefaultDatabasePath(databaseDir, databaseName, errorCode); + paramError = std::make_shared("config", "a StoreConfig."); + RDB_CHECK_RETURN_CALL_RESULT(errorCode == E_OK, context->SetError(paramError)); + context->config.SetPath(std::move(realPath)); + return OK; } -void ParseSecurityLevel(const napi_env &env, const napi_value &object, HelperRdbContext *asyncContext) +int ParseSecurityLevel(const napi_env &env, const napi_value &object, std::shared_ptr context) { - LOG_DEBUG("ParseSecurityLevel begin"); napi_value value = nullptr; bool hasProp = false; + std::shared_ptr paramError = std::make_shared("config", "a StoreConfig."); napi_status status = napi_has_named_property(env, object, "securityLevel", &hasProp); if (status != napi_ok || !hasProp) { LOG_ERROR("napi_has_named_property failed! code:%{public}d!, hasProp:%{public}d!", status, hasProp); - return; + RDB_CHECK_RETURN_CALL_RESULT(false, context->SetError(paramError)); } status = napi_get_named_property(env, object, "securityLevel", &value); if (status != napi_ok) { LOG_ERROR("napi_get_named_property failed! code:%{public}d!", status); - return; + RDB_CHECK_RETURN_CALL_RESULT(false, context->SetError(paramError)); } int32_t securityLevel; napi_get_value_int32(env, value, &securityLevel); - bool isValidSecurityLevel = static_cast(securityLevel) >= DatabaseFileSecurityLevel::S0 - && static_cast(securityLevel) - <= DatabaseFileSecurityLevel::S4; + SecurityLevel sl = static_cast(securityLevel); LOG_DEBUG("Get sl:%{public}d", securityLevel); + + bool isValidSecurityLevel = sl >= SecurityLevel::S1 && sl < SecurityLevel::LAST; if (!isValidSecurityLevel) { - LOG_ERROR("The securityLevel should be S0-S4!"); - return; + LOG_ERROR("The securityLevel should be S1-S4!"); + RDB_CHECK_RETURN_CALL_RESULT(false, context->SetError(paramError)); } - asyncContext->config.SetSecurityLevel(securityLevel); + context->config.SetSecurityLevel(sl); LOG_DEBUG("ParseSecurityLevel end"); + return OK; } -void ParseStoreConfig(const napi_env &env, const napi_value &object, HelperRdbContext *asyncContext) +int ParseStoreConfig(const napi_env &env, const napi_value &object, std::shared_ptr context) { - LOG_DEBUG("ParseStoreConfig begin"); - ParseDatabaseName(env, object, asyncContext); - ParseIsEncrypt(env, object, asyncContext); - ParseContextProperty(env, asyncContext); - std::string name = asyncContext->config.GetName(); - ParseDatabaseDir(env, asyncContext, name); - LOG_DEBUG("ParseStoreConfig end"); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseDatabaseName(env, object, context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseIsEncrypt(env, object, context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseContextProperty(env, context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseDatabaseDir(env, context)); + return OK; } -void ParseStoreConfigV9(const napi_env &env, const napi_value &object, HelperRdbContext *asyncContext) +int ParseStoreConfigV9(const napi_env &env, const napi_value &object, std::shared_ptr context) { - LOG_DEBUG("ParseStoreConfigV9 begin"); - ParseDatabaseName(env, object, asyncContext); - ParseIsEncrypt(env, object, asyncContext); - ParseSecurityLevel(env, object, asyncContext); - ParseContextProperty(env, asyncContext); - std::string name = asyncContext->config.GetName(); - ParseDatabaseDir(env, asyncContext, name); - LOG_DEBUG("ParseStoreConfigV9 end"); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseDatabaseName(env, object, context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseIsEncrypt(env, object, context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseSecurityLevel(env, object, context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseContextProperty(env, context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseDatabaseDir(env, context)); + return OK; } -void ParsePath(const napi_env &env, const napi_value &arg, HelperRdbContext *asyncContext) +int ParsePath(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - LOG_DEBUG("ParsePath begin"); std::string path = JSUtils::Convert2String(env, arg); - NAPI_ASSERT_RETURN_VOID(env, !path.empty(), "Get database name empty."); + std::shared_ptr paramError = std::make_shared("name", "a without path non empty string."); + RDB_CHECK_RETURN_CALL_RESULT(!path.empty(), context->SetError(paramError)); + size_t pos = path.find_first_of('/'); - NAPI_ASSERT_RETURN_VOID(env, pos == std::string::npos, "A name without path should be input."); + RDB_CHECK_RETURN_CALL_RESULT(pos == std::string::npos, context->SetError(paramError)); - if (asyncContext->context == nullptr) { - ParseContext(env, nullptr, asyncContext); // when no context as arg got from application. + if (context->abilitycontext == nullptr) { + // when no context as arg got from application. + ParseContext(env, nullptr, context); } - std::string databaseDir = asyncContext->context->GetDatabaseDir(); + std::string databaseDir = context->abilitycontext->GetDatabaseDir(); int errorCode = E_OK; std::string realPath = SqliteDatabaseUtils::GetDefaultDatabasePath(databaseDir, path, errorCode); - NAPI_ASSERT_RETURN_VOID(env, errorCode == E_OK, "Get database real path failed."); - asyncContext->config.SetPath(realPath); - LOG_DEBUG("ParsePath end"); + RDB_CHECK_RETURN_CALL_RESULT(errorCode == E_OK, context->SetError(paramError)); + + context->config.SetPath(realPath); + return OK; } -void ParseVersion(const napi_env &env, const napi_value &arg, HelperRdbContext *asyncContext) +int ParseVersion(const napi_env &env, const napi_value &arg, std::shared_ptr context) { - napi_get_value_int32(env, arg, &asyncContext->version); - LOG_DEBUG("ParseVersion end"); + napi_get_value_int32(env, arg, &context->version); + std::shared_ptr paramError = std::make_shared("version", "an integer greater than 0."); + RDB_CHECK_RETURN_CALL_RESULT(context->version > 0, context->SetError(paramError)); + return OK; } class DefaultOpenCallback : public RdbOpenCallback { @@ -403,95 +435,114 @@ public: } }; -napi_value GetRdbStore(napi_env env, napi_callback_info info) +napi_value InnerGetRdbStore(napi_env env, napi_callback_info info, std::shared_ptr context, + ParseStoreConfigFunction parseStoreConfig) { LOG_DEBUG("RdbJsKit::GetRdbStore start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; + context->iscontext = JSAbility::CheckContext(env, info); + // context: Context, config: StoreConfig, version: number + auto input = [context, parseStoreConfig](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + if (context->iscontext || context->apiversion > APIVERSION_V8) { + std::shared_ptr paramNumError = std::make_shared("3 or 4"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 3 || argc == 4, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseContext(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(parseStoreConfig(env, argv[1], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseVersion(env, argv[2], context)); + } else { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(parseStoreConfig(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseVersion(env, argv[1], context)); + } + ParserThis(env, self, context); + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) -> int { + LOG_DEBUG("RdbJsKit::GetRdbStore Async"); + int errCode = OK; + DefaultOpenCallback callback; + context->proxy = RdbHelper::GetRdbStore(context->config, context->version, callback, errCode); + std::shared_ptr dbInvalidError = std::make_shared(); + RDB_CHECK_RETURN_CALL_RESULT( + errCode != E_EMPTY_FILE_NAME && errCode != E_RELATIVE_PATH, context->SetError(dbInvalidError)); + std::shared_ptr dbCorruptedError = std::make_shared(); + RDB_CHECK_RETURN_CALL_RESULT(errCode >= 0, context->SetError(dbCorruptedError)); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + result = RdbStoreProxy::NewInstance(env, context->proxy, context->apiversion); + context->openCallback.DelayNotify(); + LOG_DEBUG("RdbJsKit::GetRdbStore end"); + return (result != nullptr) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); +} - if (JSAbility::CheckContext(env, info)) { - parsers.push_back(ParseContext); - } - parsers.push_back(ParseStoreConfig); - parsers.push_back(ParseVersion); - proxy.ParseInputs(parsers); - return proxy.DoAsyncWork( - "getRdbStore", - [](HelperRdbContext *context) { - LOG_DEBUG("RdbJsKit::GetRdbStore Async"); - int errCode = OK; - DefaultOpenCallback callback; - context->proxy = RdbHelper::GetRdbStore(context->config, context->version, callback, errCode); - if (errCode != E_OK) { - LOG_DEBUG("GetRdbStore failed %{public}d", errCode); - } - return (errCode == E_OK) ? OK : ERR; - }, - [](HelperRdbContext *context, napi_value &output) { - output = RdbStoreProxy::NewInstance(context->env, context->proxy); - context->openCallback.DelayNotify(); - LOG_DEBUG("RdbJsKit::GetRdbStore end"); - return (output != nullptr) ? OK : ERR; - }); +napi_value GetRdbStore(napi_env env, napi_callback_info info) +{ + auto context = std::make_shared(); + context->apiversion = APIVERSION_V8; + return InnerGetRdbStore(env, info, context, ParseStoreConfig); } napi_value GetRdbStoreV9(napi_env env, napi_callback_info info) { - LOG_DEBUG("RdbJsKit::GetRdbStoreV9 start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; + auto context = std::make_shared(); + context->apiversion = APIVERSION_V9; + return InnerGetRdbStore(env, info, context, ParseStoreConfigV9); +} - if (JSAbility::CheckContext(env, info)) { - parsers.push_back(ParseContext); - } - parsers.push_back(ParseStoreConfigV9); - parsers.push_back(ParseVersion); - proxy.ParseInputs(parsers); - return proxy.DoAsyncWork( - "getRdbStoreV9", - [](HelperRdbContext *context) { - LOG_DEBUG("RdbJsKit::GetRdbStoreV9 Async"); - int errCode = OK; - DefaultOpenCallback callback; - context->proxy = RdbHelper::GetRdbStore(context->config, context->version, callback, errCode); - if (errCode != E_OK) { - LOG_DEBUG("GetRdbStoreV9 failed %{public}d", errCode); - } - return (errCode == E_OK) ? OK : ERR; - }, - [](HelperRdbContext *context, napi_value &output) { - output = RdbStoreProxy::NewInstance(context->env, context->proxy); - context->openCallback.DelayNotify(); - LOG_DEBUG("RdbJsKit::GetRdbStoreV9 end"); - return (output != nullptr) ? OK : ERR; - }); +napi_value InnerDeleteRdbStore(napi_env env, napi_callback_info info, std::shared_ptr context) +{ + LOG_DEBUG("RdbJsKit::DeleteRdbStore start"); + context->iscontext = JSAbility::CheckContext(env, info); + // context: Context, config: StoreConfig, version: number + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> int { + if (context->iscontext || context->apiversion > APIVERSION_V8) { + std::shared_ptr paramNumError = std::make_shared("2 or 3"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 2 || argc == 3, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParseContext(env, argv[0], context)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePath(env, argv[1], context)); + } else { + std::shared_ptr paramNumError = std::make_shared("1 or 2"); + RDB_CHECK_RETURN_CALL_RESULT(argc == 1 || argc == 2, context->SetError(paramNumError)); + RDB_ASYNC_PARAM_CHECK_FUNCTION(ParsePath(env, argv[0], context)); + } + return OK; + }; + auto exec = [context](AsyncCall::Context *ctx) -> int { + int errCode = RdbHelper::DeleteRdbStore(context->config.GetPath()); + LOG_DEBUG("RdbJsKit::DeleteRdbStore failed %{public}d", errCode); + std::shared_ptr dbInvalidError = std::make_shared(); + RDB_CHECK_RETURN_CALL_RESULT(errCode != E_EMPTY_FILE_NAME, context->SetError(dbInvalidError)); + return (errCode == E_OK) ? OK : ERR; + }; + auto output = [context](napi_env env, napi_value &result) -> int { + napi_status status = napi_create_int64(env, OK, &result); + LOG_DEBUG("RdbJsKit::DeleteRdbStore end"); + return (status == napi_ok) ? OK : ERR; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, std::dynamic_pointer_cast(context)); + RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK); + return asyncCall.Call(env, exec); } napi_value DeleteRdbStore(napi_env env, napi_callback_info info) { - LOG_DEBUG("RdbJsKit::DeleteRdbStore start"); - NapiAsyncProxy proxy; - proxy.Init(env, info); - std::vector::InputParser> parsers; + auto context = std::make_shared(); + context->apiversion = APIVERSION_V8; + return InnerDeleteRdbStore(env, info, context); +} - if (JSAbility::CheckContext(env, info)) { - parsers.push_back(ParseContext); - } - parsers.push_back(ParsePath); - proxy.ParseInputs(parsers); - return proxy.DoAsyncWork( - "deleteRdbStore", - [](HelperRdbContext *context) { - int ret = RdbHelper::DeleteRdbStore(context->config.GetPath()); - return (ret == E_OK) ? OK : ERR; - }, - [](HelperRdbContext *context, napi_value &output) { - napi_status status = napi_create_int64(context->env, E_OK, &output); - LOG_DEBUG("RdbJsKit::DeleteRdbStore end"); - return (status == napi_ok) ? OK : ERR; - }); +napi_value DeleteRdbStoreV9(napi_env env, napi_callback_info info) +{ + auto context = std::make_shared(); + context->apiversion = APIVERSION_V9; + return InnerDeleteRdbStore(env, info, context); } napi_value InitRdbHelper(napi_env env, napi_value exports) @@ -499,8 +550,9 @@ napi_value InitRdbHelper(napi_env env, napi_value exports) LOG_INFO("RdbJsKit::InitRdbHelper begin"); napi_property_descriptor properties[] = { DECLARE_NAPI_FUNCTION("getRdbStore", GetRdbStore), - DECLARE_NAPI_FUNCTION("getRdbStoreV9", GetRdbStoreV9), DECLARE_NAPI_FUNCTION("deleteRdbStore", DeleteRdbStore), + DECLARE_NAPI_FUNCTION("getRdbStoreV9", GetRdbStoreV9), + DECLARE_NAPI_FUNCTION("deleteRdbStoreV9", DeleteRdbStoreV9), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); LOG_INFO("RdbJsKit::InitRdbHelper end"); diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp index c1974dd50e5903f5490c159a4643e42330a25612..fcd2aa8914db7bb78c9f2e8b24c0920f51c9a2b3 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_result_set.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,13 +13,13 @@ * limitations under the License. */ -#include "napi_result_set.h" - #include #include "js_logger.h" #include "js_utils.h" -#include "napi_async_proxy.h" +#include "napi_rdb_error.h" +#include "napi_result_set.h" +#include "rdb_errno.h" #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) #include "abs_shared_result_set.h" @@ -33,11 +33,13 @@ using namespace OHOS::AppDataMgrJsKit; namespace OHOS { namespace RdbJsKit { static napi_ref __thread ctorRef_ = nullptr; +static napi_ref __thread ctorRefV9_ = nullptr; static const int E_OK = 0; + #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -napi_value ResultSetProxy::NewInstance(napi_env env, std::shared_ptr resultSet) +napi_value ResultSetProxy::NewInstance(napi_env env, std::shared_ptr resultSet, int version) { - auto instance = NewInstance(env, std::static_pointer_cast(resultSet)); + auto instance = NewInstance(env, std::static_pointer_cast(resultSet), version); ResultSetProxy *proxy = nullptr; auto status = napi_unwrap(env, instance, reinterpret_cast(&proxy)); if (proxy == nullptr) { @@ -54,9 +56,9 @@ napi_value ResultSetProxy::NewInstance(napi_env env, std::shared_ptr resultSet) +napi_value ResultSetProxy::NewInstance(napi_env env, std::shared_ptr resultSet, int version) { - napi_value cons = GetConstructor(env); + napi_value cons = GetConstructor(env, version); if (cons == nullptr) { LOG_ERROR("NewInstance GetConstructor is nullptr!"); return nullptr; @@ -101,13 +103,18 @@ std::shared_ptr ResultSetProxy::Create() } #endif -napi_value ResultSetProxy::GetConstructor(napi_env env) +napi_value ResultSetProxy::GetConstructor(napi_env env, int version) { napi_value cons; - if (ctorRef_ != nullptr) { + if (version > APIVERSION_V8 && ctorRefV9_ != nullptr) { + NAPI_CALL(env, napi_get_reference_value(env, ctorRefV9_, &cons)); + return cons; + } + if (version == APIVERSION_V8 && 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("goToRow", GoToRow), @@ -137,30 +144,49 @@ napi_value ResultSetProxy::GetConstructor(napi_env env) DECLARE_NAPI_GETTER("isAtFirstRow", IsAtFirstRow), DECLARE_NAPI_GETTER("isAtLastRow", IsAtLastRow), }; + + if (version > APIVERSION_V8) { + NAPI_CALL(env, napi_define_class(env, "ResultSetV9", NAPI_AUTO_LENGTH, InitializeV9, nullptr, + sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons)); + NAPI_CALL(env, napi_create_reference(env, cons, 1, &ctorRefV9_)); + return cons; + } + NAPI_CALL(env, napi_define_class(env, "ResultSet", NAPI_AUTO_LENGTH, Initialize, nullptr, - sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons)); + sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons)); NAPI_CALL(env, napi_create_reference(env, cons, 1, &ctorRef_)); return cons; } -napi_value ResultSetProxy::Initialize(napi_env env, napi_callback_info info) +napi_value ResultSetProxy::InnerInitialize(napi_env env, napi_callback_info info, int version) { napi_value self = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr)); auto *proxy = new ResultSetProxy(); + proxy->apiversion = version; auto finalize = [](napi_env env, void *data, void *hint) { ResultSetProxy *proxy = reinterpret_cast(data); delete proxy; }; napi_status status = napi_wrap(env, self, proxy, finalize, nullptr, nullptr); if (status != napi_ok) { - LOG_ERROR("ResultSetProxy napi_wrap failed! code:%{public}d!", status); + LOG_ERROR("ResultSetProxy napi_wrap failed! code:%{public}d!, version:%{public}d", status, version); finalize(env, proxy, nullptr); return nullptr; } return self; } +napi_value ResultSetProxy::Initialize(napi_env env, napi_callback_info info) +{ + return InnerInitialize(env, info, APIVERSION_V8); +} + +napi_value ResultSetProxy::InitializeV9(napi_env env, napi_callback_info info) +{ + return InnerInitialize(env, info, APIVERSION_V9); +} + ResultSetProxy::~ResultSetProxy() { LOG_INFO("ResultSetProxy destructor!"); @@ -186,21 +212,58 @@ ResultSetProxy &ResultSetProxy::operator=(std::shared_ptr resultSet) return *this; } -std::shared_ptr &ResultSetProxy::GetInnerResultSet(napi_env env, napi_callback_info info) +std::shared_ptr &ResultSetProxy::GetInnerResultSet( + napi_env env, napi_callback_info info, int &version) { - ResultSetProxy *resultSet = nullptr; + ResultSetProxy *resultSetProxy = 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_unwrap(env, self, reinterpret_cast(&resultSetProxy)); + version = resultSetProxy->apiversion; + return resultSetProxy->resultSet_; +} + +ResultSetProxy *ResultSetProxy::ParseInt32FieldByName( + napi_env env, napi_callback_info info, int32_t &field, const std::string name) +{ + napi_value self = nullptr; + size_t argc = 1; + napi_value args[1] = { 0 }; + napi_get_cb_info(env, info, &argc, args, &self, nullptr); + ResultSetProxy *resultSetProxy = nullptr; + napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)); + int version = resultSetProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), version); + + napi_status status = napi_get_value_int32(env, args[0], &field); + RDB_NAPI_ASSERT_FROMV9(env, status == napi_ok, std::make_shared(name, "a number."), version); + return resultSetProxy; +} + +ResultSetProxy *ResultSetProxy::ParseFieldByName( + napi_env env, napi_callback_info info, std::string &field, const std::string name) +{ + napi_value self = nullptr; + size_t argc = 1; + napi_value args[1] = { 0 }; + napi_get_cb_info(env, info, &argc, args, &self, nullptr); + ResultSetProxy *resultSetProxy = nullptr; + napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)); + int version = resultSetProxy->apiversion; + RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), version); + + field = JSUtils::Convert2String(env, args[0]); + RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), std::make_shared(name, "a non empty string."), version); + return resultSetProxy; } napi_value ResultSetProxy::GetAllColumnNames(napi_env env, napi_callback_info info) { std::vector colNames; - int errCode = GetInnerResultSet(env, info)->GetAllColumnNames(colNames); + int version = 0; + int errCode = GetInnerResultSet(env, info, version)->GetAllColumnNames(colNames); if (errCode != E_OK) { - LOG_ERROR("GetAllColumnNames failed code:%{public}d", errCode); + LOG_ERROR("GetAllColumnNames failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, colNames); } @@ -208,26 +271,20 @@ napi_value ResultSetProxy::GetAllColumnNames(napi_env env, napi_callback_info in napi_value ResultSetProxy::GoToRow(napi_env env, napi_callback_info info) { int32_t position; - 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 = GetInnerResultSet(env, info)->GoToRow(position); - if (errCode != E_OK) { - LOG_ERROR("GoToRow failed code:%{public}d", errCode); - } - napi_value output; - napi_get_undefined(env, &output); - return output; + auto resultSetProxy = ParseInt32FieldByName(env, info, position, "position"); + RDB_NAPI_ASSERT_FROMV9( + env, resultSetProxy != nullptr, std::make_shared(), resultSetProxy->apiversion); + int errCode = resultSetProxy->resultSet_->GoToRow(position); + return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GetColumnCount(napi_env env, napi_callback_info info) { int32_t count = 0; - int errCode = GetInnerResultSet(env, info)->GetColumnCount(count); + int version = 0; + int errCode = GetInnerResultSet(env, info, version)->GetColumnCount(count); if (errCode != E_OK) { - LOG_ERROR("GetColumnCount failed code:%{public}d", errCode); + LOG_ERROR("GetColumnCount failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, count); } @@ -236,15 +293,12 @@ napi_value ResultSetProxy::GetLong(napi_env env, napi_callback_info info) { int32_t columnIndex; int64_t result; - 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)); - int errCode = GetInnerResultSet(env, info)->GetLong(columnIndex, result); - if (errCode != E_OK) { - LOG_ERROR("GetLong failed code:%{public}d", errCode); - } + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetLong(columnIndex, result); + int version = resultSetProxy->apiversion; + LOG_INFO("GetLong code:%{public}d, version:%{public}d", errCode, version); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); return JSUtils::Convert2JSValue(env, result); } @@ -252,46 +306,34 @@ napi_value ResultSetProxy::GetColumnType(napi_env env, napi_callback_info info) { int32_t columnIndex; ColumnType columnType; - 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)); - int errCode = GetInnerResultSet(env, info)->GetColumnType(columnIndex, columnType); - if (errCode != E_OK) { - LOG_ERROR("GetColumnType failed code:%{public}d", errCode); - } + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetColumnType(columnIndex, columnType); + int version = resultSetProxy->apiversion; + LOG_INFO("GetColumnType code:%{public}d, version:%{public}d", errCode, version); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); return JSUtils::Convert2JSValue(env, int32_t(columnType)); } napi_value ResultSetProxy::GoTo(napi_env env, napi_callback_info info) { - int32_t columnIndex; - 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)); - int errCode = GetInnerResultSet(env, info)->GoTo(columnIndex); - if (errCode != E_OK) { - LOG_ERROR("GoTo failed code:%{public}d", errCode); - } - napi_value output; - napi_get_undefined(env, &output); - return output; + int32_t offset; + auto resultSetProxy = ParseInt32FieldByName(env, info, offset, "offset"); + RDB_NAPI_ASSERT_FROMV9( + env, resultSetProxy != nullptr, std::make_shared(), resultSetProxy->apiversion); + int errCode = resultSetProxy->resultSet_->GoTo(offset); + return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GetColumnIndex(napi_env env, napi_callback_info info) { + std::string input; int32_t result = -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 input = JSUtils::Convert2String(env, args[0]); - int errCode = GetInnerResultSet(env, info)->GetColumnIndex(input, result); + auto resultSetProxy = ParseFieldByName(env, info, input, "columnName"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetColumnIndex(input, result); if (errCode != E_OK) { - LOG_ERROR("GetColumnIndex failed code:%{public}d", errCode); + LOG_ERROR("GetColumnIndex failed code:%{public}d, version:%{public}d", errCode, resultSetProxy->apiversion); } return JSUtils::Convert2JSValue(env, result); } @@ -300,15 +342,12 @@ napi_value ResultSetProxy::GetInt(napi_env env, napi_callback_info info) { int32_t columnIndex; int32_t result; - 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)); - int errCode = GetInnerResultSet(env, info)->GetInt(columnIndex, result); - if (errCode != E_OK) { - LOG_ERROR("GetInt failed code:%{public}d", errCode); - } + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetInt(columnIndex, result); + int version = resultSetProxy->apiversion; + LOG_INFO("GetInt code:%{public}d, version:%{public}d", errCode, version); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); return JSUtils::Convert2JSValue(env, result); } @@ -316,119 +355,125 @@ napi_value ResultSetProxy::GetColumnName(napi_env env, napi_callback_info info) { int32_t columnIndex; std::string result; - 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)); - int errCode = GetInnerResultSet(env, info)->GetColumnName(columnIndex, result); + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetColumnName(columnIndex, result); if (errCode != E_OK) { - LOG_ERROR("GetColumnName failed code:%{public}d", errCode); + LOG_ERROR("GetColumnName failed code:%{public}d, version:%{public}d", errCode, resultSetProxy->apiversion); } return JSUtils::Convert2JSValue(env, result); } napi_value ResultSetProxy::Close(napi_env env, napi_callback_info info) { - int errCode = GetInnerResultSet(env, info)->Close(); - if (errCode != E_OK) { - LOG_ERROR("Close failed code:%{public}d", errCode); - } - return JSUtils::Convert2JSValue(env, (errCode == E_OK)); + int version; + auto resultSet = GetInnerResultSet(env, info, version); + RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); + int errCode = resultSet->Close(); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); + napi_value result = nullptr; + napi_get_null(env, &result); + return result; } napi_value ResultSetProxy::GetRowCount(napi_env env, napi_callback_info info) { + int version; int32_t result; - int errCode = GetInnerResultSet(env, info)->GetRowCount(result); + int errCode = GetInnerResultSet(env, info, version)->GetRowCount(result); if (errCode != E_OK) { - LOG_ERROR("GetRowCount failed code:%{public}d", errCode); + LOG_ERROR("GetRowCount failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, result); } napi_value ResultSetProxy::GetRowIndex(napi_env env, napi_callback_info info) { + int version; int32_t result; - int errCode = GetInnerResultSet(env, info)->GetRowIndex(result); + int errCode = GetInnerResultSet(env, info, version)->GetRowIndex(result); if (errCode != E_OK) { - LOG_ERROR("GetRowIndex failed code:%{public}d", errCode); + LOG_ERROR("GetRowIndex failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, result); } napi_value ResultSetProxy::IsEnded(napi_env env, napi_callback_info info) { + int version; bool result = false; - int errCode = GetInnerResultSet(env, info)->IsEnded(result); + int errCode = GetInnerResultSet(env, info, version)->IsEnded(result); if (errCode != E_OK) { - LOG_ERROR("IsEnded failed code:%{public}d", errCode); + LOG_ERROR("IsEnded failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, result); } napi_value ResultSetProxy::IsBegin(napi_env env, napi_callback_info info) { + int version; bool result = false; - int errCode = GetInnerResultSet(env, info)->IsStarted(result); + int errCode = GetInnerResultSet(env, info, version)->IsStarted(result); if (errCode != E_OK) { - LOG_ERROR("IsBegin failed code:%{public}d", errCode); + LOG_ERROR("IsBegin failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, result); } napi_value ResultSetProxy::GoToFirstRow(napi_env env, napi_callback_info info) { - int errCode = GetInnerResultSet(env, info)->GoToFirstRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToFirstRow failed code:%{public}d", errCode); - } + int version; + auto resultSet = GetInnerResultSet(env, info, version); + RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); + int errCode = resultSet->GoToFirstRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GoToLastRow(napi_env env, napi_callback_info info) { - int errCode = GetInnerResultSet(env, info)->GoToLastRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToLastRow failed code:%{public}d", errCode); - } + int version; + auto resultSet = GetInnerResultSet(env, info, version); + RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); + int errCode = resultSet->GoToLastRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GoToNextRow(napi_env env, napi_callback_info info) { - int errCode = GetInnerResultSet(env, info)->GoToNextRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToNextRow failed code:%{public}d", errCode); - } + int version; + auto resultSet = GetInnerResultSet(env, info, version); + RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); + int errCode = resultSet->GoToNextRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::GoToPreviousRow(napi_env env, napi_callback_info info) { - int errCode = GetInnerResultSet(env, info)->GoToPreviousRow(); - if (errCode != E_OK) { - LOG_ERROR("GoToPreviousRow failed code:%{public}d", errCode); - } + int version; + auto resultSet = GetInnerResultSet(env, info, version); + RDB_NAPI_ASSERT_FROMV9(env, resultSet != nullptr, std::make_shared(), version); + int errCode = resultSet->GoToPreviousRow(); return JSUtils::Convert2JSValue(env, (errCode == E_OK)); } napi_value ResultSetProxy::IsAtFirstRow(napi_env env, napi_callback_info info) { + int version; bool result = false; - int errCode = GetInnerResultSet(env, info)->IsAtFirstRow(result); + int errCode = GetInnerResultSet(env, info, version)->IsAtFirstRow(result); if (errCode != E_OK) { - LOG_ERROR("IsAtFirstRow failed code:%{public}d", errCode); + LOG_ERROR("IsAtFirstRow failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, result); } napi_value ResultSetProxy::IsAtLastRow(napi_env env, napi_callback_info info) { + int version; bool result = false; - int errCode = GetInnerResultSet(env, info)->IsAtLastRow(result); + int errCode = GetInnerResultSet(env, info, version)->IsAtLastRow(result); if (errCode != E_OK) { - LOG_ERROR("IsAtLastRow failed code:%{public}d", errCode); + LOG_ERROR("IsAtLastRow failed code:%{public}d, version:%{public}d", errCode, version); } return JSUtils::Convert2JSValue(env, result); } @@ -437,15 +482,12 @@ napi_value ResultSetProxy::GetBlob(napi_env env, napi_callback_info info) { int32_t columnIndex; std::vector result; - 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)); - int errCode = GetInnerResultSet(env, info)->GetBlob(columnIndex, result); - if (errCode != E_OK) { - LOG_ERROR("GetBlob failed code:%{public}d", errCode); - } + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetBlob(columnIndex, result); + int version = resultSetProxy->apiversion; + LOG_INFO("GetBlob code:%{public}d, version:%{public}d", errCode, version); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); return JSUtils::Convert2JSValue(env, result); } @@ -453,15 +495,12 @@ napi_value ResultSetProxy::GetString(napi_env env, napi_callback_info info) { int32_t columnIndex; std::string result; - 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)); - int errCode = GetInnerResultSet(env, info)->GetString(columnIndex, result); - if (errCode != E_OK) { - LOG_ERROR("GetString failed code:%{public}d", errCode); - } + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetString(columnIndex, result); + int version = resultSetProxy->apiversion; + LOG_INFO("GetString code:%{public}d, version:%{public}d", errCode, version); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); return JSUtils::Convert2JSValue(env, result); } @@ -469,15 +508,12 @@ napi_value ResultSetProxy::GetDouble(napi_env env, napi_callback_info info) { int32_t columnIndex; double result = 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)); - int errCode = GetInnerResultSet(env, info)->GetDouble(columnIndex, result); - if (errCode != E_OK) { - LOG_ERROR("GetDouble failed code:%{public}d", errCode); - } + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->GetDouble(columnIndex, result); + int version = resultSetProxy->apiversion; + LOG_INFO("GetDouble code:%{public}d, version:%{public}d", errCode, version); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); return JSUtils::Convert2JSValue(env, result); } @@ -485,15 +521,12 @@ napi_value ResultSetProxy::IsColumnNull(napi_env env, napi_callback_info info) { int32_t columnIndex; bool result = false; - 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)); - int errCode = GetInnerResultSet(env, info)->IsColumnNull(columnIndex, result); - if (errCode != E_OK) { - LOG_ERROR("IsColumnNull failed code:%{public}d", errCode); - } + auto resultSetProxy = ParseInt32FieldByName(env, info, columnIndex, "columnIndex"); + RDB_CHECK_RETURN_NULLPTR(resultSetProxy != nullptr); + int errCode = resultSetProxy->resultSet_->IsColumnNull(columnIndex, result); + int version = resultSetProxy->apiversion; + LOG_INFO("IsColumnNull code:%{public}d, version:%{public}d", errCode, version); + RDB_NAPI_ASSERT_FROMV9(env, errCode == E_OK, std::make_shared(), version); napi_value output; napi_get_boolean(env, result, &output); return output; @@ -501,7 +534,8 @@ napi_value ResultSetProxy::IsColumnNull(napi_env env, napi_callback_info info) napi_value ResultSetProxy::IsClosed(napi_env env, napi_callback_info info) { - int result = GetInnerResultSet(env, info)->IsClosed(); + int version; + int result = GetInnerResultSet(env, info, version)->IsClosed(); napi_value output; napi_get_boolean(env, result, &output); return output; diff --git a/relational_store/frameworks/native/rdb/include/hitrace.h b/relational_store/frameworks/native/rdb/include/hitrace.h new file mode 100644 index 0000000000000000000000000000000000000000..d5438557a5ac568deb13c6fdd7ccccd72596273b --- /dev/null +++ b/relational_store/frameworks/native/rdb/include/hitrace.h @@ -0,0 +1,40 @@ +/* + * 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 DISTRIBUTEDDATAMGR_NATIVERDB_HITRACE_H +#define DISTRIBUTEDDATAMGR_NATIVERDB_HITRACE_H + +#include + +#include "hitrace_meter.h" + +namespace OHOS { +namespace NativeRdb { +class HiTrace final { +public: + inline HiTrace(const std::string &value) + { + StartTrace(HITRACE_TAG_DISTRIBUTEDDATA, value); + } + + inline ~HiTrace() + { + FinishTrace(HITRACE_TAG_DISTRIBUTEDDATA); + } +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h index 726d849fbc5c9cc7c96e39f7becfe7394198b31c..722dd43ed0ebb8e733b9675ed7fb3ad9f15d70b9 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h @@ -1,152 +1,150 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NATIVE_RDB_RDB_STORE_IMPL_H -#define NATIVE_RDB_RDB_STORE_IMPL_H - -#include -#include -#include -#include -#include - -#include "rdb_store.h" -#include "rdb_store_config.h" -#include "sqlite_connection_pool.h" -#include "sqlite_statement.h" -#include "store_session.h" -#include "transaction_observer.h" - -namespace OHOS::NativeRdb { -class RdbStoreImpl : public RdbStore, public std::enable_shared_from_this { -public: - static std::shared_ptr Open(const RdbStoreConfig &config, int &errCode); - RdbStoreImpl(); - ~RdbStoreImpl() override; - - int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; - int BatchInsert(int64_t &outInsertNum, const std::string &table, - const std::vector &initialBatchValues) override; - int Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; - int InsertWithConflictResolution(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues, - ConflictResolution conflictResolution) override; - int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, - const std::vector &whereArgs) override; - int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, - const std::string &whereClause, const std::vector &whereArgs, - ConflictResolution conflictResolution) override; - int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, - const std::vector &whereArgs) override; - std::unique_ptr Query(int &errCode, bool distinct, - const std::string &table, const std::vector &columns, - const std::string &selection, const std::vector &selectionArgs, const std::string &groupBy, - const std::string &having, const std::string &orderBy, const std::string &limit) override; - std::unique_ptr QuerySql(const std::string &sql, - const std::vector &selectionArgs) override; - int ExecuteSql(const std::string &sql, const std::vector &bindArgs) override; - int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const std::vector &bindArgs) override; - int ExecuteAndGetString(std::string &outValue, const std::string &sql, - const std::vector &bindArgs) override; - int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs) override; - int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs) override; - int Backup(const std::string databasePath, const std::vector destEncryptKey) override; - int Attach(const std::string &alias, const std::string &pathName, - const std::vector destEncryptKey) override; - int GetVersion(int &version) override; - int SetVersion(int version) override; - int BeginTransaction() override; - int RollBack() override; - int Commit() override; - int MarkAsCommit() override; - int EndTransaction() override; - bool IsInTransaction() override; - std::shared_ptr BeginStepQuery(int &errCode, const std::string sql, - const std::vector &bindArgs); - int EndStepQuery(); - bool IsOpen() const override; - std::string GetPath() override; - bool IsReadOnly() const override; - bool IsMemoryRdb() const override; - int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, - std::vector &columnNames); - bool IsHoldingConnection() override; - int GiveConnectionTemporarily(int64_t milliseconds); - int BeginTransactionWithObserver(TransactionObserver *transactionObserver); -#ifdef RDB_SUPPORT_ICU - int ConfigLocale(const std::string localeStr); -#endif - int Restore(const std::string backupPath, const std::vector &newKey) override; - int ChangeDbFileForRestore(const std::string newPath, const std::string backupPath, - const std::vector &newKey) override; - std::string GetName(); - std::string GetOrgPath(); - std::string GetFileType(); - std::string GetFileSecurityLevel(); - int ExecuteForSharedBlock(int &rowNum, AppDataFwk::SharedBlock *sharedBlock, int startPos, int requiredPos, - bool isCountAllRows, std::string sql, std::vector &bindArgVec); - std::unique_ptr QueryByStep(const std::string &sql, - const std::vector &selectionArgs) override; - - std::unique_ptr Query( - const AbsRdbPredicates &predicates, const std::vector columns) override; - std::unique_ptr QueryByStep( - const AbsRdbPredicates &predicates, const std::vector columns) override; - std::shared_ptr RemoteQuery(const std::string &device, const AbsRdbPredicates &predicates, - const std::vector &columns) override; - int Count(int64_t &outValue, const AbsRdbPredicates &predicates) override; - int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) override; - int Delete(int &deletedRows, const AbsRdbPredicates &predicates) override; - - bool SetDistributedTables(const std::vector& tables) override; - - std::string ObtainDistributedTableName(const std::string& device, const std::string& table) override; - - bool Sync(const SyncOption& option, const AbsRdbPredicates& predicate, const SyncCallback& callback) override; - - bool Subscribe(const SubscribeOption& option, RdbStoreObserver *observer) override; - - bool UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer) override; - - // user must use UDID - bool DropDeviceData(const std::vector& devices, const DropOption& option) override; - -private: - int InnerOpen(const RdbStoreConfig &config); - std::shared_ptr GetThreadSession(); - void ReleaseThreadSession(); - int CheckAttach(const std::string &sql); - - SqliteConnectionPool *connectionPool; - static const int MAX_IDLE_SESSION_SIZE = 5; - std::mutex sessionMutex; - std::map, int>> threadMap; - std::list> idleSessions; - bool isOpen; - std::string path; - std::string orgPath; - bool isReadOnly; - bool isMemoryRdb; - std::string name; - std::string fileSecurityLevel; - std::string fileType; - std::stack transactionObserverStack; - bool isShared_ = false; - DistributedRdb::RdbSyncerParam syncerParam_; - bool isEncrypt_; -}; -} // namespace OHOS::NativeRdb -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_STORE_IMPL_H +#define NATIVE_RDB_RDB_STORE_IMPL_H + +#include +#include +#include +#include +#include + +#include "rdb_store.h" +#include "rdb_store_config.h" +#include "sqlite_connection_pool.h" +#include "sqlite_statement.h" +#include "store_session.h" +#include "transaction_observer.h" + +namespace OHOS::NativeRdb { +class RdbStoreImpl : public RdbStore, public std::enable_shared_from_this { +public: + static std::shared_ptr Open(const RdbStoreConfig &config, int &errCode); + RdbStoreImpl(); + ~RdbStoreImpl() override; + + int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; + int BatchInsert(int64_t &outInsertNum, const std::string &table, + const std::vector &initialBatchValues) override; + int Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; + int InsertWithConflictResolution(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues, + ConflictResolution conflictResolution) override; + int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, + const std::vector &whereArgs) override; + int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &whereArgs, + ConflictResolution conflictResolution) override; + int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &whereArgs) override; + std::unique_ptr Query(int &errCode, bool distinct, + const std::string &table, const std::vector &columns, + const std::string &selection, const std::vector &selectionArgs, const std::string &groupBy, + const std::string &having, const std::string &orderBy, const std::string &limit) override; + std::unique_ptr QuerySql(const std::string &sql, + const std::vector &selectionArgs) override; + int ExecuteSql(const std::string &sql, const std::vector &bindArgs) override; + int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const std::vector &bindArgs) override; + int ExecuteAndGetString(std::string &outValue, const std::string &sql, + const std::vector &bindArgs) override; + int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs) override; + int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs) override; + int Backup(const std::string databasePath, const std::vector destEncryptKey) override; + int Attach(const std::string &alias, const std::string &pathName, + const std::vector destEncryptKey) override; + int GetVersion(int &version) override; + int SetVersion(int version) override; + int BeginTransaction() override; + int RollBack() override; + int Commit() override; + int MarkAsCommit() override; + int EndTransaction() override; + bool IsInTransaction() override; + std::shared_ptr BeginStepQuery(int &errCode, const std::string sql, + const std::vector &bindArgs); + int EndStepQuery(); + bool IsOpen() const override; + std::string GetPath() override; + bool IsReadOnly() const override; + bool IsMemoryRdb() const override; + int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, + std::vector &columnNames); + bool IsHoldingConnection() override; + int GiveConnectionTemporarily(int64_t milliseconds); + int BeginTransactionWithObserver(TransactionObserver *transactionObserver); +#ifdef RDB_SUPPORT_ICU + int ConfigLocale(const std::string localeStr); +#endif + int Restore(const std::string backupPath, const std::vector &newKey) override; + int ChangeDbFileForRestore(const std::string newPath, const std::string backupPath, + const std::vector &newKey) override; + std::string GetName(); + std::string GetOrgPath(); + std::string GetFileType(); + int ExecuteForSharedBlock(int &rowNum, AppDataFwk::SharedBlock *sharedBlock, int startPos, int requiredPos, + bool isCountAllRows, std::string sql, std::vector &bindArgVec); + std::unique_ptr QueryByStep(const std::string &sql, + const std::vector &selectionArgs) override; + + std::unique_ptr Query( + const AbsRdbPredicates &predicates, const std::vector columns) override; + std::unique_ptr QueryByStep( + const AbsRdbPredicates &predicates, const std::vector columns) override; + std::shared_ptr RemoteQuery(const std::string &device, const AbsRdbPredicates &predicates, + const std::vector &columns) override; + int Count(int64_t &outValue, const AbsRdbPredicates &predicates) override; + int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) override; + int Delete(int &deletedRows, const AbsRdbPredicates &predicates) override; + + bool SetDistributedTables(const std::vector& tables) override; + + std::string ObtainDistributedTableName(const std::string& device, const std::string& table) override; + + bool Sync(const SyncOption& option, const AbsRdbPredicates& predicate, const SyncCallback& callback) override; + + bool Subscribe(const SubscribeOption& option, RdbStoreObserver *observer) override; + + bool UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer) override; + + // user must use UDID + bool DropDeviceData(const std::vector& devices, const DropOption& option) override; + +private: + int InnerOpen(const RdbStoreConfig &config); + std::shared_ptr GetThreadSession(); + void ReleaseThreadSession(); + int CheckAttach(const std::string &sql); + + SqliteConnectionPool *connectionPool; + static const int MAX_IDLE_SESSION_SIZE = 5; + std::mutex sessionMutex; + std::map, int>> threadMap; + std::list> idleSessions; + bool isOpen; + std::string path; + std::string orgPath; + bool isReadOnly; + bool isMemoryRdb; + std::string name; + std::string fileType; + std::stack transactionObserverStack; + bool isShared_ = false; + DistributedRdb::RdbSyncerParam syncerParam_; + bool isEncrypt_; +}; +} // namespace OHOS::NativeRdb +#endif diff --git a/relational_store/frameworks/native/rdb/include/rdb_trace.h b/relational_store/frameworks/native/rdb/include/rdb_trace.h index f511f3e9256d0b38e936d21821511104f26e71ce..6a4d9cbbe0e34b1020eb36092cdf299e4a5fe14f 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_trace.h +++ b/relational_store/frameworks/native/rdb/include/rdb_trace.h @@ -1,26 +1,32 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef NATIVE_RDB_RDB_TRACE_H -#define NATIVE_RDB_RDB_TRACE_H - -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -#include "dds_trace.h" -#define DDS_TRACE(...) \ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), ##__VA_ARGS__) -#else -#define DDS_TRACE(...) -#endif - +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NATIVE_RDB_RDB_TRACE_H +#define NATIVE_RDB_RDB_TRACE_H + +#define DO_NOTHING + +#ifdef WINDOWS_PLATFORM +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING + +#elif MAC_PLATFORM +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING + +#else +#include "hitrace.h" +#define DISTRIBUTED_DATA_HITRACE(trace) HiTrace hitrace(trace) + +#endif + #endif \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/include/security_policy.h b/relational_store/frameworks/native/rdb/include/security_policy.h new file mode 100644 index 0000000000000000000000000000000000000000..df1788c07254007017a803675e5022c02cab9815 --- /dev/null +++ b/relational_store/frameworks/native/rdb/include/security_policy.h @@ -0,0 +1,34 @@ +/* +* 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 DISTRIBUTEDDATAMGR_RELATIONAL_STORE_SLAGAIN_SECURITY_POLICY_H +#define DISTRIBUTEDDATAMGR_RELATIONAL_STORE_SLAGAIN_SECURITY_POLICY_H + +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +class SecurityPolicy { +public: + static int SetSecurityLabel(const RdbStoreConfig &config); + +private: + static std::string GetSecurityLevelValue(SecurityLevel securityLevel); + static int SetFileSecurityLevel(const std::string &filePath, const std::string &securityLevel); + static std::string GetFileSecurityLevel(const std::string &filePath); +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/frameworks/native/rdb/include/sqlite_config.h b/relational_store/frameworks/native/rdb/include/sqlite_config.h index a85b72b49afa9f967e3b56f8a67d3691c5f2a6c6..b90d31d197cca052ac1ac2f132885eb6a7cd0ec2 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_config.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_config.h @@ -1,61 +1,71 @@ -/* - * 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_RDB_SQLITE_CONFIG_H -#define NATIVE_RDB_SQLITE_CONFIG_H - -#include -#include - -#include "rdb_store_config.h" - -namespace OHOS { -namespace NativeRdb { - -class SqliteConfig { -public: - explicit SqliteConfig(const RdbStoreConfig &config); - ~SqliteConfig(); - std::string GetPath() const; - void SetPath(std::string newPath); - StorageMode GetStorageMode() const; - std::string GetJournalMode() const; - std::string GetSyncMode() const; - std::string GetDatabaseFileType() const; - bool IsReadOnly() const; - bool IsEncrypt() const; - std::string GetBundleName() const; - int32_t GetSecurityLevel() const; - bool IsCreateNecessary() const; - void SetCreateNecessary(bool CreateNecessary); - -private: - std::string path; - StorageMode storageMode; - std::string journalMode; - std::string syncMode; - bool readOnly; - std::string databaseFileType; - - // Encryption - bool isEncrypt = false; - std::string bundleName; - int32_t securityLevel = 0; - bool isCreateNecessary; -}; - -} // namespace NativeRdb -} // namespace OHOS -#endif +/* + * 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_RDB_SQLITE_CONFIG_H +#define NATIVE_RDB_SQLITE_CONFIG_H + +#include +#include + +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { + +class SqliteConfig { +public: + explicit SqliteConfig(const RdbStoreConfig &config); + ~SqliteConfig(); + std::string GetPath() const; + void SetPath(std::string newPath); + StorageMode GetStorageMode() const; + std::string GetJournalMode() const; + std::string GetSyncMode() const; + std::string GetDatabaseFileType() const; + bool IsReadOnly() const; + bool IsEncrypt() const; + std::string GetBundleName() const; + bool IsCreateNecessary() const; + void SetCreateNecessary(bool CreateNecessary); + bool IsAutoCheck() const; + void SetAutoCheck(bool autoCheck); + int GetJournalSize() const; + void SetJournalSize(int journalSize); + int GetPageSize() const; + void SetPageSize(int pageSize); + std::string GetEncryptAlgo() const; + void SetEncryptAlgo(const std::string &encryptAlgo); + +private: + std::string path; + StorageMode storageMode; + std::string journalMode; + std::string syncMode; + bool autoCheck; + int journalSize; + int pageSize; + std::string encryptAlgo; + bool readOnly; + std::string databaseFileType; + + // Encryption + bool isEncrypt = false; + std::string bundleName; + bool isCreateNecessary; +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/frameworks/native/rdb/include/sqlite_connection.h b/relational_store/frameworks/native/rdb/include/sqlite_connection.h index dcbd116e11cc76e2030c2bdc232c83e8fe4abbdd..05a9aeb3d20a906709fcf0016acb56a0b7919f0f 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_connection.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_connection.h @@ -1,92 +1,91 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NATIVE_RDB_SQLITE_CONNECTION_H -#define NATIVE_RDB_SQLITE_CONNECTION_H - -#include -#include -#include - -#include "sqlite3sym.h" -#include "sqlite_config.h" -#include "sqlite_statement.h" -#include "value_object.h" -#include "shared_block.h" - -namespace OHOS { -namespace NativeRdb { - -class SqliteConnection { -public: - static SqliteConnection *Open(const SqliteConfig &config, bool isWriteConnection, int &errCode); - ~SqliteConnection(); - bool IsWriteConnection() const; - int Prepare(const std::string &sql, bool &outIsReadOnly); - int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, - std::vector &columnNames); - int ExecuteSql(const std::string &sql, const std::vector &bindArgs = std::vector()); - int ExecuteForChangedRowCount(int &changedRows, const std::string &sql, const std::vector &bindArgs); - int ExecuteForLastInsertedRowId(int64_t &outRowId, const std::string &sql, - const std::vector &bindArgs); - int ExecuteGetLong(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()); - int ExecuteGetString(std::string &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()); - std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, - const std::vector &selectionArgs) const; - int EndStepQuery(); -#ifdef RDB_SUPPORT_ICU - int ConfigLocale(const std::string localeStr); -#endif - int ExecuteForSharedBlock(int &rowNum, std::string sql, const std::vector &bindArgs, - AppDataFwk::SharedBlock *sharedBlock, int startPos, int requiredPos, bool isCountAllRows); - -private: - explicit SqliteConnection(bool isWriteConnection); - int InnerOpen(const SqliteConfig &config); - int Config(const SqliteConfig &config); - int SetPageSize(); - int SetEncryptAlgo(); - int SetEncryptKey(const std::vector &encryptKey); - int SetJournalMode(const std::string &journalMode, const std::string &synclMode); - int SetJournalSizeLimit(); - int SetAutoCheckpoint(); - int SetWalSyncMode(const std::string &syncMode); - int PrepareAndBind(const std::string &sql, const std::vector &bindArgs); - void LimitPermission(const std::string &dbPath) const; - int ManageKey(const SqliteConfig &config); - int InitKey(); - int GetKeyFromFile(); - - int SetPersistWal(); - int SetBusyTimeout(int timeout); - int SetSecurityLabel(const std::string &dbPath, const SqliteConfig &config, const bool &isDbFileExist); - - sqlite3 *dbHandle; - bool isWriteConnection; - bool isReadOnly; - SqliteStatement statement; - std::shared_ptr stepStatement; - std::string filePath; - int openFlags; - std::mutex rdbMutex; - - static constexpr int DEFAULT_BUSY_TIMEOUT_MS = 2000; -}; - -} // namespace NativeRdb -} // namespace OHOS -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_SQLITE_CONNECTION_H +#define NATIVE_RDB_SQLITE_CONNECTION_H + +#include +#include +#include + +#include "sqlite3sym.h" +#include "sqlite_config.h" +#include "sqlite_statement.h" +#include "value_object.h" +#include "shared_block.h" + +namespace OHOS { +namespace NativeRdb { + +class SqliteConnection { +public: + static SqliteConnection *Open(const SqliteConfig &config, bool isWriteConnection, int &errCode); + ~SqliteConnection(); + bool IsWriteConnection() const; + int Prepare(const std::string &sql, bool &outIsReadOnly); + int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, + std::vector &columnNames); + int ExecuteSql(const std::string &sql, const std::vector &bindArgs = std::vector()); + int ExecuteForChangedRowCount(int &changedRows, const std::string &sql, const std::vector &bindArgs); + int ExecuteForLastInsertedRowId(int64_t &outRowId, const std::string &sql, + const std::vector &bindArgs); + int ExecuteGetLong(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()); + int ExecuteGetString(std::string &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()); + std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, + const std::vector &selectionArgs) const; + int EndStepQuery(); +#ifdef RDB_SUPPORT_ICU + int ConfigLocale(const std::string localeStr); +#endif + int ExecuteForSharedBlock(int &rowNum, std::string sql, const std::vector &bindArgs, + AppDataFwk::SharedBlock *sharedBlock, int startPos, int requiredPos, bool isCountAllRows); + +private: + explicit SqliteConnection(bool isWriteConnection); + int InnerOpen(const SqliteConfig &config); + int Config(const SqliteConfig &config); + int SetPageSize(const SqliteConfig &config); + int SetEncryptAlgo(const SqliteConfig &config); + int SetEncryptKey(const std::vector &encryptKey); + int SetJournalMode(const SqliteConfig &config); + int SetJournalSizeLimit(const SqliteConfig &config); + int SetAutoCheckpoint(const SqliteConfig &config); + int SetWalSyncMode(const std::string &syncMode); + int PrepareAndBind(const std::string &sql, const std::vector &bindArgs); + void LimitPermission(const std::string &dbPath) const; + int ManageKey(const SqliteConfig &config); + int InitKey(); + int GetKeyFromFile(); + + int SetPersistWal(); + int SetBusyTimeout(int timeout); + + sqlite3 *dbHandle; + bool isWriteConnection; + bool isReadOnly; + SqliteStatement statement; + std::shared_ptr stepStatement; + std::string filePath; + int openFlags; + std::mutex rdbMutex; + + static constexpr int DEFAULT_BUSY_TIMEOUT_MS = 2000; +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/frameworks/native/rdb/include/sqlite_global_config.h b/relational_store/frameworks/native/rdb/include/sqlite_global_config.h index 6b906902e9757f3489b8320a08fceabdc8bf669c..2e8bca1ca8b78f53cf79a67a5a13433a31c4c2ab 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_global_config.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_global_config.h @@ -1,53 +1,76 @@ -/* - * 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_RDB_SQLITE_GLOBAL_CONFIG_H -#define NATIVE_RDB_SQLITE_GLOBAL_CONFIG_H - -#include - -namespace OHOS { -namespace NativeRdb { - -class SqliteGlobalConfig { -public: - SqliteGlobalConfig(); - ~SqliteGlobalConfig(); - static void InitSqliteGlobalConfig(); - static void SqliteLogCallback(const void *data, int err, const char *msg); - static int GetReadConnectionCount(); - static std::string GetMemoryDbPath(); - static int GetPageSize(); - static std::string GetWalSyncMode(); - static int GetJournalFileSize(); - static int GetWalAutoCheckpoint(); - static std::string GetDefaultJournalMode(); - -private: - static const int SOFT_HEAP_LIMIT; - static const bool CALLBACK_LOG_SWITCH; - static const int CONNECTION_POOL_SIZE; - static const std::string MEMORY_DB_PATH; - static const int DB_PAGE_SIZE; - static const std::string DEFAULT_JOURNAL_MODE; - static const std::string WAL_SYNC_MODE; - static const int JOURNAL_FILE_SIZE; - static const int WAL_AUTO_CHECKPOINT; -}; - -} // namespace NativeRdb -} // namespace OHOS - -#endif +/* + * 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_RDB_SQLITE_GLOBAL_CONFIG_H +#define NATIVE_RDB_SQLITE_GLOBAL_CONFIG_H + +#include + +namespace OHOS { +namespace NativeRdb { + +class GlobalExpr { +public: + static constexpr bool CALLBACK_LOG_SWITCH = true; /* Sqlite callback log switch */ + static constexpr bool DB_AUTO_CHECK = false; /* Sqlite callback log switch */ + static constexpr int SOFT_HEAP_LIMIT = 8 * 1024 * 1024; /* 8MB */ + static constexpr int CONNECTION_POOL_SIZE = 4; + static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ + static constexpr int DB_JOURNAL_SIZE = 1048576; /* default file size : 1M */ + static constexpr int WAL_AUTO_CHECKPOINT = 100; /* 100 pages */ + static constexpr int APP_DEFAULT_UMASK = 0002; + static constexpr char ATTACH_BACKUP_SQL[] = "ATTACH ? AS backup KEY ?"; + static constexpr char ATTACH_SQL[] = "ATTACH ? AS ? KEY ?"; + static constexpr char EXPORT_SQL[] = "SELECT export_database('backup')"; + static constexpr char DETACH_BACKUP_SQL[] = "detach backup"; + static constexpr char PRAGMA_JOUR_MODE_EXP[] = "PRAGMA journal_mode"; + static constexpr char PRAGMA_VERSION[] = "PRAGMA user_version"; + static constexpr char DEFAULT_JOURNAL_MODE[] = "WAL"; + static constexpr char DB_DEFAULT_JOURNAL_MODE[] = "DELETE"; + static constexpr char WAL_SYNC_MODE[] = "FULL"; + static constexpr char MEMORY_DB_PATH[] = ":memory:"; + static constexpr char ENCRYPT_ALGO[] = "sha256"; +}; + +class SqliteGlobalConfig { +public: + SqliteGlobalConfig(); + ~SqliteGlobalConfig(); + static void InitSqliteGlobalConfig(); + static void SqliteLogCallback(const void *data, int err, const char *msg); + static int GetReadConnectionCount(); + static std::string GetMemoryDbPath(); + static int GetPageSize(); + static std::string GetWalSyncMode(); + static int GetJournalFileSize(); + static int GetWalAutoCheckpoint(); + static std::string GetDefaultJournalMode(); + +private: + static const int SOFT_HEAP_LIMIT; + static const bool CALLBACK_LOG_SWITCH; + static const int CONNECTION_POOL_SIZE; + static const std::string MEMORY_DB_PATH; + static const int DB_PAGE_SIZE; + static const std::string DEFAULT_JOURNAL_MODE; + static const std::string WAL_SYNC_MODE; + static const int JOURNAL_FILE_SIZE; + static const int WAL_AUTO_CHECKPOINT; +}; + +} // namespace NativeRdb +} // namespace OHOS + +#endif diff --git a/relational_store/frameworks/native/rdb/include/sqlite_utils.h b/relational_store/frameworks/native/rdb/include/sqlite_utils.h index 5a55e7f6ec779fa188eeeaa9018db66de9337833..cb7b1c4efc9dfef986289baa1dd7e732e0bbcb13 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_utils.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_utils.h @@ -1,57 +1,54 @@ -/* - * 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_RDB_SQLITE_UTILS_H -#define NATIVE_RDB_SQLITE_UTILS_H - -#include -#include - -namespace OHOS { -namespace NativeRdb { - -class SqliteUtils { -public: - static const int STATEMENT_SELECT; - static const int STATEMENT_UPDATE; - static const int STATEMENT_ATTACH; - static const int STATEMENT_DETACH; - static const int STATEMENT_BEGIN; - static const int STATEMENT_COMMIT; - static const int STATEMENT_ROLLBACK; - static const int STATEMENT_PRAGMA; - static const int STATEMENT_DDL; - static const int STATEMENT_OTHER; - static const int CONFLICT_CLAUSE_COUNT = 6; - static const std::string DATA_LEVEL[]; - - static int GetSqlStatementType(const std::string &sql); - static bool IsSqlReadOnly(int sqlType); - static bool IsSpecial(int sqlType); - static int GetConflictClause(int conflictResolution, std::string &conflictClause); - static std::string StrToUpper(std::string s); - static bool DeleteFile(const std::string path); - static int RenameFile(const std::string srcFile, const std::string destFile); - static int SetFileSecurityLevel(const std::string &filePath, const int32_t &securityLevel); - static std::string GetFileSecurityLevel(const std::string &filePath); - -private: - static const std::map SQL_TYPE_MAP; - static const std::string ON_CONFLICT_CLAUSE[CONFLICT_CLAUSE_COUNT]; -}; - -} // namespace NativeRdb -} // namespace OHOS +/* + * 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_RDB_SQLITE_UTILS_H +#define NATIVE_RDB_SQLITE_UTILS_H + +#include +#include + +namespace OHOS { +namespace NativeRdb { + +class SqliteUtils { +public: + static const int STATEMENT_SELECT; + static const int STATEMENT_UPDATE; + static const int STATEMENT_ATTACH; + static const int STATEMENT_DETACH; + static const int STATEMENT_BEGIN; + static const int STATEMENT_COMMIT; + static const int STATEMENT_ROLLBACK; + static const int STATEMENT_PRAGMA; + static const int STATEMENT_DDL; + static const int STATEMENT_OTHER; + static const int CONFLICT_CLAUSE_COUNT = 6; + + static int GetSqlStatementType(const std::string &sql); + static bool IsSqlReadOnly(int sqlType); + static bool IsSpecial(int sqlType); + static int GetConflictClause(int conflictResolution, std::string &conflictClause); + static std::string StrToUpper(std::string s); + static bool DeleteFile(const std::string path); + static int RenameFile(const std::string srcFile, const std::string destFile); + +private: + static const std::map SQL_TYPE_MAP; + static const std::string ON_CONFLICT_CLAUSE[CONFLICT_CLAUSE_COUNT]; +}; + +} // namespace NativeRdb +} // namespace OHOS #endif \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h b/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h index 82d2f597ef78968a1f5022e51a744caa765df796..13b76ded8941ec696ce7ea022c9f98dd52fd91eb 100644 --- a/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/mock/include/rdb_store_impl.h @@ -1,127 +1,125 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NATIVE_RDB_RDB_STORE_IMPL_H -#define NATIVE_RDB_RDB_STORE_IMPL_H - -#include -#include -#include -#include -#include - -#include "rdb_store.h" -#include "rdb_store_config.h" -#include "sqlite_connection_pool.h" -#include "sqlite_statement.h" -#include "store_session.h" -#include "transaction_observer.h" - -namespace OHOS::NativeRdb { -class RdbStoreImpl : public RdbStore, public std::enable_shared_from_this { -public: - static std::shared_ptr Open(const RdbStoreConfig &config, int &errCode); - RdbStoreImpl(); - ~RdbStoreImpl() override; -#ifdef WINDOWS_PLATFORM - void Clear() override; -#endif - int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; - int BatchInsert(int64_t &outInsertNum, const std::string &table, - const std::vector &initialBatchValues) override; - int Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; - int InsertWithConflictResolution(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues, - ConflictResolution conflictResolution) override; - int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, - const std::vector &whereArgs) override; - int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, - const std::string &whereClause, const std::vector &whereArgs, - ConflictResolution conflictResolution) override; - int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, - const std::vector &whereArgs) override; - int ExecuteSql(const std::string &sql, const std::vector &bindArgs) override; - int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const std::vector &bindArgs) override; - int ExecuteAndGetString(std::string &outValue, const std::string &sql, - const std::vector &bindArgs) override; - int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs) override; - int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs) override; - int Backup(const std::string databasePath, const std::vector destEncryptKey) override; - int Attach(const std::string &alias, const std::string &pathName, - const std::vector destEncryptKey) override; - int GetVersion(int &version) override; - int SetVersion(int version) override; - int BeginTransaction() override; - int RollBack() override; - int Commit() override; - int MarkAsCommit() override; - int EndTransaction() override; - bool IsInTransaction() override; - std::shared_ptr BeginStepQuery(int &errCode, const std::string sql, - const std::vector &bindArgs); - int EndStepQuery(); - bool IsOpen() const override; - std::string GetPath() override; - bool IsReadOnly() const override; - bool IsMemoryRdb() const override; - int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, - std::vector &columnNames); - bool IsHoldingConnection() override; - int GiveConnectionTemporarily(int64_t milliseconds); - int BeginTransactionWithObserver(TransactionObserver *transactionObserver); -#ifdef RDB_SUPPORT_ICU - int ConfigLocale(const std::string localeStr); -#endif - int Restore(const std::string backupPath, const std::vector &newKey) override; - int ChangeDbFileForRestore(const std::string newPath, const std::string backupPath, - const std::vector &newKey) override; - std::string GetName(); - std::string GetOrgPath(); - std::string GetFileType(); - std::string GetFileSecurityLevel(); - std::unique_ptr QueryByStep(const std::string &sql, - const std::vector &selectionArgs) override; - std::unique_ptr Query( - const AbsRdbPredicates &predicates, const std::vector columns) override; - int Count(int64_t &outValue, const AbsRdbPredicates &predicates) override; - int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) override; - int Delete(int &deletedRows, const AbsRdbPredicates &predicates) override; - -private: - int InnerOpen(const RdbStoreConfig &config); - std::shared_ptr GetThreadSession(); - void ReleaseThreadSession(); - int CheckAttach(const std::string &sql); - std::string ExtractFilePath(const std::string& fileFullName); - bool PathToRealPath(const std::string& path, std::string& realPath); - - SqliteConnectionPool *connectionPool; - static const int MAX_IDLE_SESSION_SIZE = 5; - std::mutex sessionMutex; - std::map, int>> threadMap; - std::list> idleSessions; - bool isOpen; - std::string path; - std::string orgPath; - bool isReadOnly; - bool isMemoryRdb; - std::string name; - std::string fileSecurityLevel; - std::string fileType; - std::stack transactionObserverStack; -}; -} // namespace OHOS::NativeRdb -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_STORE_IMPL_H +#define NATIVE_RDB_RDB_STORE_IMPL_H + +#include +#include +#include +#include +#include + +#include "rdb_store.h" +#include "rdb_store_config.h" +#include "sqlite_connection_pool.h" +#include "sqlite_statement.h" +#include "store_session.h" +#include "transaction_observer.h" + +namespace OHOS::NativeRdb { +class RdbStoreImpl : public RdbStore, public std::enable_shared_from_this { +public: + static std::shared_ptr Open(const RdbStoreConfig &config, int &errCode); + RdbStoreImpl(); + ~RdbStoreImpl() override; +#ifdef WINDOWS_PLATFORM + void Clear() override; +#endif + int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; + int BatchInsert(int64_t &outInsertNum, const std::string &table, + const std::vector &initialBatchValues) override; + int Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) override; + int InsertWithConflictResolution(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues, + ConflictResolution conflictResolution) override; + int Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, + const std::vector &whereArgs) override; + int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause, const std::vector &whereArgs, + ConflictResolution conflictResolution) override; + int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, + const std::vector &whereArgs) override; + int ExecuteSql(const std::string &sql, const std::vector &bindArgs) override; + int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const std::vector &bindArgs) override; + int ExecuteAndGetString(std::string &outValue, const std::string &sql, + const std::vector &bindArgs) override; + int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs) override; + int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs) override; + int Backup(const std::string databasePath, const std::vector destEncryptKey) override; + int Attach(const std::string &alias, const std::string &pathName, + const std::vector destEncryptKey) override; + int GetVersion(int &version) override; + int SetVersion(int version) override; + int BeginTransaction() override; + int RollBack() override; + int Commit() override; + int MarkAsCommit() override; + int EndTransaction() override; + bool IsInTransaction() override; + std::shared_ptr BeginStepQuery(int &errCode, const std::string sql, + const std::vector &bindArgs); + int EndStepQuery(); + bool IsOpen() const override; + std::string GetPath() override; + bool IsReadOnly() const override; + bool IsMemoryRdb() const override; + int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, + std::vector &columnNames); + bool IsHoldingConnection() override; + int GiveConnectionTemporarily(int64_t milliseconds); + int BeginTransactionWithObserver(TransactionObserver *transactionObserver); +#ifdef RDB_SUPPORT_ICU + int ConfigLocale(const std::string localeStr); +#endif + int Restore(const std::string backupPath, const std::vector &newKey) override; + int ChangeDbFileForRestore(const std::string newPath, const std::string backupPath, + const std::vector &newKey) override; + std::string GetName(); + std::string GetOrgPath(); + std::string GetFileType(); + std::unique_ptr QueryByStep(const std::string &sql, + const std::vector &selectionArgs) override; + std::unique_ptr Query( + const AbsRdbPredicates &predicates, const std::vector columns) override; + int Count(int64_t &outValue, const AbsRdbPredicates &predicates) override; + int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) override; + int Delete(int &deletedRows, const AbsRdbPredicates &predicates) override; + +private: + int InnerOpen(const RdbStoreConfig &config); + std::shared_ptr GetThreadSession(); + void ReleaseThreadSession(); + int CheckAttach(const std::string &sql); + std::string ExtractFilePath(const std::string& fileFullName); + bool PathToRealPath(const std::string& path, std::string& realPath); + + SqliteConnectionPool *connectionPool; + static const int MAX_IDLE_SESSION_SIZE = 5; + std::mutex sessionMutex; + std::map, int>> threadMap; + std::list> idleSessions; + bool isOpen; + std::string path; + std::string orgPath; + bool isReadOnly; + bool isMemoryRdb; + std::string name; + std::string fileType; + std::stack transactionObserverStack; +}; +} // namespace OHOS::NativeRdb +#endif diff --git a/relational_store/frameworks/native/rdb/mock/include/rdb_trace.h b/relational_store/frameworks/native/rdb/mock/include/rdb_trace.h index f511f3e9256d0b38e936d21821511104f26e71ce..6a4d9cbbe0e34b1020eb36092cdf299e4a5fe14f 100644 --- a/relational_store/frameworks/native/rdb/mock/include/rdb_trace.h +++ b/relational_store/frameworks/native/rdb/mock/include/rdb_trace.h @@ -1,26 +1,32 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef NATIVE_RDB_RDB_TRACE_H -#define NATIVE_RDB_RDB_TRACE_H - -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -#include "dds_trace.h" -#define DDS_TRACE(...) \ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), ##__VA_ARGS__) -#else -#define DDS_TRACE(...) -#endif - +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NATIVE_RDB_RDB_TRACE_H +#define NATIVE_RDB_RDB_TRACE_H + +#define DO_NOTHING + +#ifdef WINDOWS_PLATFORM +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING + +#elif MAC_PLATFORM +#define DISTRIBUTED_DATA_HITRACE(trace) DO_NOTHING + +#else +#include "hitrace.h" +#define DISTRIBUTED_DATA_HITRACE(trace) HiTrace hitrace(trace) + +#endif + #endif \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_config.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_config.h index 49f7371f3e391c0007d25d30f4d14115d6d8a335..1ca89ead8554e806cbc7701353f93866736f60f5 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_config.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_config.h @@ -1,60 +1,69 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NATIVE_RDB_SQLITE_CONFIG_H -#define NATIVE_RDB_SQLITE_CONFIG_H - -#include -#include - -#include "rdb_store_config.h" - -namespace OHOS { -namespace NativeRdb { -class SqliteConfig { -public: - explicit SqliteConfig(const RdbStoreConfig &config); - ~SqliteConfig(); - std::string GetPath() const; - void SetPath(std::string newPath); - StorageMode GetStorageMode() const; - std::string GetJournalMode() const; - std::string GetSyncMode() const; - std::string GetDatabaseFileType() const; - bool IsReadOnly() const; - bool IsEncrypted() const; - bool IsInitEncrypted() const; - std::vector GetEncryptKey() const; - void UpdateEncryptKey(const std::vector &newKey); - void ClearEncryptKey(); - int32_t GetSecurityLevel() const; - bool IsCreateNecessary() const; - void SetCreateNecessary(bool CreateNecessary); - -private: - std::string path; - StorageMode storageMode; - std::string journalMode; - std::string syncMode; - bool readOnly; - bool encrypted; - bool initEncrypted; - std::string databaseFileType; - std::vector encryptKey; - int32_t securityLevel = 0; -}; -} // namespace NativeRdb -} // namespace OHOS -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_SQLITE_CONFIG_H +#define NATIVE_RDB_SQLITE_CONFIG_H + +#include +#include + +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +class SqliteConfig { +public: + explicit SqliteConfig(const RdbStoreConfig &config); + ~SqliteConfig(); + std::string GetPath() const; + void SetPath(std::string newPath); + StorageMode GetStorageMode() const; + std::string GetJournalMode() const; + std::string GetSyncMode() const; + std::string GetDatabaseFileType() const; + bool IsReadOnly() const; + bool IsEncrypted() const; + bool IsInitEncrypted() const; + std::vector GetEncryptKey() const; + void UpdateEncryptKey(const std::vector &newKey); + void ClearEncryptKey(); + bool IsCreateNecessary() const; + void SetCreateNecessary(bool CreateNecessary); + bool IsAutoCheck() const; + void SetAutoCheck(bool autoCheck); + int GetJournalSize() const; + void SetJournalSize(int journalSize); + int GetPageSize() const; + void SetPageSize(int pageSize); + std::string GetEncryptAlgo() const; + void SetEncryptAlgo(const std::string &encryptAlgo); +private: + std::string path; + StorageMode storageMode; + std::string journalMode; + std::string syncMode; + bool autoCheck; + int journalSize; + int pageSize; + std::string encryptAlgo; + bool readOnly; + bool encrypted; + bool initEncrypted; + std::string databaseFileType; + std::vector encryptKey; +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h index 77c5862264c94facc26006f760f94c0b85f55d6c..ab7349fbd9096b9018b34a183c1a2f84c8f131d8 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_connection.h @@ -1,83 +1,83 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NATIVE_RDB_SQLITE_CONNECTION_H -#define NATIVE_RDB_SQLITE_CONNECTION_H - -#include -#include -#include - -#include "sqlite3sym.h" -#include "sqlite_config.h" -#include "sqlite_statement.h" -#include "value_object.h" - -namespace OHOS { -namespace NativeRdb { -class SqliteConnection { -public: - static SqliteConnection *Open(const SqliteConfig &config, bool isWriteConnection, int &errCode); - ~SqliteConnection(); - bool IsWriteConnection() const; - int Prepare(const std::string &sql, bool &outIsReadOnly); - int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, - std::vector &columnNames); - int ExecuteSql(const std::string &sql, const std::vector &bindArgs = std::vector()); - int ExecuteForChangedRowCount(int &changedRows, const std::string &sql, const std::vector &bindArgs); - int ExecuteForLastInsertedRowId(int64_t &outRowId, const std::string &sql, - const std::vector &bindArgs); - int ExecuteGetLong(int64_t &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()); - int ExecuteGetString(std::string &outValue, const std::string &sql, - const std::vector &bindArgs = std::vector()); - std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, - const std::vector &selectionArgs) const; - int EndStepQuery(); -#ifdef RDB_SUPPORT_ICU - int ConfigLocale(const std::string localeStr); -#endif - -private: - explicit SqliteConnection(bool isWriteConnection); - int InnerOpen(const SqliteConfig &config); - int Config(const SqliteConfig &config); - int SetPageSize(); - int SetEncryptAlgo(); - int SetEncryptKey(const std::vector &encryptKey); - int SetJournalMode(const std::string &journalMode, const std::string &synclMode); - int SetJournalSizeLimit(); - int SetAutoCheckpoint(); - int SetWalSyncMode(const std::string &syncMode); - int PrepareAndBind(const std::string &sql, const std::vector &bindArgs); - void LimitPermission(const std::string &dbPath) const; - - int SetPersistWal(); - int SetBusyTimeout(int timeout); - - sqlite3 *dbHandle; - bool isWriteConnection; - bool isReadOnly; - SqliteStatement statement; - std::shared_ptr stepStatement; - std::string filePath; - int openFlags; - std::mutex rdbMutex; - - static constexpr int DEFAULT_BUSY_TIMEOUT_MS = 2000; -}; -} // namespace NativeRdb -} // namespace OHOS -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_SQLITE_CONNECTION_H +#define NATIVE_RDB_SQLITE_CONNECTION_H + +#include +#include +#include + +#include "sqlite3sym.h" +#include "sqlite_config.h" +#include "sqlite_statement.h" +#include "value_object.h" + +namespace OHOS { +namespace NativeRdb { +class SqliteConnection { +public: + static SqliteConnection *Open(const SqliteConfig &config, bool isWriteConnection, int &errCode); + ~SqliteConnection(); + bool IsWriteConnection() const; + int Prepare(const std::string &sql, bool &outIsReadOnly); + int PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, + std::vector &columnNames); + int ExecuteSql(const std::string &sql, const std::vector &bindArgs = std::vector()); + int ExecuteForChangedRowCount(int &changedRows, const std::string &sql, const std::vector &bindArgs); + int ExecuteForLastInsertedRowId(int64_t &outRowId, const std::string &sql, + const std::vector &bindArgs); + int ExecuteGetLong(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()); + int ExecuteGetString(std::string &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()); + std::shared_ptr BeginStepQuery(int &errCode, const std::string &sql, + const std::vector &selectionArgs) const; + int EndStepQuery(); +#ifdef RDB_SUPPORT_ICU + int ConfigLocale(const std::string localeStr); +#endif + +private: + explicit SqliteConnection(bool isWriteConnection); + int InnerOpen(const SqliteConfig &config); + int Config(const SqliteConfig &config); + int SetPageSize(const SqliteConfig &config); + int SetEncryptAlgo(const SqliteConfig &config); + int SetEncryptKey(const std::vector &encryptKey); + int SetJournalMode(const SqliteConfig &config); + int SetJournalSizeLimit(const SqliteConfig &config); + int SetAutoCheckpoint(const SqliteConfig &config); + int SetWalSyncMode(const std::string &syncMode); + int PrepareAndBind(const std::string &sql, const std::vector &bindArgs); + void LimitPermission(const std::string &dbPath) const; + + int SetPersistWal(); + int SetBusyTimeout(int timeout); + + sqlite3 *dbHandle; + bool isWriteConnection; + bool isReadOnly; + SqliteStatement statement; + std::shared_ptr stepStatement; + std::string filePath; + int openFlags; + std::mutex rdbMutex; + + static constexpr int DEFAULT_BUSY_TIMEOUT_MS = 2000; +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h index 970cda8728c67485a805a5392759d94bbf7185f6..ec40ea20c01527a94cd6775dbc7005f5db2ed906 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h @@ -1,50 +1,74 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NATIVE_RDB_SQLITE_GLOBAL_CONFIG_H -#define NATIVE_RDB_SQLITE_GLOBAL_CONFIG_H - -#include - -namespace OHOS { -namespace NativeRdb { -class SqliteGlobalConfig { -public: - SqliteGlobalConfig(); - ~SqliteGlobalConfig(); - static void InitSqliteGlobalConfig(); - static void SqliteLogCallback(const void *data, int err, const char *msg); - static int GetReadConnectionCount(); - static std::string GetMemoryDbPath(); - static int GetPageSize(); - static std::string GetWalSyncMode(); - static int GetJournalFileSize(); - static int GetWalAutoCheckpoint(); - static std::string GetDefaultJournalMode(); - -private: - static const int SOFT_HEAP_LIMIT; - static const bool CALLBACK_LOG_SWITCH; - static const int CONNECTION_POOL_SIZE; - static const std::string MEMORY_DB_PATH; - static const int DB_PAGE_SIZE; - static const std::string DEFAULT_JOURNAL_MODE; - static const std::string WAL_SYNC_MODE; - static const int JOURNAL_FILE_SIZE; - static const int WAL_AUTO_CHECKPOINT; -}; -} // namespace NativeRdb -} // namespace OHOS -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_SQLITE_GLOBAL_CONFIG_H +#define NATIVE_RDB_SQLITE_GLOBAL_CONFIG_H + +#include + +namespace OHOS { +namespace NativeRdb { + +class GlobalExpr { +public: + static constexpr bool CALLBACK_LOG_SWITCH = true; /* Sqlite callback log switch */ + static constexpr bool DB_AUTO_CHECK = false; /* Sqlite callback log switch */ + static constexpr int SOFT_HEAP_LIMIT = 8 * 1024 * 1024; /* 8MB */ + static constexpr int CONNECTION_POOL_SIZE = 4; + static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ + static constexpr int DB_JOURNAL_SIZE = 1048576; /* default file size : 1M */ + static constexpr int WAL_AUTO_CHECKPOINT = 100; /* 100 pages */ + static constexpr int APP_DEFAULT_UMASK = 0002; + static constexpr char ATTACH_BACKUP_SQL[] = "ATTACH ? AS backup KEY ?"; + static constexpr char ATTACH_SQL[] = "ATTACH ? AS ? KEY ?"; + static constexpr char EXPORT_SQL[] = "SELECT export_database('backup')"; + static constexpr char DETACH_BACKUP_SQL[] = "detach backup"; + static constexpr char PRAGMA_JOUR_MODE_EXP[] = "PRAGMA journal_mode"; + static constexpr char PRAGMA_VERSION[] = "PRAGMA user_version"; + static constexpr char DEFAULT_JOURNAL_MODE[] = "WAL"; + static constexpr char DB_DEFAULT_JOURNAL_MODE[] = "delete"; + static constexpr char WAL_SYNC_MODE[] = "FULL"; + static constexpr char MEMORY_DB_PATH[] = ":memory:"; + static constexpr char ENCRYPT_ALGO[] = "sha256"; +}; + +class SqliteGlobalConfig { +public: + SqliteGlobalConfig(); + ~SqliteGlobalConfig(); + static void InitSqliteGlobalConfig(); + static void SqliteLogCallback(const void *data, int err, const char *msg); + static int GetReadConnectionCount(); + static std::string GetMemoryDbPath(); + static int GetPageSize(); + static std::string GetWalSyncMode(); + static int GetJournalFileSize(); + static int GetWalAutoCheckpoint(); + static std::string GetDefaultJournalMode(); + +private: + static const int SOFT_HEAP_LIMIT; + static const bool CALLBACK_LOG_SWITCH; + static const int CONNECTION_POOL_SIZE; + static const std::string MEMORY_DB_PATH; + static const int DB_PAGE_SIZE; + static const std::string DEFAULT_JOURNAL_MODE; + static const std::string WAL_SYNC_MODE; + static const int JOURNAL_FILE_SIZE; + static const int WAL_AUTO_CHECKPOINT; +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/frameworks/native/rdb/src/abs_result_set.cpp b/relational_store/frameworks/native/rdb/src/abs_result_set.cpp index 6621176bd80d6b937c9374875ccc55231ac8d73c..19b9c5b261190562aec8f6b67c74609c10850634 100644 --- a/relational_store/frameworks/native/rdb/src/abs_result_set.cpp +++ b/relational_store/frameworks/native/rdb/src/abs_result_set.cpp @@ -1,255 +1,255 @@ -/* - * 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 "abs_result_set.h" - -#include -#include - -#include "logger.h" -#include "rdb_errno.h" -#include "rdb_trace.h" - -namespace OHOS { -namespace NativeRdb { -AbsResultSet::AbsResultSet() : rowPos_(INIT_POS), isClosed(false) -{ -} - -AbsResultSet::~AbsResultSet() {} - -int AbsResultSet::GetRowCount(int &count) -{ - return E_OK; -} - -int AbsResultSet::GetAllColumnNames(std::vector &columnNames) -{ - return E_OK; -} - -int AbsResultSet::GetBlob(int columnIndex, std::vector &blob) -{ - return E_OK; -} - -int AbsResultSet::GetString(int columnIndex, std::string &value) -{ - return E_OK; -} - -int AbsResultSet::GetInt(int columnIndex, int &value) -{ - return E_OK; -} - -int AbsResultSet::GetLong(int columnIndex, int64_t &value) -{ - return E_OK; -} - -int AbsResultSet::GetDouble(int columnIndex, double &value) -{ - return E_OK; -} - -int AbsResultSet::IsColumnNull(int columnIndex, bool &isNull) -{ - return E_OK; -} - -int AbsResultSet::GoToRow(int position) -{ - return E_OK; -} - -int AbsResultSet::GetColumnType(int columnIndex, ColumnType &columnType) -{ - return E_OK; -} - -int AbsResultSet::GetRowIndex(int &position) const -{ - position = rowPos_; - return E_OK; -} - -int AbsResultSet::GoTo(int offset) -{ - DDS_TRACE(); - int ret = GoToRow(rowPos_ + offset); - if (ret != E_OK) { - LOG_WARN("AbsResultSet::GoTo return ret is wrong!"); - return ret; - } - return E_OK; -} - -int AbsResultSet::GoToFirstRow() -{ - DDS_TRACE(); - int ret = GoToRow(0); - if (ret != E_OK) { - LOG_WARN("AbsResultSet::GoToFirstRow return ret is wrong!"); - return ret; - } - return E_OK; -} - -int AbsResultSet::GoToLastRow() -{ - DDS_TRACE(); - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_WARN("AbsResultSet::GoToLastRow return GetRowCount::ret is wrong!"); - return ret; - } - - ret = GoToRow(rowCnt - 1); - if (ret != E_OK) { - LOG_WARN("AbsResultSet::GoToLastRow return GoToRow::ret is wrong!"); - return ret; - } - return E_OK; -} - -int AbsResultSet::GoToNextRow() -{ - DDS_TRACE(); - int ret = GoToRow(rowPos_ + 1); - if (ret != E_OK) { - LOG_WARN("AbsResultSet::GoToNextRow return GoToRow::ret is wrong!"); - return ret; - } - return E_OK; -} - -int AbsResultSet::GoToPreviousRow() -{ - DDS_TRACE(); - int ret = GoToRow(rowPos_ - 1); - if (ret != E_OK) { - LOG_WARN("AbsResultSet::GoToPreviousRow return GoToRow::ret is wrong!"); - return ret; - } - return E_OK; -} - -int AbsResultSet::IsAtFirstRow(bool &result) const -{ - result = (rowPos_ == 0); - return E_OK; -} - -int AbsResultSet::IsAtLastRow(bool &result) -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("AbsResultSet::IsAtLastRow return GetRowCount::ret is wrong!"); - return ret; - } - result = (rowPos_ == (rowCnt - 1)); - return E_OK; -} - -int AbsResultSet::IsStarted(bool &result) const -{ - result = (rowPos_ != INIT_POS); - return E_OK; -} - -int AbsResultSet::IsEnded(bool &result) -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("AbsResultSet::IsEnded return GetRowCount::ret is wrong!"); - return ret; - } - result = (rowCnt == 0) ? true : (rowPos_ == rowCnt); - return E_OK; -} - -int AbsResultSet::GetColumnCount(int &count) -{ - std::vector columnNames; - int ret = GetAllColumnNames(columnNames); - if (ret != E_OK) { - LOG_ERROR("AbsResultSet::GetColumnCount return GetAllColumnNames::ret is wrong!"); - return ret; - } - count = static_cast(columnNames.size()); - return E_OK; -} - -int AbsResultSet::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("AbsResultSet::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 AbsResultSet::GetColumnName(int columnIndex, std::string &columnName) -{ - int rowCnt = 0; - int ret = GetColumnCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("AbsResultSet::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 AbsResultSet::IsClosed() const -{ - return isClosed; -} - -int AbsResultSet::Close() -{ - isClosed = true; - return E_OK; -} -} // namespace NativeRdb +/* + * 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 "abs_result_set.h" + +#include +#include + +#include "logger.h" +#include "rdb_errno.h" +#include "rdb_trace.h" + +namespace OHOS { +namespace NativeRdb { +AbsResultSet::AbsResultSet() : rowPos_(INIT_POS), isClosed(false) +{ +} + +AbsResultSet::~AbsResultSet() {} + +int AbsResultSet::GetRowCount(int &count) +{ + return E_OK; +} + +int AbsResultSet::GetAllColumnNames(std::vector &columnNames) +{ + return E_OK; +} + +int AbsResultSet::GetBlob(int columnIndex, std::vector &blob) +{ + return E_OK; +} + +int AbsResultSet::GetString(int columnIndex, std::string &value) +{ + return E_OK; +} + +int AbsResultSet::GetInt(int columnIndex, int &value) +{ + return E_OK; +} + +int AbsResultSet::GetLong(int columnIndex, int64_t &value) +{ + return E_OK; +} + +int AbsResultSet::GetDouble(int columnIndex, double &value) +{ + return E_OK; +} + +int AbsResultSet::IsColumnNull(int columnIndex, bool &isNull) +{ + return E_OK; +} + +int AbsResultSet::GoToRow(int position) +{ + return E_OK; +} + +int AbsResultSet::GetColumnType(int columnIndex, ColumnType &columnType) +{ + return E_OK; +} + +int AbsResultSet::GetRowIndex(int &position) const +{ + position = rowPos_; + return E_OK; +} + +int AbsResultSet::GoTo(int offset) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int ret = GoToRow(rowPos_ + offset); + if (ret != E_OK) { + LOG_WARN("AbsResultSet::GoTo return ret is wrong!"); + return ret; + } + return E_OK; +} + +int AbsResultSet::GoToFirstRow() +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int ret = GoToRow(0); + if (ret != E_OK) { + LOG_WARN("AbsResultSet::GoToFirstRow return ret is wrong!"); + return ret; + } + return E_OK; +} + +int AbsResultSet::GoToLastRow() +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int rowCnt = 0; + int ret = GetRowCount(rowCnt); + if (ret != E_OK) { + LOG_WARN("AbsResultSet::GoToLastRow return GetRowCount::ret is wrong!"); + return ret; + } + + ret = GoToRow(rowCnt - 1); + if (ret != E_OK) { + LOG_WARN("AbsResultSet::GoToLastRow return GoToRow::ret is wrong!"); + return ret; + } + return E_OK; +} + +int AbsResultSet::GoToNextRow() +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int ret = GoToRow(rowPos_ + 1); + if (ret != E_OK) { + LOG_WARN("AbsResultSet::GoToNextRow return GoToRow::ret is wrong!"); + return ret; + } + return E_OK; +} + +int AbsResultSet::GoToPreviousRow() +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int ret = GoToRow(rowPos_ - 1); + if (ret != E_OK) { + LOG_WARN("AbsResultSet::GoToPreviousRow return GoToRow::ret is wrong!"); + return ret; + } + return E_OK; +} + +int AbsResultSet::IsAtFirstRow(bool &result) const +{ + result = (rowPos_ == 0); + return E_OK; +} + +int AbsResultSet::IsAtLastRow(bool &result) +{ + int rowCnt = 0; + int ret = GetRowCount(rowCnt); + if (ret != E_OK) { + LOG_ERROR("AbsResultSet::IsAtLastRow return GetRowCount::ret is wrong!"); + return ret; + } + result = (rowPos_ == (rowCnt - 1)); + return E_OK; +} + +int AbsResultSet::IsStarted(bool &result) const +{ + result = (rowPos_ != INIT_POS); + return E_OK; +} + +int AbsResultSet::IsEnded(bool &result) +{ + int rowCnt = 0; + int ret = GetRowCount(rowCnt); + if (ret != E_OK) { + LOG_ERROR("AbsResultSet::IsEnded return GetRowCount::ret is wrong!"); + return ret; + } + result = (rowCnt == 0) ? true : (rowPos_ == rowCnt); + return E_OK; +} + +int AbsResultSet::GetColumnCount(int &count) +{ + std::vector columnNames; + int ret = GetAllColumnNames(columnNames); + if (ret != E_OK) { + LOG_ERROR("AbsResultSet::GetColumnCount return GetAllColumnNames::ret is wrong!"); + return ret; + } + count = static_cast(columnNames.size()); + return E_OK; +} + +int AbsResultSet::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("AbsResultSet::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 AbsResultSet::GetColumnName(int columnIndex, std::string &columnName) +{ + int rowCnt = 0; + int ret = GetColumnCount(rowCnt); + if (ret != E_OK) { + LOG_ERROR("AbsResultSet::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 AbsResultSet::IsClosed() const +{ + return isClosed; +} + +int AbsResultSet::Close() +{ + isClosed = true; + return E_OK; +} +} // namespace NativeRdb } // namespace OHOS \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp b/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp index 7ddae662e783c8b64cf7cd290c4e9c0ffdc826ce..411a0c453888eff9f399c3aa8e616ef30a6b1704 100644 --- a/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp +++ b/relational_store/frameworks/native/rdb/src/abs_shared_result_set.cpp @@ -1,435 +1,436 @@ -/* - * 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 "abs_shared_result_set.h" - -#include -#include -#include -#include -#include -#include - -#include "dds_trace.h" -#include "logger.h" -#include "parcel.h" -#include "rdb_errno.h" -#include "shared_block.h" -#include "string_ex.h" - -namespace OHOS { -namespace NativeRdb { -AbsSharedResultSet::AbsSharedResultSet(std::string name) -{ - AppDataFwk::SharedBlock::Create(name, DEFAULT_BLOCK_SIZE, sharedBlock_); -} - -AbsSharedResultSet::AbsSharedResultSet() -{ -} - -AbsSharedResultSet::~AbsSharedResultSet() -{ - ClosedBlock(); -} - -int AbsSharedResultSet::GetAllColumnNames(std::vector &columnNames) -{ - return E_OK; -} - -int AbsSharedResultSet::GetRowCount(int &count) -{ - return E_OK; -} - -bool AbsSharedResultSet::OnGo(int oldRowIndex, int newRowIndex) -{ - return true; -} - -void AbsSharedResultSet::FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) -{ - return; -} - -/** - * Get current shared block - */ -AppDataFwk::SharedBlock *AbsSharedResultSet::GetBlock() const -{ - return sharedBlock_; -} - -int AbsSharedResultSet::GetColumnType(int columnIndex, ColumnType &columnType) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = - sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), (uint32_t)columnIndex); - if (!cellUnit) { - LOG_ERROR("AbsSharedResultSet::GetColumnType cellUnit is null!"); - return E_ERROR; - } - columnType = (ColumnType)cellUnit->type; - return E_OK; -} - -int AbsSharedResultSet::GoToRow(int position) -{ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - int rowCnt = 0; - GetRowCount(rowCnt); - if (rowCnt == 0) { - LOG_WARN("No data!"); - return E_ERROR; - } - if (position < 0) { - LOG_ERROR("Invalid position %{public}d!", position); - return E_ERROR; - } - if (position >= rowCnt) { - rowPos_ = rowCnt; - return E_ERROR; - } - - if (position == rowPos_) { - return E_OK; - } - if (rowPos_ <= INIT_POS) { - rowPos_ = 0; - } - bool result = true; - if (sharedBlock_ == nullptr || (uint32_t)position < sharedBlock_->GetStartPos() || - (uint32_t)position >= sharedBlock_->GetLastPos() || rowPos_ == rowCnt) { - result = OnGo(rowPos_, position); - } else { - uint32_t blockPos = sharedBlock_->GetBlockPos(); - if (position > rowPos_) { - blockPos += (uint32_t)(position - rowPos_); - } else { - uint32_t offset = (uint32_t)(rowPos_ - position); - if (blockPos >= offset) { - blockPos -= offset; - } else { - LOG_ERROR("GoToRow failed of position= %{public}d, rowPos= %{public}d", position, rowPos_); - return E_ERROR; - } - } - sharedBlock_->SetBlockPos(blockPos); - } - - if (!result) { - return E_ERROR; - } else { - rowPos_ = position; - return E_OK; - } -} - -int AbsSharedResultSet::GetBlob(int columnIndex, std::vector &value) -{ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); - if (!cellUnit) { - LOG_ERROR("AbsSharedResultSet::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("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER!"); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT!"); - return E_OK; - } else { - LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::nothing !"); - return E_INVALID_OBJECT_TYPE; - } -} - -int AbsSharedResultSet::GetString(int columnIndex, std::string &value) -{ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); - if (!cellUnit) { - LOG_ERROR("AbsSharedResultSet::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("AbsSharedResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); - return E_ERROR; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - LOG_ERROR("AbsSharedResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!"); - return E_ERROR; - } else { - LOG_ERROR("AbsSharedResultSet::GetString is failed!"); - return E_ERROR; - } -} - -int AbsSharedResultSet::GetInt(int columnIndex, int &value) -{ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); - if (!cellUnit) { - LOG_ERROR("AbsSharedResultSet::GetInt cellUnit is null!"); - return E_ERROR; - } - value = (int)cellUnit->cell.longValue; - return E_OK; -} - -int AbsSharedResultSet::GetLong(int columnIndex, int64_t &value) -{ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); - if (!cellUnit) { - LOG_ERROR("AbsSharedResultSet::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)) ? int64_t(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("AbsSharedResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT !"); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - LOG_ERROR("AbsSharedResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL !"); - value = 0L; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - LOG_ERROR("AbsSharedResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB !"); - value = 0L; - return E_OK; - } else { - LOG_ERROR("AbsSharedResultSet::GetLong Nothing !"); - return E_INVALID_OBJECT_TYPE; - } -} - -int AbsSharedResultSet::GetDouble(int columnIndex, double &value) -{ - DistributedDataDfx::DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); - if (!cellUnit) { - LOG_ERROR("AbsSharedResultSet::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("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); - value = 0.0; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!"); - value = 0.0; - return E_OK; - } else { - LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::nothing !"); - value = 0.0; - return E_INVALID_OBJECT_TYPE; - } -} - -int AbsSharedResultSet::IsColumnNull(int columnIndex, bool &isNull) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); - if (!cellUnit) { - LOG_ERROR("AbsSharedResultSet::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 AbsSharedResultSet::Close() -{ - AbsResultSet::Close(); - ClosedBlock(); - return E_OK; -} - -/** - * Allocates a new shared block to an {@link AbsSharedResultSet} - */ -void AbsSharedResultSet::SetBlock(AppDataFwk::SharedBlock *block) -{ - if (sharedBlock_ != block) { - ClosedBlock(); - sharedBlock_ = block; - } -} - -/** - * Checks whether an {@code AbsSharedResultSet} object contains shared blocks - */ -bool AbsSharedResultSet::HasBlock() const -{ - return sharedBlock_ != nullptr; -} - -/** - * Closes a shared block that is not empty in this {@code AbsSharedResultSet} object - */ -void AbsSharedResultSet::ClosedBlock() -{ - delete sharedBlock_; - sharedBlock_ = nullptr; -} - -void AbsSharedResultSet::ClearBlock() -{ - if (sharedBlock_ != nullptr) { - sharedBlock_->Clear(); - } -} - -void AbsSharedResultSet::Finalize() -{ - Close(); -} - -/** - * Check current status - */ -int AbsSharedResultSet::CheckState(int columnIndex) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("AbsSharedResultSet::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 AbsSharedResultSet::Marshalling(MessageParcel &parcel) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("AbsSharedResultSet::Marshalling sharedBlock is null."); - return false; - } - LOG_DEBUG("AbsSharedResultSet::Marshalling sharedBlock."); - return sharedBlock_->WriteMessageParcel(parcel); -} - -bool AbsSharedResultSet::Unmarshalling(MessageParcel &parcel) -{ - if (sharedBlock_ != nullptr) { - return false; - } - int result = AppDataFwk::SharedBlock::ReadMessageParcel(parcel, sharedBlock_); - if (result < 0) { - LOG_ERROR("AbsSharedResultSet: create from parcel error is %{public}d.", result); - } - return true; -} -} // namespace NativeRdb -} // namespace OHOS +/* + * 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 "abs_shared_result_set.h" + +#include +#include +#include +#include +#include +#include + +#include "logger.h" +#include "parcel.h" +#include "rdb_errno.h" +#include "rdb_trace.h" +#include "shared_block.h" +#include "string_ex.h" + +namespace OHOS { +namespace NativeRdb { +AbsSharedResultSet::AbsSharedResultSet(std::string name) +{ + AppDataFwk::SharedBlock::Create(name, DEFAULT_BLOCK_SIZE, sharedBlock_); +} + +AbsSharedResultSet::AbsSharedResultSet() +{ +} + +AbsSharedResultSet::~AbsSharedResultSet() +{ + ClosedBlock(); +} + +int AbsSharedResultSet::GetAllColumnNames(std::vector &columnNames) +{ + return E_OK; +} + +int AbsSharedResultSet::GetRowCount(int &count) +{ + return E_OK; +} + +bool AbsSharedResultSet::OnGo(int oldRowIndex, int newRowIndex) +{ + return true; +} + +void AbsSharedResultSet::FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) +{ + return; +} + +/** + * Get current shared block + */ +AppDataFwk::SharedBlock *AbsSharedResultSet::GetBlock() const +{ + return sharedBlock_; +} + +int AbsSharedResultSet::GetColumnType(int columnIndex, ColumnType &columnType) +{ + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = + sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), (uint32_t)columnIndex); + if (!cellUnit) { + LOG_ERROR("AbsSharedResultSet::GetColumnType cellUnit is null!"); + return E_ERROR; + } + columnType = (ColumnType)cellUnit->type; + return E_OK; +} + +int AbsSharedResultSet::GoToRow(int position) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int rowCnt = 0; + GetRowCount(rowCnt); + if (rowCnt == 0) { + LOG_WARN("No data!"); + return E_ERROR; + } + if (position < 0) { + LOG_ERROR("Invalid position %{public}d!", position); + return E_ERROR; + } + if (position >= rowCnt) { + rowPos_ = rowCnt; + return E_ERROR; + } + + if (position == rowPos_) { + return E_OK; + } + if (rowPos_ <= INIT_POS) { + rowPos_ = 0; + } + bool result = true; + if (sharedBlock_ == nullptr || (uint32_t)position < sharedBlock_->GetStartPos() || + (uint32_t)position >= sharedBlock_->GetLastPos() || rowPos_ == rowCnt) { + result = OnGo(rowPos_, position); + } else { + uint32_t blockPos = sharedBlock_->GetBlockPos(); + if (position > rowPos_) { + blockPos += (uint32_t)(position - rowPos_); + } else { + uint32_t offset = (uint32_t)(rowPos_ - position); + if (blockPos >= offset) { + blockPos -= offset; + } else { + LOG_ERROR("GoToRow failed of position= %{public}d, rowPos= %{public}d", position, rowPos_); + return E_ERROR; + } + } + sharedBlock_->SetBlockPos(blockPos); + } + + if (!result) { + return E_ERROR; + } else { + rowPos_ = position; + return E_OK; + } +} + +int AbsSharedResultSet::GetBlob(int columnIndex, std::vector &value) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); + if (!cellUnit) { + LOG_ERROR("AbsSharedResultSet::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("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER!"); + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { + LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { + LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT!"); + return E_OK; + } else { + LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::nothing !"); + return E_INVALID_OBJECT_TYPE; + } +} + +int AbsSharedResultSet::GetString(int columnIndex, std::string &value) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); + if (!cellUnit) { + LOG_ERROR("AbsSharedResultSet::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 = ""; + LOG_ERROR("AbsSharedResultSet::GetString string is null"); + return E_OK; + } + 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("AbsSharedResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { + LOG_ERROR("AbsSharedResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!"); + return E_OK; + } else { + LOG_ERROR("AbsSharedResultSet::GetString is failed!"); + return E_ERROR; + } +} + +int AbsSharedResultSet::GetInt(int columnIndex, int &value) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); + if (!cellUnit) { + LOG_ERROR("AbsSharedResultSet::GetInt cellUnit is null!"); + return E_ERROR; + } + value = (int)cellUnit->cell.longValue; + return E_OK; +} + +int AbsSharedResultSet::GetLong(int columnIndex, int64_t &value) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); + if (!cellUnit) { + LOG_ERROR("AbsSharedResultSet::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)) ? int64_t(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("AbsSharedResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT !"); + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { + LOG_ERROR("AbsSharedResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL !"); + value = 0L; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { + LOG_ERROR("AbsSharedResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB !"); + value = 0L; + return E_OK; + } else { + LOG_ERROR("AbsSharedResultSet::GetLong Nothing !"); + return E_INVALID_OBJECT_TYPE; + } +} + +int AbsSharedResultSet::GetDouble(int columnIndex, double &value) +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); + if (!cellUnit) { + LOG_ERROR("AbsSharedResultSet::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("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!"); + value = 0.0; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { + LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!"); + value = 0.0; + return E_OK; + } else { + LOG_ERROR("AbsSharedResultSet::GetDouble AppDataFwk::SharedBlock::nothing !"); + value = 0.0; + return E_INVALID_OBJECT_TYPE; + } +} + +int AbsSharedResultSet::IsColumnNull(int columnIndex, bool &isNull) +{ + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(sharedBlock_->GetBlockPos(), columnIndex); + if (!cellUnit) { + LOG_ERROR("AbsSharedResultSet::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 AbsSharedResultSet::Close() +{ + AbsResultSet::Close(); + ClosedBlock(); + return E_OK; +} + +/** + * Allocates a new shared block to an {@link AbsSharedResultSet} + */ +void AbsSharedResultSet::SetBlock(AppDataFwk::SharedBlock *block) +{ + if (sharedBlock_ != block) { + ClosedBlock(); + sharedBlock_ = block; + } +} + +/** + * Checks whether an {@code AbsSharedResultSet} object contains shared blocks + */ +bool AbsSharedResultSet::HasBlock() const +{ + return sharedBlock_ != nullptr; +} + +/** + * Closes a shared block that is not empty in this {@code AbsSharedResultSet} object + */ +void AbsSharedResultSet::ClosedBlock() +{ + delete sharedBlock_; + sharedBlock_ = nullptr; +} + +void AbsSharedResultSet::ClearBlock() +{ + if (sharedBlock_ != nullptr) { + sharedBlock_->Clear(); + } +} + +void AbsSharedResultSet::Finalize() +{ + Close(); +} + +/** + * Check current status + */ +int AbsSharedResultSet::CheckState(int columnIndex) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("AbsSharedResultSet::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 AbsSharedResultSet::Marshalling(MessageParcel &parcel) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("AbsSharedResultSet::Marshalling sharedBlock is null."); + return false; + } + LOG_DEBUG("AbsSharedResultSet::Marshalling sharedBlock."); + return sharedBlock_->WriteMessageParcel(parcel); +} + +bool AbsSharedResultSet::Unmarshalling(MessageParcel &parcel) +{ + if (sharedBlock_ != nullptr) { + return false; + } + int result = AppDataFwk::SharedBlock::ReadMessageParcel(parcel, sharedBlock_); + if (result < 0) { + LOG_ERROR("AbsSharedResultSet: create from parcel error is %{public}d.", result); + } + return true; +} +} // namespace NativeRdb +} // namespace OHOS diff --git a/relational_store/frameworks/native/rdb/src/rdb_helper.cpp b/relational_store/frameworks/native/rdb/src/rdb_helper.cpp index 71138226c57993c0933a9d9a4490415032c864cf..25784ab183584e1942c785b45f566bc85d045b06 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_helper.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_helper.cpp @@ -24,6 +24,7 @@ #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) #include "rdb_security_manager.h" +#include "security_policy.h" #endif namespace OHOS { @@ -33,7 +34,7 @@ std::map> RdbHelper::storeCache_; std::shared_ptr RdbHelper::GetRdbStore( const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) { - DDS_TRACE(DistributedDataDfx::TraceSwitch::BYTRACE_ON | DistributedDataDfx::TraceSwitch::TRACE_CHAIN_ON); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); SqliteGlobalConfig::InitSqliteGlobalConfig(); #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) @@ -58,6 +59,14 @@ std::shared_ptr RdbHelper::GetRdbStore( } } +#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) + errCode = SecurityPolicy::SetSecurityLabel(config); + if (errCode != E_OK) { + LOG_ERROR("RdbHelper set security label fail."); + return nullptr; + } +#endif + errCode = ProcessOpenCallback(*rdbStore, config, version, openCallback); if (errCode != E_OK) { LOG_ERROR("RdbHelper GetRdbStore ProcessOpenCallback fail"); @@ -120,7 +129,7 @@ static void DeleteRdbKeyFiles(const std::string &dbFileName) int RdbHelper::DeleteRdbStore(const std::string &dbFileName) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); if (dbFileName.empty()) { return E_EMPTY_FILE_NAME; } diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp index bec69cbf7e30e4a2a1e1dd9d2bee53764f96a6c4..7b19d10f858cc0b52478800bc817d69a9bce5880 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_config.cpp @@ -30,12 +30,13 @@ RdbStoreConfig::RdbStoreConfig(const RdbStoreConfig &config) syncMode = config.GetSyncMode(); readOnly = config.IsReadOnly(); databaseFileType = config.GetDatabaseFileType(); - databaseFileSecurityLevel = config.GetDatabaseFileSecurityLevel(); + securityLevel = config.GetSecurityLevel(); } RdbStoreConfig::RdbStoreConfig(const std::string &name, StorageMode storageMode, bool isReadOnly, const std::vector &encryptKey, const std::string &journalMode, const std::string &syncMode, - const std::string &databaseFileType, const std::string &databaseFileSecurityLevel, bool isCreateNecessary) + const std::string &databaseFileType, SecurityLevel securityLevel, bool isCreateNecessary, bool autoCheck, + int journalSize, int pageSize, const std::string &encryptAlgo) : name(name), path(name), storageMode(storageMode), @@ -43,9 +44,14 @@ RdbStoreConfig::RdbStoreConfig(const std::string &name, StorageMode storageMode, syncMode(syncMode), readOnly(isReadOnly), databaseFileType(databaseFileType), - databaseFileSecurityLevel(databaseFileSecurityLevel), - isCreateNecessary_(isCreateNecessary) -{} + securityLevel(securityLevel), + isCreateNecessary_(isCreateNecessary), + autoCheck(autoCheck), + journalSize(journalSize), + pageSize(pageSize), + encryptAlgo(encryptAlgo) +{ +} RdbStoreConfig::~RdbStoreConfig() = default; @@ -113,14 +119,6 @@ std::string RdbStoreConfig::GetDatabaseFileType() const return databaseFileType; } -/** - * Obtains the security level of the database file. - */ -std::string RdbStoreConfig::GetDatabaseFileSecurityLevel() const -{ - return databaseFileSecurityLevel; -} - void RdbStoreConfig::SetName(std::string name) { this->name = std::move(name); @@ -152,6 +150,39 @@ void RdbStoreConfig::SetStorageMode(StorageMode storageMode) this->storageMode = storageMode; } +bool RdbStoreConfig::IsAutoCheck() const +{ + return autoCheck; +} +void RdbStoreConfig::SetAutoCheck(bool autoCheck) +{ + this->autoCheck = autoCheck; +} +int RdbStoreConfig::GetJournalSize() const +{ + return journalSize; +} +void RdbStoreConfig::SetJournalSize(int journalSize) +{ + this->journalSize = journalSize; +} +int RdbStoreConfig::GetPageSize() const +{ + return pageSize; +} +void RdbStoreConfig::SetPageSize(int pageSize) +{ + this->pageSize = pageSize; +} +const std::string RdbStoreConfig::GetEncryptAlgo() const +{ + return encryptAlgo; +} +void RdbStoreConfig::SetEncryptAlgo(const std::string &encryptAlgo) +{ + this->encryptAlgo = encryptAlgo; +} + void RdbStoreConfig::SetReadOnly(bool readOnly) { this->readOnly = readOnly; @@ -273,38 +304,14 @@ std::string RdbStoreConfig::GetDatabaseFileTypeValue(DatabaseFileType databaseFi return value; } -std::string RdbStoreConfig::GetDatabaseFileSecurityLevelValue(DatabaseFileSecurityLevel databaseFileSecurityLevel) -{ - std::string value = ""; - - switch (databaseFileSecurityLevel) { - case DatabaseFileSecurityLevel::S4: - return "S4"; - case DatabaseFileSecurityLevel::S3: - return "S3"; - case DatabaseFileSecurityLevel::S2: - return "S2"; - case DatabaseFileSecurityLevel::S1: - return "S1"; - case DatabaseFileSecurityLevel::S0: - return "S0"; - case DatabaseFileSecurityLevel::NO_LEVEL: - return "NO_LEVEL"; - default: - break; - } - - return value; -} - -void RdbStoreConfig::SetSecurityLevel(const int32_t &secLevel) +void RdbStoreConfig::SetSecurityLevel(SecurityLevel sl) { - securityLevel_ = secLevel; + securityLevel = sl; } -int32_t RdbStoreConfig::GetSecurityLevel() const +SecurityLevel RdbStoreConfig::GetSecurityLevel() const { - return securityLevel_; + return securityLevel; } void RdbStoreConfig::SetEncryptStatus(const bool status) diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp index ec9b612559cd2484dd92bdac3d34125786907cd4..88c424863f4821801bf61270f8e013b3b826a848 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp @@ -36,7 +36,6 @@ #include "rdb_security_manager.h" #include "rdb_manager.h" #include "relational_store_manager.h" -#include "reporter.h" #include "result_set_proxy.h" #include "sqlite_shared_result_set.h" #endif @@ -72,14 +71,13 @@ int RdbStoreImpl::InnerOpen(const RdbStoreConfig &config) isReadOnly = config.IsReadOnly(); isMemoryRdb = config.IsMemoryRdb(); name = config.GetName(); - fileSecurityLevel = config.GetDatabaseFileSecurityLevel(); fileType = config.GetDatabaseFileType(); #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) syncerParam_.bundleName_ = config.GetBundleName(); syncerParam_.hapName_ = config.GetModuleName(); syncerParam_.storeName_ = config.GetName(); syncerParam_.area_ = config.GetArea(); - syncerParam_.level_ = config.GetSecurityLevel(); + syncerParam_.level_ = static_cast(config.GetSecurityLevel()); syncerParam_.type_ = config.GetDistributedType(); syncerParam_.isEncrypt_ = config.IsEncrypt(); syncerParam_.password_ = {}; @@ -179,7 +177,7 @@ void RdbStoreImpl::ReleaseThreadSession() int RdbStoreImpl::Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); return InsertWithConflictResolution(outRowId, table, initialValues, ConflictResolution::ON_CONFLICT_NONE); } @@ -254,7 +252,7 @@ int RdbStoreImpl::InsertWithConflictResolution(int64_t &outRowId, const std::str int RdbStoreImpl::Update(int &changedRows, const std::string &table, const ValuesBucket &values, const std::string &whereClause, const std::vector &whereArgs) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); return UpdateWithConflictResolution( changedRows, table, values, whereClause, whereArgs, ConflictResolution::ON_CONFLICT_NONE); } @@ -310,7 +308,7 @@ int RdbStoreImpl::UpdateWithConflictResolution(int &changedRows, const std::stri int RdbStoreImpl::Delete(int &deletedRows, const AbsRdbPredicates &predicates) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); return Delete(deletedRows, predicates.GetTableName(), predicates.GetWhereClause(), predicates.GetWhereArgs()); } @@ -342,7 +340,7 @@ int RdbStoreImpl::Delete(int &deletedRows, const std::string &table, const std:: std::unique_ptr RdbStoreImpl::Query( const AbsRdbPredicates &predicates, const std::vector columns) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); LOG_DEBUG("RdbStoreImpl::Query on called."); std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns); @@ -352,7 +350,7 @@ std::unique_ptr RdbStoreImpl::Query( std::unique_ptr RdbStoreImpl::QueryByStep( const AbsRdbPredicates &predicates, const std::vector columns) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); LOG_DEBUG("RdbStoreImpl::QueryByStep on called."); std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns); @@ -362,7 +360,7 @@ std::unique_ptr RdbStoreImpl::QueryByStep( std::shared_ptr RdbStoreImpl::RemoteQuery(const std::string &device, const AbsRdbPredicates &predicates, const std::vector &columns) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); LOG_DEBUG("RdbStoreImpl::RemoteQuery on called."); std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns); @@ -384,7 +382,7 @@ std::unique_ptr RdbStoreImpl::Query(int &errCode, bool disti const std::vector &selectionArgs, const std::string &groupBy, const std::string &having, const std::string &orderBy, const std::string &limit) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::string sql; errCode = SqliteSqlBuilder::BuildQueryString(distinct, table, columns, selection, groupBy, having, orderBy, limit, "", sql); @@ -399,7 +397,7 @@ std::unique_ptr RdbStoreImpl::Query(int &errCode, bool disti std::unique_ptr RdbStoreImpl::QuerySql(const std::string &sql, const std::vector &selectionArgs) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); auto resultSet = std::make_unique(shared_from_this(), path, sql, selectionArgs); return resultSet; } @@ -409,7 +407,7 @@ std::unique_ptr RdbStoreImpl::QuerySql(const std::string &sq std::unique_ptr RdbStoreImpl::Query( const AbsRdbPredicates &predicates, const std::vector columns) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); LOG_DEBUG("RdbStoreImpl::Query on called."); std::vector selectionArgs = predicates.GetWhereArgs(); std::string sql = SqliteSqlBuilder::BuildQueryString(predicates, columns); @@ -434,7 +432,7 @@ int RdbStoreImpl::Count(int64_t &outValue, const AbsRdbPredicates &predicates) int RdbStoreImpl::ExecuteSql(const std::string &sql, const std::vector &bindArgs) { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); int errCode = CheckAttach(sql); if (errCode != E_OK) { return errCode; @@ -570,7 +568,7 @@ int RdbStoreImpl::SetVersion(int version) */ int RdbStoreImpl::BeginTransaction() { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::shared_ptr session = GetThreadSession(); int errCode = session->BeginTransaction(); if (errCode != E_OK) { @@ -584,7 +582,7 @@ int RdbStoreImpl::BeginTransaction() */ int RdbStoreImpl::RollBack() { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); std::shared_ptr session = GetThreadSession(); int errCode = session->RollBack(); if (errCode != E_OK) { @@ -598,7 +596,7 @@ int RdbStoreImpl::RollBack() */ int RdbStoreImpl::Commit() { - DDS_TRACE(); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); LOG_DEBUG("Enter Commit"); std::shared_ptr session = GetThreadSession(); int errCode = session->Commit(); @@ -783,11 +781,6 @@ std::string RdbStoreImpl::GetFileType() return fileType; } -std::string RdbStoreImpl::GetFileSecurityLevel() -{ - return fileSecurityLevel; -} - int RdbStoreImpl::PrepareAndGetInfo(const std::string &sql, bool &outIsReadOnly, int &numParameters, std::vector &columnNames) { @@ -904,7 +897,7 @@ std::unique_ptr RdbStoreImpl::QueryByStep(const std::string &sql, #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) bool RdbStoreImpl::SetDistributedTables(const std::vector &tables) { - DDS_TRACE(DistributedDataDfx::TraceSwitch::BYTRACE_ON | DistributedDataDfx::TraceSwitch::TRACE_CHAIN_ON); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); if (isEncrypt_) { bool status = false; RdbSecurityManager::GetInstance().GetKeyDistributedStatus( @@ -941,7 +934,7 @@ bool RdbStoreImpl::SetDistributedTables(const std::vector &tables) std::string RdbStoreImpl::ObtainDistributedTableName(const std::string &device, const std::string &table) { - DDS_TRACE(DistributedDataDfx::TraceSwitch::BYTRACE_ON | DistributedDataDfx::TraceSwitch::TRACE_CHAIN_ON); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); auto service = DistributedRdb::RdbManager::GetRdbService(syncerParam_); if (service == nullptr) { return ""; @@ -952,7 +945,7 @@ std::string RdbStoreImpl::ObtainDistributedTableName(const std::string &device, bool RdbStoreImpl::Sync(const SyncOption &option, const AbsRdbPredicates &predicate, const SyncCallback &callback) { - DDS_TRACE(DistributedDataDfx::TraceSwitch::BYTRACE_ON | DistributedDataDfx::TraceSwitch::TRACE_CHAIN_ON); + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); auto service = DistributedRdb::RdbManager::GetRdbService(syncerParam_); if (service == nullptr) { return false; diff --git a/relational_store/frameworks/native/rdb/src/security_policy.cpp b/relational_store/frameworks/native/rdb/src/security_policy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca24059f17ea8f0141e5c4832ffc7254a1d60184 --- /dev/null +++ b/relational_store/frameworks/native/rdb/src/security_policy.cpp @@ -0,0 +1,66 @@ +/* +* 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 "security_policy.h" + +#include "logger.h" +#include "rdb_errno.h" +#include "security_label.h" + +namespace OHOS { +namespace NativeRdb { +int SecurityPolicy::SetFileSecurityLevel(const std::string &filePath, const std::string &securityLevel) +{ + bool result = DistributedFS::ModuleSecurityLabel::SecurityLabel::SetSecurityLabel(filePath, securityLevel); + LOG_INFO("Set database securityLabel:%{public}s, result:%{public}d.", securityLevel.c_str(), result); + return result ? E_OK : E_ERROR; +} + +std::string SecurityPolicy::GetSecurityLevelValue(SecurityLevel securityLevel) +{ + switch (securityLevel) { + case SecurityLevel::S1: + return "s1"; + case SecurityLevel::S2: + return "s2"; + case SecurityLevel::S3: + return "s3"; + case SecurityLevel::S4: + return "s4"; + default: + return ""; + } +} + +std::string SecurityPolicy::GetFileSecurityLevel(const std::string &filePath) +{ + return DistributedFS::ModuleSecurityLabel::SecurityLabel::GetSecurityLabel(filePath); +} + +int SecurityPolicy::SetSecurityLabel(const RdbStoreConfig &config) { + if (config.GetStorageMode() != StorageMode::MODE_MEMORY && config.GetSecurityLevel() != SecurityLevel::LAST) { + + std::string currentLevel = GetFileSecurityLevel(config.GetPath()); + std::string toSetLevel = GetSecurityLevelValue(config.GetSecurityLevel()); + LOG_INFO("Security level current is %{public}s to %{public}s.", currentLevel.c_str(), toSetLevel.c_str()); + if (currentLevel.empty()) { + return SetFileSecurityLevel(config.GetPath(), toSetLevel); + } + return currentLevel == toSetLevel ? E_OK : E_ERROR; + } + return E_OK; +} +} // namespace NativeRdb +} // namespace OHOS \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/sqlite_config.cpp b/relational_store/frameworks/native/rdb/src/sqlite_config.cpp index f2c87170e4936cb26d6df4939a4140a4183f9cc4..6f727b7eeb834f63f5da2da40bf68f6ba1c7a38d 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_config.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_config.cpp @@ -25,7 +25,6 @@ SqliteConfig::SqliteConfig(const RdbStoreConfig &config) readOnly = config.IsReadOnly(); journalMode = config.GetJournalMode(); databaseFileType = config.GetDatabaseFileType(); - securityLevel = config.GetSecurityLevel(); syncMode = config.GetSyncMode(); if (journalMode.empty()) { journalMode = SqliteGlobalConfig::GetDefaultJournalMode(); @@ -34,6 +33,11 @@ SqliteConfig::SqliteConfig(const RdbStoreConfig &config) isEncrypt = config.IsEncrypt(); isCreateNecessary = config.IsCreateNecessary(); #endif + + this->autoCheck = config.IsAutoCheck(); + this->journalSize = config.GetJournalSize(); + this->pageSize = config.GetPageSize(); + this->encryptAlgo = config.GetEncryptAlgo(); } SqliteConfig::~SqliteConfig() = default; @@ -69,14 +73,43 @@ bool SqliteConfig::IsReadOnly() const return readOnly; } -int32_t SqliteConfig::GetSecurityLevel() const +std::string SqliteConfig::GetDatabaseFileType() const { - return securityLevel; + return databaseFileType; } -std::string SqliteConfig::GetDatabaseFileType() const +bool SqliteConfig::IsAutoCheck() const { - return databaseFileType; + return autoCheck; +} +void SqliteConfig::SetAutoCheck(bool autoCheck) +{ + this->autoCheck = autoCheck; +} +int SqliteConfig::GetJournalSize() const +{ + return journalSize; +} +void SqliteConfig::SetJournalSize(int journalSize) +{ + this->journalSize = journalSize; +} +int SqliteConfig::GetPageSize() const +{ + return pageSize; +} +void SqliteConfig::SetPageSize(int pageSize) +{ + this->pageSize = pageSize; +} + +std::string SqliteConfig::GetEncryptAlgo() const +{ + return encryptAlgo; +} +void SqliteConfig::SetEncryptAlgo(const std::string &encryptAlgo) +{ + this->encryptAlgo = encryptAlgo; } #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) @@ -89,6 +122,7 @@ std::string SqliteConfig::GetBundleName() const { return bundleName; } + bool SqliteConfig::IsCreateNecessary() const { return isCreateNecessary; diff --git a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp index bb9c64339908817b1dd87602c2a52cf35f58b075..c75361aa3da4ec7218c5ba2f00a90f3749b37178 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp @@ -91,9 +91,9 @@ int SqliteConnection::InnerOpen(const SqliteConfig &config) return E_STEP_STATEMENT_NOT_INIT; } #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) - bool isDbFileExist = access(dbPath.c_str(), F_OK) == 0; // db not exist - if ((!config.IsCreateNecessary()) && !isDbFileExist) { + bool isDbFileExist = access(dbPath.c_str(), F_OK) == 0; + if (!isDbFileExist && (!config.IsCreateNecessary())) { LOG_ERROR("SqliteConnection InnerOpen db not exist"); return E_DB_NOT_EXIST; } @@ -109,12 +109,6 @@ int SqliteConnection::InnerOpen(const SqliteConfig &config) SetPersistWal(); SetBusyTimeout(DEFAULT_BUSY_TIMEOUT_MS); LimitPermission(dbPath); -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) - errCode = SetSecurityLabel(dbPath, config, isDbFileExist); - if (errCode != E_OK) { - return errCode; - } -#endif errCode = Config(config); if (errCode != E_OK) { @@ -127,45 +121,13 @@ int SqliteConnection::InnerOpen(const SqliteConfig &config) return E_OK; } -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -int SqliteConnection::SetSecurityLabel(const std::string &dbPath, const SqliteConfig &config, const bool &isDbFileExist) -{ - if (isWriteConnection && config.GetSecurityLevel() != 0) { - std::string currentLevel = SqliteUtils::GetFileSecurityLevel(dbPath); - if (currentLevel.empty()) { - LOG_DEBUG("Set database SecurityLabel"); - int errCode = SqliteUtils::SetFileSecurityLevel(dbPath, config.GetSecurityLevel()); - if (errCode != E_OK) { - LOG_ERROR("Set database securityLabel failed, path = %{public}s", dbPath.c_str()); - if (!isDbFileExist) { - bool ret = RemoveFile(ExtractFilePath(dbPath)); - if (ret == false) { - LOG_ERROR("Delete dbFile error"); - } - return errCode; - } - return E_OK; - } - } else { - std::string inputLevel = SqliteUtils::DATA_LEVEL[config.GetSecurityLevel()]; - if (inputLevel != currentLevel) { - LOG_WARN("The input securityLabel is inconsistent with the current database securityLabel %{public}s.", - currentLevel.c_str()); - return E_OK; - } - } - } - return E_OK; -} -#endif - int SqliteConnection::Config(const SqliteConfig &config) { if (config.GetStorageMode() == StorageMode::MODE_MEMORY) { return E_OK; } - int errCode = SetPageSize(); + int errCode = SetPageSize(config); if (errCode != E_OK) { return errCode; } @@ -177,22 +139,22 @@ int SqliteConnection::Config(const SqliteConfig &config) } #endif - errCode = SetEncryptAlgo(); + errCode = SetEncryptAlgo(config); if (errCode != E_OK) { return errCode; } - errCode = SetJournalMode(config.GetJournalMode(), config.GetSyncMode()); + errCode = SetJournalMode(config); if (errCode != E_OK) { return errCode; } - errCode = SetJournalSizeLimit(); + errCode = SetJournalSizeLimit(config); if (errCode != E_OK) { return errCode; } - errCode = SetAutoCheckpoint(); + errCode = SetAutoCheckpoint(config); if (errCode != E_OK) { return errCode; } @@ -214,13 +176,13 @@ SqliteConnection::~SqliteConnection() } } -int SqliteConnection::SetPageSize() +int SqliteConnection::SetPageSize(const SqliteConfig &config) { - if (isReadOnly) { + if (isReadOnly || config.GetPageSize() == GlobalExpr::DB_PAGE_SIZE) { return E_OK; } - int targetValue = SqliteGlobalConfig::GetPageSize(); + int targetValue = config.GetPageSize(); int64_t value; int errCode = ExecuteGetLong(value, "PRAGMA page_size"); if (errCode != E_OK) { @@ -239,9 +201,16 @@ int SqliteConnection::SetPageSize() return errCode; } -int SqliteConnection::SetEncryptAlgo() +int SqliteConnection::SetEncryptAlgo(const SqliteConfig &config) { - int errCode = ExecuteSql("PRAGMA codec_hmac_algo=sha256"); + int errCode = E_OK; + if (config.GetEncryptAlgo().compare(GlobalExpr::ENCRYPT_ALGO) == 0) { + return errCode; + } + + // first to get the value, then to set algo + std::string sqlStr = "PRAGMA codec_hmac_algo=" + config.GetEncryptAlgo(); + errCode = ExecuteSql(sqlStr); if (errCode != E_OK) { LOG_ERROR("SqliteConnection SetEncryptAlgorithm fail, err = %{public}d", errCode); } @@ -286,9 +255,9 @@ int SqliteConnection::SetBusyTimeout(int timeout) return E_OK; } -int SqliteConnection::SetJournalMode(const std::string &journalMode, const std::string &synclMode) +int SqliteConnection::SetJournalMode(const SqliteConfig &config) { - if (isReadOnly) { + if (isReadOnly || config.GetJournalMode().compare(GlobalExpr::DB_DEFAULT_JOURNAL_MODE) == 0) { return E_OK; } @@ -300,30 +269,30 @@ int SqliteConnection::SetJournalMode(const std::string &journalMode, const std:: } currentMode = SqliteUtils::StrToUpper(currentMode); - if (currentMode != journalMode) { + if (currentMode != config.GetJournalMode()) { std::string result; - int errorCode = ExecuteGetString(result, "PRAGMA journal_mode=" + journalMode); + int errorCode = ExecuteGetString(result, "PRAGMA journal_mode=" + config.GetJournalMode()); if (errorCode != E_OK) { LOG_ERROR("SqliteConnection SetJournalMode: fail to set journal mode err=%{public}d", errorCode); return errorCode; } - if (SqliteUtils::StrToUpper(result) != journalMode) { + if (SqliteUtils::StrToUpper(result) != config.GetJournalMode()) { LOG_ERROR("SqliteConnection SetJournalMode: result incorrect"); return E_EXECUTE_RESULT_INCORRECT; } } - if (journalMode == "WAL") { - errCode = SetWalSyncMode(synclMode); + if (config.GetJournalMode() == "WAL") { + errCode = SetWalSyncMode(config.GetSyncMode()); } return errCode; } -int SqliteConnection::SetJournalSizeLimit() +int SqliteConnection::SetJournalSizeLimit(const SqliteConfig &config) { - if (isReadOnly) { + if (isReadOnly || config.GetJournalSize() == GlobalExpr::DB_JOURNAL_SIZE) { return E_OK; } @@ -347,9 +316,9 @@ int SqliteConnection::SetJournalSizeLimit() return errCode; } -int SqliteConnection::SetAutoCheckpoint() +int SqliteConnection::SetAutoCheckpoint(const SqliteConfig &config) { - if (isReadOnly) { + if (isReadOnly || config.IsAutoCheck() == GlobalExpr::DB_AUTO_CHECK) { return E_OK; } diff --git a/relational_store/frameworks/native/rdb/src/sqlite_database_utils.cpp b/relational_store/frameworks/native/rdb/src/sqlite_database_utils.cpp index e9e1d4459fac7046173156c9217fb143e30fd227..6f983f4777ce54b2f9e25ec4351ec4fbe2c58c08 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_database_utils.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_database_utils.cpp @@ -1,226 +1,197 @@ -/* - * 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 "sqlite_database_utils.h" - -#include -#include -#include - -#include -#include -#ifdef WINDOWS_PLATFORM -#include -#endif -#include -#include - -#include "logger.h" -#include "rdb_errno.h" - -#ifdef WINDOWS_PLATFORM -#define REALPATH(relPath, absPath, ...) (_fullpath(absPath, relPath, ##__VA_ARGS__)) -#define MKDIR(filePath) (mkdir(filePath)) -#else -#define REALPATH(absPath, relPath, ...) (realpath(absPath, relPath)) -#define MKDIR(filePath) (mkdir(filePath, g_mkdirMode)) -#endif - -namespace OHOS { -namespace NativeRdb { -std::map SqliteDatabaseUtils::g_statementType = SqliteDatabaseUtils::MapInit(); -std::mutex SqliteDatabaseUtils::g_locker; -// Set the file access permissions is 777 -int SqliteDatabaseUtils::g_mkdirMode = 0771; -std::map SqliteDatabaseUtils::MapInit() -{ - std::map temp; - temp["SEL"] = STATEMENT_SELECT; - temp["INS"] = STATEMENT_UPDATE; - temp["UPD"] = STATEMENT_UPDATE; - temp["REP"] = STATEMENT_UPDATE; - temp["DEL"] = STATEMENT_UPDATE; - temp["ATT"] = STATEMENT_ATTACH; - temp["DET"] = STATEMENT_DETACH; - temp["COM"] = STATEMENT_COMMIT; - temp["END"] = STATEMENT_COMMIT; - temp["ROL"] = STATEMENT_ROLLBACK; - temp["BEG"] = STATEMENT_BEGIN; - temp["PRA"] = STATEMENT_PRAGMA; - temp["CRE"] = STATEMENT_DDL; - temp["DRO"] = STATEMENT_DDL; - temp["ALT"] = STATEMENT_DDL; - - return temp; -} - -/** - * Obtains the type of SQL statement. - */ -int SqliteDatabaseUtils::GetSqlStatementType(std::string sql) -{ - if (sql.empty()) { - return STATEMENT_OTHER; - } - sql.erase(0, sql.find_first_not_of(" ")); - sql.erase(sql.find_last_not_of(" ") + 1); - - if (sql.length() < SQL_FIRST_CHARACTER) { - return STATEMENT_OTHER; - } - sql = sql.substr(0, SQL_FIRST_CHARACTER); - std::string prefixSql = sql; - transform(sql.begin(), sql.end(), prefixSql.begin(), ::toupper); - prefixSql = prefixSql.c_str(); - auto iter = g_statementType.find(prefixSql); - if (iter != g_statementType.end()) { - return iter->second; - } - return STATEMENT_OTHER; -} - -/** - * Delete the specified file. - */ -void SqliteDatabaseUtils::DeleteFile(std::string &fileName) -{ - if (access(fileName.c_str(), F_OK) != 0) { - LOG_ERROR("File %{private}s does not exist", fileName.c_str()); - return; - } - if (!remove(fileName.c_str())) { - LOG_ERROR("FileName= %{private}s has been deleted", fileName.c_str()); - return; - } - LOG_INFO("Failed to delete File %{private}s", fileName.c_str()); -} - -/** - * Rename file. - */ -bool SqliteDatabaseUtils::RenameFile(std::string &oldFileName, std::string &newFileName) -{ - if (access(oldFileName.c_str(), F_OK) != 0) { - LOG_ERROR("File %{private}s does not exist", oldFileName.c_str()); - return false; - } - if (rename(oldFileName.c_str(), newFileName.c_str())) { - LOG_ERROR("Rename oldFileName = %{private}s to newFileName %{private}s", oldFileName.c_str(), - newFileName.c_str()); - return true; - } - return false; -} - -/** - * Get and Check default path. - */ -std::string SqliteDatabaseUtils::GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode) -{ - std::unique_lock lock(g_locker); - if (access(baseDir.c_str(), F_OK) != 0) { - if (MKDIR(baseDir.c_str())) { - errorCode = E_CREATE_FOLDER_FAIL; - } - } -#if defined(WINDOWS_PLATFORM) - std::string databasePath = baseDir + "\\rdb"; -#else - std::string databasePath = baseDir + "/rdb"; -#endif - if (access(databasePath.c_str(), F_OK) != 0) { - if (MKDIR(databasePath.c_str())) { - errorCode = E_CREATE_FOLDER_FAIL; - } - } - char canonicalPath[PATH_MAX + 1] = { 0 }; - if (REALPATH(databasePath.c_str(), canonicalPath, PATH_MAX) == nullptr) { - LOG_ERROR("Failed to obtain real path, errno:%{public}d", errno); - errorCode = E_INVALID_FILE_PATH; - return ""; - } - std::string realFilePath(canonicalPath); -#if defined(WINDOWS_PLATFORM) - realFilePath = realFilePath.append("\\").append(name); -#else - realFilePath = realFilePath.append("/").append(name); -#endif - return realFilePath; -} - -/** - * Get corrupt path from database path. - */ -std::string SqliteDatabaseUtils::GetCorruptPath(std::string &path, int &errorCode) -{ - std::string databaseFile = path; - std::string name = databaseFile.substr(databaseFile.find_last_of("/") + 1); - std::string parentFile = databaseFile.substr(0, databaseFile.find_last_of("/")); - std::string databaseTypeDir = parentFile.substr(parentFile.find_last_of("/") + 1); - size_t posDatabaseType = databaseTypeDir.find("_encrypt"); - - bool isEncrypt = false; - if (posDatabaseType != databaseTypeDir.npos) { - std::string databaseTypeDirStr = databaseTypeDir.substr(posDatabaseType); - std::string end = "_encrypt"; - if (databaseTypeDirStr.compare(end) == 0) { - isEncrypt = true; - } - } - - std::string databaseDir = parentFile.substr(0, parentFile.find_last_of("/")); - std::string encrypt = isEncrypt ? "_encrypt" : ""; - std::string corruptTypeDir = "corrupt" + encrypt; - std::string corruptPath = databaseDir + "/" + corruptTypeDir; - - if (access(corruptPath.c_str(), F_OK) != 0) { - if (MKDIR(corruptPath.c_str())) { - errorCode = E_CREATE_FOLDER_FAIL; - } - } - corruptPath = corruptPath + "/" + name; - return corruptPath; -} - -/** - * Get and Check no dbname path. - */ -std::string SqliteDatabaseUtils::GetDatabasePathNoName(std::string &context, RdbStoreConfig &fileConfig, int &errorCode) -{ - std::string securityLevel = fileConfig.GetDatabaseFileSecurityLevel(); - std::string databaseDir = GetDatabaseDir(fileConfig, securityLevel); - std::string databasePath = context + "/" + databaseDir; - std::unique_lock lock(g_locker); - if (access(databasePath.c_str(), F_OK) != 0) { - if (MKDIR(databasePath.c_str())) { - errorCode = E_CREATE_FOLDER_FAIL; - } - } - return databasePath; -} - -std::string SqliteDatabaseUtils::GetDatabaseDir(RdbStoreConfig &fileConfig, std::string &securityLevel) -{ - std::string databaseTypeDir = fileConfig.GetDatabaseFileType(); - std::string prefix; - if (!securityLevel.compare("S3") || !securityLevel.compare("S4")) { - prefix = "sece_"; - } else { - prefix = ""; - } - return prefix + databaseTypeDir; -} -} // namespace NativeRdb +/* + * 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 "sqlite_database_utils.h" + +#include +#include +#include + +#include +#include +#ifdef WINDOWS_PLATFORM +#include +#endif +#include +#include + +#include "logger.h" +#include "rdb_errno.h" + +#ifdef WINDOWS_PLATFORM +#define REALPATH(relPath, absPath, ...) (_fullpath(absPath, relPath, ##__VA_ARGS__)) +#define MKDIR(filePath) (mkdir(filePath)) +#else +#define REALPATH(absPath, relPath, ...) (realpath(absPath, relPath)) +#define MKDIR(filePath) (mkdir(filePath, g_mkdirMode)) +#endif + +namespace OHOS { +namespace NativeRdb { +std::map SqliteDatabaseUtils::g_statementType = SqliteDatabaseUtils::MapInit(); +std::mutex SqliteDatabaseUtils::g_locker; +// Set the file access permissions is 777 +int SqliteDatabaseUtils::g_mkdirMode = 0771; +std::map SqliteDatabaseUtils::MapInit() +{ + std::map temp; + temp["SEL"] = STATEMENT_SELECT; + temp["INS"] = STATEMENT_UPDATE; + temp["UPD"] = STATEMENT_UPDATE; + temp["REP"] = STATEMENT_UPDATE; + temp["DEL"] = STATEMENT_UPDATE; + temp["ATT"] = STATEMENT_ATTACH; + temp["DET"] = STATEMENT_DETACH; + temp["COM"] = STATEMENT_COMMIT; + temp["END"] = STATEMENT_COMMIT; + temp["ROL"] = STATEMENT_ROLLBACK; + temp["BEG"] = STATEMENT_BEGIN; + temp["PRA"] = STATEMENT_PRAGMA; + temp["CRE"] = STATEMENT_DDL; + temp["DRO"] = STATEMENT_DDL; + temp["ALT"] = STATEMENT_DDL; + + return temp; +} + +/** + * Obtains the type of SQL statement. + */ +int SqliteDatabaseUtils::GetSqlStatementType(std::string sql) +{ + if (sql.empty()) { + return STATEMENT_OTHER; + } + sql.erase(0, sql.find_first_not_of(" ")); + sql.erase(sql.find_last_not_of(" ") + 1); + + if (sql.length() < SQL_FIRST_CHARACTER) { + return STATEMENT_OTHER; + } + sql = sql.substr(0, SQL_FIRST_CHARACTER); + std::string prefixSql = sql; + transform(sql.begin(), sql.end(), prefixSql.begin(), ::toupper); + prefixSql = prefixSql.c_str(); + auto iter = g_statementType.find(prefixSql); + if (iter != g_statementType.end()) { + return iter->second; + } + return STATEMENT_OTHER; +} + +/** + * Delete the specified file. + */ +void SqliteDatabaseUtils::DeleteFile(std::string &fileName) +{ + if (access(fileName.c_str(), F_OK) != 0) { + LOG_ERROR("File %{private}s does not exist", fileName.c_str()); + return; + } + if (!remove(fileName.c_str())) { + LOG_ERROR("FileName= %{private}s has been deleted", fileName.c_str()); + return; + } + LOG_INFO("Failed to delete File %{private}s", fileName.c_str()); +} + +/** + * Rename file. + */ +bool SqliteDatabaseUtils::RenameFile(std::string &oldFileName, std::string &newFileName) +{ + if (access(oldFileName.c_str(), F_OK) != 0) { + LOG_ERROR("File %{private}s does not exist", oldFileName.c_str()); + return false; + } + if (rename(oldFileName.c_str(), newFileName.c_str())) { + LOG_ERROR("Rename oldFileName = %{private}s to newFileName %{private}s", oldFileName.c_str(), + newFileName.c_str()); + return true; + } + return false; +} + +/** + * Get and Check default path. + */ +std::string SqliteDatabaseUtils::GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode) +{ + std::unique_lock lock(g_locker); + if (access(baseDir.c_str(), F_OK) != 0) { + if (MKDIR(baseDir.c_str())) { + errorCode = E_CREATE_FOLDER_FAIL; + } + } +#if defined(WINDOWS_PLATFORM) + std::string databasePath = baseDir + "\\rdb"; +#else + std::string databasePath = baseDir + "/rdb"; +#endif + if (access(databasePath.c_str(), F_OK) != 0) { + if (MKDIR(databasePath.c_str())) { + errorCode = E_CREATE_FOLDER_FAIL; + } + } + char canonicalPath[PATH_MAX + 1] = { 0 }; + if (REALPATH(databasePath.c_str(), canonicalPath, PATH_MAX) == nullptr) { + LOG_ERROR("Failed to obtain real path, errno:%{public}d", errno); + errorCode = E_INVALID_FILE_PATH; + return ""; + } + std::string realFilePath(canonicalPath); +#if defined(WINDOWS_PLATFORM) + realFilePath = realFilePath.append("\\").append(name); +#else + realFilePath = realFilePath.append("/").append(name); +#endif + return realFilePath; +} + +/** + * Get corrupt path from database path. + */ +std::string SqliteDatabaseUtils::GetCorruptPath(std::string &path, int &errorCode) +{ + std::string databaseFile = path; + std::string name = databaseFile.substr(databaseFile.find_last_of("/") + 1); + std::string parentFile = databaseFile.substr(0, databaseFile.find_last_of("/")); + std::string databaseTypeDir = parentFile.substr(parentFile.find_last_of("/") + 1); + size_t posDatabaseType = databaseTypeDir.find("_encrypt"); + + bool isEncrypt = false; + if (posDatabaseType != databaseTypeDir.npos) { + std::string databaseTypeDirStr = databaseTypeDir.substr(posDatabaseType); + std::string end = "_encrypt"; + if (databaseTypeDirStr.compare(end) == 0) { + isEncrypt = true; + } + } + + std::string databaseDir = parentFile.substr(0, parentFile.find_last_of("/")); + std::string encrypt = isEncrypt ? "_encrypt" : ""; + std::string corruptTypeDir = "corrupt" + encrypt; + std::string corruptPath = databaseDir + "/" + corruptTypeDir; + + if (access(corruptPath.c_str(), F_OK) != 0) { + if (MKDIR(corruptPath.c_str())) { + errorCode = E_CREATE_FOLDER_FAIL; + } + } + corruptPath = corruptPath + "/" + name; + return corruptPath; +} +} // namespace NativeRdb } // namespace OHOS \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/sqlite_global_config.cpp b/relational_store/frameworks/native/rdb/src/sqlite_global_config.cpp index 126be6d60735222fb3e970f82a47d36a836534b7..12d9f02e903249f5052bfa9fb835c28102c58aa5 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_global_config.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_global_config.cpp @@ -23,16 +23,7 @@ namespace OHOS { namespace NativeRdb { -const int SqliteGlobalConfig::SOFT_HEAP_LIMIT = 8 * 1024 * 1024; /* 8MB */ -const bool SqliteGlobalConfig::CALLBACK_LOG_SWITCH = true; /* Sqlite callback log switch */ -const int SqliteGlobalConfig::CONNECTION_POOL_SIZE = 4; -const std::string SqliteGlobalConfig::MEMORY_DB_PATH = ":memory:"; -const int SqliteGlobalConfig::DB_PAGE_SIZE = 4096; -const std::string SqliteGlobalConfig::DEFAULT_JOURNAL_MODE = "WAL"; -const std::string SqliteGlobalConfig::WAL_SYNC_MODE = "FULL"; -const int SqliteGlobalConfig::JOURNAL_FILE_SIZE = 524288; /* 512KB */ -const int SqliteGlobalConfig::WAL_AUTO_CHECKPOINT = 100; /* 100 pages */ -constexpr int APP_DEFAULT_UMASK = 0002; + void SqliteGlobalConfig::InitSqliteGlobalConfig() { @@ -41,13 +32,14 @@ void SqliteGlobalConfig::InitSqliteGlobalConfig() SqliteGlobalConfig::SqliteGlobalConfig() { - umask(APP_DEFAULT_UMASK); + umask(GlobalExpr::APP_DEFAULT_UMASK); sqlite3_config(SQLITE_CONFIG_MULTITHREAD); - sqlite3_config(SQLITE_CONFIG_LOG, &SqliteLogCallback, CALLBACK_LOG_SWITCH ? reinterpret_cast(1) : NULL); + sqlite3_config(SQLITE_CONFIG_LOG, &SqliteLogCallback, + GlobalExpr::CALLBACK_LOG_SWITCH ? reinterpret_cast(1) : NULL); - sqlite3_soft_heap_limit(SOFT_HEAP_LIMIT); + sqlite3_soft_heap_limit(GlobalExpr::SOFT_HEAP_LIMIT); sqlite3_initialize(); } @@ -73,37 +65,37 @@ void SqliteGlobalConfig::SqliteLogCallback(const void *data, int err, const char int SqliteGlobalConfig::GetReadConnectionCount() { - return CONNECTION_POOL_SIZE - 1; + return GlobalExpr::CONNECTION_POOL_SIZE - 1; } std::string SqliteGlobalConfig::GetMemoryDbPath() { - return MEMORY_DB_PATH; + return GlobalExpr::MEMORY_DB_PATH; } int SqliteGlobalConfig::GetPageSize() { - return DB_PAGE_SIZE; + return GlobalExpr::DB_PAGE_SIZE; } std::string SqliteGlobalConfig::GetWalSyncMode() { - return WAL_SYNC_MODE; + return GlobalExpr::WAL_SYNC_MODE; } int SqliteGlobalConfig::GetJournalFileSize() { - return JOURNAL_FILE_SIZE; + return GlobalExpr::DB_JOURNAL_SIZE; } int SqliteGlobalConfig::GetWalAutoCheckpoint() { - return WAL_AUTO_CHECKPOINT; + return GlobalExpr::WAL_AUTO_CHECKPOINT; } std::string SqliteGlobalConfig::GetDefaultJournalMode() { - return DEFAULT_JOURNAL_MODE; + return GlobalExpr::DEFAULT_JOURNAL_MODE; } } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp b/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp index bc7035dcf57cdc6a6674274d45ab1cf33c777bef..3efd946f56a43a20b0e73663c9cb240aee2bf328 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp @@ -23,16 +23,11 @@ #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) #include "rdb_store_config.h" -#include "security_label.h" #include #endif namespace OHOS { namespace NativeRdb { -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -using SecurityLabel = OHOS::DistributedFS::ModuleSecurityLabel::SecurityLabel; -const std::string SqliteUtils::DATA_LEVEL[] = { "", "s0", "s1", "s2", "s3", "s4" }; -#endif const int SqliteUtils::STATEMENT_SELECT = 1; const int SqliteUtils::STATEMENT_UPDATE = 2; const int SqliteUtils::STATEMENT_ATTACH = 3; @@ -118,27 +113,5 @@ int SqliteUtils::RenameFile(const std::string srcFile, const std::string destFil { return rename(srcFile.c_str(), destFile.c_str()); } - -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -int SqliteUtils::SetFileSecurityLevel(const std::string &filePath, const int32_t &securityLevel) -{ - if (access(filePath.c_str(), F_OK) != 0) { - LOG_ERROR("The database file does not exist."); - return E_ERROR; - } - - bool result = SecurityLabel::SetSecurityLabel(filePath, DATA_LEVEL[securityLevel]); - if (result) { - LOG_INFO("Set database securityLabel %{public}s successful.", DATA_LEVEL[securityLevel].c_str()); - return E_OK; - } - return E_ERROR; -} - -std::string SqliteUtils::GetFileSecurityLevel(const std::string &filePath) -{ - return SecurityLabel::GetSecurityLabel(filePath); -} -#endif } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/frameworks/native/rdb/src/step_result_set.cpp b/relational_store/frameworks/native/rdb/src/step_result_set.cpp index b824ec24956035ccfb66ebf0253019dc445aeb74..afeee0e880ce82a02090ee378d8e2d11b5257298 100644 --- a/relational_store/frameworks/native/rdb/src/step_result_set.cpp +++ b/relational_store/frameworks/native/rdb/src/step_result_set.cpp @@ -40,13 +40,18 @@ StepResultSet::~StepResultSet() int StepResultSet::GetAllColumnNames(std::vector &columnNames) { - int errCode = PrepareStep(); - if (errCode) { - return errCode; + bool needRelease = false; + if (sqliteStatement == nullptr) { + int errCode = E_STEP_RESULT_QUERY_NOT_EXECUTED; + sqliteStatement = rdb->BeginStepQuery(errCode, sql, selectionArgs); + if (sqliteStatement == nullptr) { + return errCode; + } + needRelease = true; } int columnCount = 0; - errCode = sqliteStatement->GetColumnCount(columnCount); + auto errCode = sqliteStatement->GetColumnCount(columnCount); if (errCode) { return errCode; } @@ -61,7 +66,10 @@ int StepResultSet::GetAllColumnNames(std::vector &columnNames) } columnNames.push_back(columnName); } - + if (needRelease) { + rdb->EndStepQuery(); + sqliteStatement = nullptr; + } return E_OK; } diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_store_config.h b/relational_store/interfaces/inner_api/rdb/include/rdb_store_config.h index ff02111e0233f5f8ced2dc14f03eab5e49a08302..31ede92236a70faa7f029aa7f8f2da199e9280a6 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_store_config.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_store_config.h @@ -49,17 +49,19 @@ enum class DatabaseFileType { CORRUPT, }; -enum class DatabaseFileSecurityLevel : int32_t { - NO_LEVEL = 0, - S0, - S1, +enum class SecurityLevel : int32_t { + S1 = 1, S2, S3, S4, - LAST, + LAST }; -static const char *DatabaseFileSecurityLabel[] = { "", "S0", "S1", "S2", "S3", "S4" }; + +static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ +static constexpr int DB_JOURNAL_SIZE = 1048576; /* default file size : 1M */ +static constexpr char DB_DEFAULT_JOURNAL_MODE[] = "WAL"; +static constexpr char DB_DEFAULT_ENCRYPT_ALGO[] = "sha256"; using DistributedType = OHOS::DistributedRdb::RdbDistributedType; @@ -67,9 +69,12 @@ class RdbStoreConfig { public: RdbStoreConfig(const RdbStoreConfig &config); RdbStoreConfig(const std::string &path, StorageMode storageMode = StorageMode::MODE_DISK, bool readOnly = false, - const std::vector &encryptKey = std::vector(), const std::string &journalMode = "", + const std::vector &encryptKey = std::vector(), + const std::string &journalMode = DB_DEFAULT_JOURNAL_MODE, const std::string &syncMode = "", const std::string &databaseFileType = "", - const std::string &databaseFileSecurityLevel = "", bool isCreateNecessary = true); + SecurityLevel securityLevel = SecurityLevel::LAST, bool isCreateNecessary = true, + bool autoCheck = false, int journalSize = DB_JOURNAL_SIZE, int pageSize = DB_PAGE_SIZE, + const std::string &encryptAlgo = DB_DEFAULT_ENCRYPT_ALGO); ~RdbStoreConfig(); std::string GetName() const; std::string GetPath() const; @@ -79,8 +84,7 @@ public: bool IsReadOnly() const; bool IsMemoryRdb() const; std::string GetDatabaseFileType() const; - std::string GetDatabaseFileSecurityLevel() const; - int32_t GetSecurityLevel() const; + SecurityLevel GetSecurityLevel() const; void SetEncryptStatus(const bool status); bool IsEncrypt() const; bool IsCreateNecessary() const; @@ -91,7 +95,7 @@ public: void SetReadOnly(bool readOnly); void SetStorageMode(StorageMode storageMode); void SetDatabaseFileType(DatabaseFileType type); - void SetSecurityLevel(const int32_t& secLevel); + void SetSecurityLevel(SecurityLevel secLevel); void SetCreateNecessary(bool isCreateNecessary); // distributed rdb @@ -114,7 +118,14 @@ public: static std::string GetJournalModeValue(JournalMode journalMode); static std::string GetSyncModeValue(SyncMode syncMode); static std::string GetDatabaseFileTypeValue(DatabaseFileType databaseFileType); - static std::string GetDatabaseFileSecurityLevelValue(DatabaseFileSecurityLevel databaseFileSecurityLevel); + bool IsAutoCheck() const; + void SetAutoCheck(bool autoCheck); + int GetJournalSize() const; + void SetJournalSize(int journalSize); + int GetPageSize() const; + void SetPageSize(int pageSize); + const std::string GetEncryptAlgo() const; + void SetEncryptAlgo(const std::string &encryptAlgo); private: std::string name; @@ -122,9 +133,9 @@ private: StorageMode storageMode; std::string journalMode; std::string syncMode; + bool readOnly; std::string databaseFileType; - std::string databaseFileSecurityLevel; // distributed rdb DistributedType distributedType_ = DistributedRdb::RdbDistributedType::RDB_DEVICE_COLLABORATION; @@ -133,11 +144,16 @@ private: std::string moduleName_; bool isEncrypt_ = false; - int32_t securityLevel_ = 0; + SecurityLevel securityLevel = SecurityLevel::LAST; std::string uri_; std::string readPermission_; std::string writePermission_; bool isCreateNecessary_; + + bool autoCheck; + int journalSize; + int pageSize; + std::string encryptAlgo; }; } // namespace OHOS::NativeRdb diff --git a/relational_store/interfaces/inner_api/rdb/include/sqlite_database_utils.h b/relational_store/interfaces/inner_api/rdb/include/sqlite_database_utils.h index bdfe2b3f9d75596c62457adabdd0329f0e0172ff..5e21391c48956af7dff5fbdd9f972e574ff399f4 100644 --- a/relational_store/interfaces/inner_api/rdb/include/sqlite_database_utils.h +++ b/relational_store/interfaces/inner_api/rdb/include/sqlite_database_utils.h @@ -1,70 +1,67 @@ -/* - * 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_RDB_SQLITE_DATABASE_UTILS_H -#define NATIVE_RDB_SQLITE_DATABASE_UTILS_H - -#include -#include -#include - -#include "rdb_store_config.h" - -namespace OHOS { -namespace NativeRdb { -enum Type { - STATEMENT_SELECT = 1, - STATEMENT_UPDATE = 2, - STATEMENT_ATTACH = 3, - STATEMENT_DETACH = 4, - STATEMENT_BEGIN = 5, - STATEMENT_COMMIT = 6, - STATEMENT_ROLLBACK = 7, - STATEMENT_PRAGMA = 8, - STATEMENT_DDL = 9, - STATEMENT_OTHER = 99, - DATA_TYPE_BOOLEAN = 5, - DATA_TYPE_BLOB = 4, - DATA_TYPE_STRING = 3, - DATA_TYPE_FLOAT = 2, - DATA_TYPE_INTEGER = 1, - DATA_TYPE_NULL = 0, - SQL_FIRST_CHARACTER = 3 -}; - -class SqliteDatabaseUtils { -public: - static std::map MapInit(); - static int GetSqlStatementType(std::string sql); - static void DeleteFile(std::string &fileName); - static bool RenameFile(std::string &oldFileName, std::string &newFileName); - static std::string GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode); - static std::string GetCorruptPath(std::string &path, int &errorCode); - static std::string GetDatabasePathNoName(std::string &context, RdbStoreConfig &fileConfig, int &errorCode); - -private: - static std::map g_statementType; - static std::mutex g_locker; - static int g_mkdirMode; - - SqliteDatabaseUtils(); - ~SqliteDatabaseUtils(); - - static std::string GetDatabaseDir(RdbStoreConfig &fileConfig, std::string &securityLevel); -}; -} // namespace NativeRdb -} // namespace OHOS - -#endif +/* + * 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_RDB_SQLITE_DATABASE_UTILS_H +#define NATIVE_RDB_SQLITE_DATABASE_UTILS_H + +#include +#include +#include + +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +enum Type { + STATEMENT_SELECT = 1, + STATEMENT_UPDATE = 2, + STATEMENT_ATTACH = 3, + STATEMENT_DETACH = 4, + STATEMENT_BEGIN = 5, + STATEMENT_COMMIT = 6, + STATEMENT_ROLLBACK = 7, + STATEMENT_PRAGMA = 8, + STATEMENT_DDL = 9, + STATEMENT_OTHER = 99, + DATA_TYPE_BOOLEAN = 5, + DATA_TYPE_BLOB = 4, + DATA_TYPE_STRING = 3, + DATA_TYPE_FLOAT = 2, + DATA_TYPE_INTEGER = 1, + DATA_TYPE_NULL = 0, + SQL_FIRST_CHARACTER = 3 +}; + +class SqliteDatabaseUtils { +public: + static std::map MapInit(); + static int GetSqlStatementType(std::string sql); + static void DeleteFile(std::string &fileName); + static bool RenameFile(std::string &oldFileName, std::string &newFileName); + static std::string GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode); + static std::string GetCorruptPath(std::string &path, int &errorCode); + +private: + static std::map g_statementType; + static std::mutex g_locker; + static int g_mkdirMode; + + SqliteDatabaseUtils(); + ~SqliteDatabaseUtils(); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store_config.h b/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store_config.h index e27b21506e611b7aa738870ded09296ab849dc0f..5b880b9687c05e0367327f39ee3140ddc49dff96 100644 --- a/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store_config.h +++ b/relational_store/interfaces/inner_api/rdb/mock/include/rdb_store_config.h @@ -48,25 +48,28 @@ enum class DatabaseFileType { CORRUPT, }; -enum class DatabaseFileSecurityLevel : int32_t { - NO_LEVEL = 0, - S0, - S1, +enum class SecurityLevel : int32_t { + S1 = 1, S2, S3, S4, - LAST, + LAST }; -static const char *DatabaseFileSecurityLabel[] = { "", "S0", "S1", "S2", "S3", "S4" }; +static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ +static constexpr int DB_JOURNAL_SIZE = 1048576; /* default file size : 1M */ +static constexpr char DB_DEFAULT_JOURNAL_MODE[] = "delete"; +static constexpr char DB_DEFAULT_ENCRYPT_ALGO[] = "sha256"; class RdbStoreConfig { public: RdbStoreConfig(const RdbStoreConfig &config); RdbStoreConfig(const std::string &path, StorageMode storageMode = StorageMode::MODE_DISK, bool readOnly = false, - const std::vector &encryptKey = std::vector(), const std::string &journalMode = "", + const std::vector &encryptKey = std::vector(), const std::string &journalMode = "delete", const std::string &syncMode = "", const std::string &databaseFileType = "", - const std::string &databaseFileSecurityLevel = "", bool isCreateNecessary = true); + SecurityLevel securityLevel = SecurityLevel::LAST, bool isCreateNecessary = true, + bool autoCheck = false, int journalSize = 1048576, int pageSize = 4096, + const std::string &encryptAlgo = "sha256"); ~RdbStoreConfig(); std::string GetName() const; std::string GetPath() const; @@ -77,8 +80,7 @@ public: bool IsReadOnly() const; bool IsMemoryRdb() const; std::string GetDatabaseFileType() const; - std::string GetDatabaseFileSecurityLevel() const; - int32_t GetSecurityLevel() const; + SecurityLevel GetSecurityLevel() const; void SetEncryptStatus(const bool status); bool IsEncrypt() const; bool IsCreateNecessary() const; @@ -91,7 +93,7 @@ public: void SetStorageMode(StorageMode storageMode); void SetDatabaseFileType(DatabaseFileType type); void SetEncryptKey(const std::vector &encryptKey); - void SetSecurityLevel(const int32_t& secLevel); + void SetSecurityLevel(SecurityLevel secLevel); void ClearEncryptKey(); // distributed rdb @@ -113,7 +115,14 @@ public: static std::string GetJournalModeValue(JournalMode journalMode); static std::string GetSyncModeValue(SyncMode syncMode); static std::string GetDatabaseFileTypeValue(DatabaseFileType databaseFileType); - static std::string GetDatabaseFileSecurityLevelValue(DatabaseFileSecurityLevel databaseFileSecurityLevel); + bool IsAutoCheck() const; + void SetAutoCheck(bool autoCheck); + int GetJournalSize() const; + void SetJournalSize(int journalSize); + int GetPageSize() const; + void SetPageSize(int pageSize); + const std::string GetEncryptAlgo() const; + void SetEncryptAlgo(const std::string &encryptAlgo); private: std::string name; @@ -124,18 +133,22 @@ private: std::vector encryptKey; bool readOnly; std::string databaseFileType; - std::string databaseFileSecurityLevel; int32_t area_ = 0; std::string bundleName_; std::string moduleName_; bool isEncrypt_ = false; - int32_t securityLevel_ = 0; + SecurityLevel securityLevel = SecurityLevel::LAST; std::string uri_; std::string readPermission_; std::string writePermission_; bool isCreateNecessary_; + + bool autoCheck; + int journalSize; + int pageSize; + std::string encryptAlgo; }; } // namespace OHOS::NativeRdb diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/sqlite_database_utils.h b/relational_store/interfaces/inner_api/rdb/mock/include/sqlite_database_utils.h index bdfe2b3f9d75596c62457adabdd0329f0e0172ff..5e21391c48956af7dff5fbdd9f972e574ff399f4 100644 --- a/relational_store/interfaces/inner_api/rdb/mock/include/sqlite_database_utils.h +++ b/relational_store/interfaces/inner_api/rdb/mock/include/sqlite_database_utils.h @@ -1,70 +1,67 @@ -/* - * 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_RDB_SQLITE_DATABASE_UTILS_H -#define NATIVE_RDB_SQLITE_DATABASE_UTILS_H - -#include -#include -#include - -#include "rdb_store_config.h" - -namespace OHOS { -namespace NativeRdb { -enum Type { - STATEMENT_SELECT = 1, - STATEMENT_UPDATE = 2, - STATEMENT_ATTACH = 3, - STATEMENT_DETACH = 4, - STATEMENT_BEGIN = 5, - STATEMENT_COMMIT = 6, - STATEMENT_ROLLBACK = 7, - STATEMENT_PRAGMA = 8, - STATEMENT_DDL = 9, - STATEMENT_OTHER = 99, - DATA_TYPE_BOOLEAN = 5, - DATA_TYPE_BLOB = 4, - DATA_TYPE_STRING = 3, - DATA_TYPE_FLOAT = 2, - DATA_TYPE_INTEGER = 1, - DATA_TYPE_NULL = 0, - SQL_FIRST_CHARACTER = 3 -}; - -class SqliteDatabaseUtils { -public: - static std::map MapInit(); - static int GetSqlStatementType(std::string sql); - static void DeleteFile(std::string &fileName); - static bool RenameFile(std::string &oldFileName, std::string &newFileName); - static std::string GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode); - static std::string GetCorruptPath(std::string &path, int &errorCode); - static std::string GetDatabasePathNoName(std::string &context, RdbStoreConfig &fileConfig, int &errorCode); - -private: - static std::map g_statementType; - static std::mutex g_locker; - static int g_mkdirMode; - - SqliteDatabaseUtils(); - ~SqliteDatabaseUtils(); - - static std::string GetDatabaseDir(RdbStoreConfig &fileConfig, std::string &securityLevel); -}; -} // namespace NativeRdb -} // namespace OHOS - -#endif +/* + * 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_RDB_SQLITE_DATABASE_UTILS_H +#define NATIVE_RDB_SQLITE_DATABASE_UTILS_H + +#include +#include +#include + +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +enum Type { + STATEMENT_SELECT = 1, + STATEMENT_UPDATE = 2, + STATEMENT_ATTACH = 3, + STATEMENT_DETACH = 4, + STATEMENT_BEGIN = 5, + STATEMENT_COMMIT = 6, + STATEMENT_ROLLBACK = 7, + STATEMENT_PRAGMA = 8, + STATEMENT_DDL = 9, + STATEMENT_OTHER = 99, + DATA_TYPE_BOOLEAN = 5, + DATA_TYPE_BLOB = 4, + DATA_TYPE_STRING = 3, + DATA_TYPE_FLOAT = 2, + DATA_TYPE_INTEGER = 1, + DATA_TYPE_NULL = 0, + SQL_FIRST_CHARACTER = 3 +}; + +class SqliteDatabaseUtils { +public: + static std::map MapInit(); + static int GetSqlStatementType(std::string sql); + static void DeleteFile(std::string &fileName); + static bool RenameFile(std::string &oldFileName, std::string &newFileName); + static std::string GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode); + static std::string GetCorruptPath(std::string &path, int &errorCode); + +private: + static std::map g_statementType; + static std::mutex g_locker; + static int g_mkdirMode; + + SqliteDatabaseUtils(); + ~SqliteDatabaseUtils(); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif diff --git a/relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js b/relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js index cff5baa284561248130e691e6c33d87e2cd2a466..9b99b973f2c9dc929f93e5742f33f95239dabba5 100644 --- a/relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js +++ b/relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js @@ -134,8 +134,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0010 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0001', 0, async function (done) { - console.log(TAG + "************* testEqualTo0001 start *************"); + it('testDataAbilityDataAbilityEqualTo0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityDataAbilityEqualTo0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("booleanValue", true); @@ -146,7 +146,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testEqualTo0001 end *************"); + console.log(TAG + "************* testDataAbilityDataAbilityEqualTo0001 end *************"); }) /** @@ -154,8 +154,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0011 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0002', 0, async function (done) { - console.log(TAG + "************* testEqualTo0002 start *************"); + it('testDataAbilityDataAbilityEqualTo0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityDataAbilityEqualTo0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("byteValue", -128).or().equalTo("byteValue", 1); @@ -166,7 +166,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testEqualTo0002 end *************"); + console.log(TAG + "************* testDataAbilityEqualTo0002 end *************"); }) /** @@ -174,8 +174,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0012 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0003', 0, async function (done) { - console.log(TAG + "************* testEqualTo0003 start *************"); + it('testDataAbilityDataAbilityEqualTo0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEqualTo0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN"); @@ -186,7 +186,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testEqualTo0003 end *************"); + console.log(TAG + "************* testDataAbilityEqualTo0003 end *************"); }) /** @@ -194,8 +194,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0013 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0004', 0, async function (done) { - console.log(TAG + "************* testEqualTo0004 start *************"); + it('testDataAbilityDataAbilityEqualTo0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEqualTo0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("doubleValue", DOUBLE_MAX); @@ -206,7 +206,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testEqualTo0004 end *************"); + console.log(TAG + "************* testDataAbilityEqualTo0004 end *************"); }) /** @@ -214,8 +214,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0014 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0005', 0, async function (done) { - console.log(TAG + "************* testEqualTo0005 start *************"); + it('testDataAbilityDataAbilityEqualTo0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEqualTo0005 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("shortValue", -32768.0); @@ -226,7 +226,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testEqualTo0005 end *************"); + console.log(TAG + "************* testDataAbilityEqualTo0005 end *************"); }) /** @@ -234,8 +234,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0015 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0006', 0, async function (done) { - console.log(TAG + "************* testEqualTo0006 start *************"); + it('testDataAbilityDataAbilityEqualTo0006', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEqualTo0006 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("integerValue", 1); @@ -246,7 +246,7 @@ describe('dataAbilityPredicatesTest', function () { expect(2).assertEqual(result.getLong(0)); } done(); - console.log(TAG + "************* testEqualTo0006 end *************"); + console.log(TAG + "************* testDataAbilityEqualTo0006 end *************"); }) /** @@ -254,8 +254,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0016 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0007', 0, async function (done) { - console.log(TAG + "************* testEqualTo0007 start *************"); + it('testDataAbilityDataAbilityEqualTo0007', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEqualTo0007 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("longValue", 1); @@ -266,7 +266,7 @@ describe('dataAbilityPredicatesTest', function () { expect(2).assertEqual(result.getLong(0)) } done(); - console.log(TAG + "************* testEqualTo0007 end *************"); + console.log(TAG + "************* testDataAbilityEqualTo0007 end *************"); }) /** @@ -274,8 +274,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0017 * @tc.desc predicates equalTo normal test */ - it('testEqualTo0008', 0, async function (done) { - console.log(TAG + "************* testEqualTo0008 start *************"); + it('testDataAbilityEqualTo0008', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEqualTo0008 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("floatValue", -0.123); @@ -287,7 +287,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testEqualTo0008 end *************"); + console.log(TAG + "************* testDataAbilityEqualTo0008 end *************"); }) /** @@ -295,8 +295,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0020 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0001', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0001 start *************"); + it('testDataAbilityNotEqualTo0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("booleanValue", true); @@ -307,7 +307,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0001 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0001 end *************"); }) /** @@ -315,8 +315,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0021 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0002', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0002 start *************"); + it('testDataAbilityNotEqualTo0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("byteValue", -128); @@ -328,7 +328,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0002 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0002 end *************"); }) /** @@ -336,8 +336,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0022 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0003', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0003 start *************"); + it('testDataAbilityNotEqualTo0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("stringValue", "ABCDEFGHIJKLMN"); @@ -348,7 +348,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0003 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0003 end *************"); }) /** @@ -356,8 +356,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0023 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0004', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0004 start *************"); + it('testDataAbilityNotEqualTo0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("doubleValue", DOUBLE_MAX); @@ -368,7 +368,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0004 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0004 end *************"); }) /** @@ -376,8 +376,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0024 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0005', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0005 start *************"); + it('testDataAbilityNotEqualTo0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0005 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("shortValue", -32768); @@ -388,7 +388,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0005 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0005 end *************"); }) /** @@ -396,8 +396,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0025 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0006', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0006 start *************"); + it('testDataAbilityNotEqualTo0006', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0006 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("integerValue", 1); @@ -408,7 +408,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0006 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0006 end *************"); }) /** @@ -416,8 +416,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0026 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0007', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0007 start *************"); + it('testDataAbilityNotEqualTo0007', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0007 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("longValue", 1); @@ -428,7 +428,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0007 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0007 end *************"); }) /** @@ -436,8 +436,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0027 * @tc.desc predicates notEqualTo normal test */ - it('testNotEqualTo0008', 0, async function (done) { - console.log(TAG + "************* testNotEqualTo0008 start *************"); + it('testDataAbilityNotEqualTo0008', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotEqualTo0008 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notEqualTo("floatValue", -0.123); @@ -448,7 +448,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotEqualTo0008 end *************"); + console.log(TAG + "************* testDataAbilityNotEqualTo0008 end *************"); }) /** @@ -456,8 +456,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0030 * @tc.desc resultSet isNull normal test */ - it('testIsNull0001', 0, async function (done) { - console.log(TAG + "************* testIsNull001 start *************"); + it('testDataAbilityIsNull0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNull001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNull("primLongValue"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -466,7 +466,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNull0001 end *************"); + console.log(TAG + "************* testDataAbilityIsNull0001 end *************"); }) /** @@ -474,8 +474,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0031 * @tc.desc predicates isNull normal test */ - it('testIsNull0002', 0, async function (done) { - console.log(TAG + "************* testIsNull0002 start *************"); + it('testDataAbilityIsNull0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNull0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNull("longValue"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -484,7 +484,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNull0002 end *************"); + console.log(TAG + "************* testDataAbilityIsNull0002 end *************"); }) /** @@ -492,8 +492,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0032 * @tc.desc predicates isNull normal test */ - it('testIsNull0003', 0, async function (done) { - console.log(TAG + "************* testIsNull0003 start *************"); + it('testDataAbilityIsNull0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNull0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNull("stringValue"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -502,7 +502,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNull0003 end *************"); + console.log(TAG + "************* testDataAbilityIsNull0003 end *************"); }) /** @@ -510,8 +510,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0033 * @tc.desc predicates isNull normal test */ - it('testIsNull0004', 0, async function (done) { - console.log(TAG + "************* testIsNull0004 start *************"); + it('testDataAbilityIsNull0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNull0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNull("stringValueX"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -520,7 +520,7 @@ describe('dataAbilityPredicatesTest', function () { expect(-1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNull0004 end *************"); + console.log(TAG + "************* testDataAbilityIsNull0004 end *************"); }) /** @@ -528,8 +528,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0040 * @tc.desc predicates isNotNull normal test */ - it('testIsNotNull0001', 0, async function (done) { - console.log(TAG + "************* testIsNotNull0001 start *************"); + it('testDataAbilityIsNotNull0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNotNull0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNotNull("primLongValue"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -538,7 +538,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNotNull0001 end *************"); + console.log(TAG + "************* testDataAbilityIsNotNull0001 end *************"); }) /** @@ -546,8 +546,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0041 * @tc.desc predicates isNotNull normal test */ - it('testIsNotNull0002', 0, async function (done) { - console.log(TAG + "************* testIsNotNull0002 start *************"); + it('testDataAbilityIsNotNull0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNotNull0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNotNull("longValue"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -556,7 +556,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNotNull0002 end *************"); + console.log(TAG + "************* testDataAbilityIsNotNull0002 end *************"); }) /** @@ -564,8 +564,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0042 * @tc.desc predicates isNotNull normal test */ - it('testIsNotNull0003', 0, async function (done) { - console.log(TAG + "************* testIsNotNull0003 start *************"); + it('testDataAbilityIsNotNull0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNotNull0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNotNull("stringValue"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -574,7 +574,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNotNull0003 end *************"); + console.log(TAG + "************* testDataAbilityIsNotNull0003 end *************"); }) /** @@ -582,8 +582,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0043 * @tc.desc predicates isNotNull normal test */ - it('testIsNotNull0004', 0, async function (done) { - console.log(TAG + "************* testIsNotNull0004 start *************"); + it('testDataAbilityIsNotNull0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIsNotNull0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.isNotNull("stringValueX"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -592,7 +592,7 @@ describe('dataAbilityPredicatesTest', function () { expect(-1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIsNotNull0004 end *************"); + console.log(TAG + "************* testDataAbilityIsNotNull0004 end *************"); }) /** @@ -600,8 +600,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0050 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0001', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0001 start *************"); + it('testDataAbilityGreaterThan0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("stringValue", "ABC"); @@ -612,7 +612,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0001 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0001 end *************"); }) /** @@ -620,8 +620,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0051 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0002', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0002 start *************"); + it('testDataAbilityGreaterThan0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("doubleValue", 0.0); @@ -632,7 +632,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0002 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0002 end *************"); }) /** @@ -640,8 +640,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0052 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0003', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0003 start *************"); + it('testDataAbilityGreaterThan0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("integerValue", 1); @@ -652,7 +652,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0003 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0003 end *************"); }) /** @@ -660,8 +660,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0053 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0004', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0004 start *************"); + it('testDataAbilityGreaterThan0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("longValue", 1); @@ -672,7 +672,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0004 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0004 end *************"); }) @@ -681,8 +681,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0054 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0005', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0005 start *************"); + it('testDataAbilityGreaterThan0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0005 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("stringValue", "ZZZ"); @@ -693,7 +693,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0005 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0005 end *************"); }) /** @@ -701,8 +701,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0055 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0006', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0006 start *************"); + it('testDataAbilityGreaterThan0006', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0006 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("doubleValue", 999.0); @@ -713,7 +713,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0006 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0006 end *************"); }) /** @@ -721,8 +721,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0056 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0007', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0007 start *************"); + it('testDataAbilityGreaterThan0007', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0007 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("integerValue", -999); @@ -733,7 +733,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0007 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0007 end *************"); }) /** @@ -741,8 +741,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0057 * @tc.desc predicates greaterThan normal test */ - it('testGreaterThan0008', 0, async function (done) { - console.log(TAG + "************* testGreaterThan0008 start *************"); + it('testDataAbilityGreaterThan0008', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThan0008 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThan("longValue", -999); @@ -753,7 +753,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThan0008 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThan0008 end *************"); }) /** @@ -761,8 +761,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0060 * @tc.desc predicates greaterThanOrEqualTo normal test */ - it('testGreaterThanOrEqualTo0001', 0, async function (done) { - console.log(TAG + "************* testGreaterThanOrEqualTo0001 start *************"); + it('testDataAbilityGreaterThanOrEqualTo0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThanOrEqualTo("stringValue", "ABC"); @@ -773,7 +773,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThanOrEqualTo0001 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0001 end *************"); }) /** @@ -781,8 +781,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0061 * @tc.desc predicates greaterThanOrEqualTo normal test */ - it('testGreaterThanOrEqualTo0002', 0, async function (done) { - console.log(TAG + "************* testGreaterThanOrEqualTo0002 start *************"); + it('testDataAbilityGreaterThanOrEqualTo0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThanOrEqualTo("doubleValue", 0.0); @@ -793,7 +793,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThanOrEqualTo0002 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0002 end *************"); }) /** @@ -801,8 +801,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0062 * @tc.desc predicates greaterThanOrEqualTo normal test */ - it('testGreaterThanOrEqualTo0003', 0, async function (done) { - console.log(TAG + "************* testGreaterThanOrEqualTo0003 start *************"); + it('testDataAbilityGreaterThanOrEqualTo0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThanOrEqualTo("integerValue", 1); @@ -813,7 +813,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThanOrEqualTo0003 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0003 end *************"); }) /** @@ -821,8 +821,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0063 * @tc.desc predicates greaterThanOrEqualTo normal test */ - it('testGreaterThanOrEqualTo0004', 0, async function (done) { - console.log(TAG + "************* testGreaterThanOrEqualTo0004 start *************"); + it('testDataAbilityGreaterThanOrEqualTo0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.greaterThanOrEqualTo("longValue", 1); @@ -833,7 +833,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGreaterThanOrEqualTo0004 end *************"); + console.log(TAG + "************* testDataAbilityGreaterThanOrEqualTo0004 end *************"); }) /** @@ -841,8 +841,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0070 * @tc.desc predicates lessThan normal test */ - it('testLessThan0001', 0, async function (done) { - console.log(TAG + "************* testLessThan0001 start *************"); + it('testDataAbilityLessThan0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("stringValue", "ABD"); @@ -853,7 +853,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0001 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0001 end *************"); }) /** @@ -861,8 +861,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0071 * @tc.desc predicates lessThan normal test */ - it('testLessThan0002', 0, async function (done) { - console.log(TAG + "************* testLessThan0002 start *************"); + it('testDataAbilityLessThan0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("doubleValue", 0.0); @@ -873,7 +873,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0002 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0002 end *************"); }) /** @@ -881,8 +881,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0072 * @tc.desc predicates lessThan normal test */ - it('testLessThan0003', 0, async function (done) { - console.log(TAG + "************* testLessThan0003 start *************"); + it('testDataAbilityLessThan0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("integerValue", 1); @@ -893,7 +893,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0003 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0003 end *************"); }) /** @@ -901,8 +901,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0073 * @tc.desc predicates lessThan normal test */ - it('testLessThan0004', 0, async function (done) { - console.log(TAG + "************* testLessThan0004 start *************"); + it('testDataAbilityLessThan0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("longValue", 1); @@ -913,7 +913,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0004 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0004 end *************"); }) @@ -922,8 +922,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0074 * @tc.desc predicates lessThan normal test */ - it('testLessThan0005', 0, async function (done) { - console.log(TAG + "************* testLessThan0005 start *************"); + it('testDataAbilityLessThan0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0005 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("stringValue", "ABD"); @@ -934,7 +934,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0005 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0005 end *************"); }) /** @@ -942,8 +942,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0075 * @tc.desc predicates lessThan normal test */ - it('testLessThan0006', 0, async function (done) { - console.log(TAG + "************* testLessThan0006 start *************"); + it('testDataAbilityLessThan0006', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0006 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("doubleValue", 1.0); @@ -954,7 +954,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0006 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0006 end *************"); }) /** @@ -962,8 +962,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0076 * @tc.desc predicates lessThan normal test */ - it('testLessThan0007', 0, async function (done) { - console.log(TAG + "************* testLessThan0007 start *************"); + it('testDataAbilityLessThan0007', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0007 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("integerValue", -2147483648); @@ -974,7 +974,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0007 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0007 end *************"); }) /** @@ -982,8 +982,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0077 * @tc.desc predicates lessThan normal test */ - it('testLessThan0008', 0, async function (done) { - console.log(TAG + "************* testLessThan0008 start *************"); + it('testDataAbilityLessThan0008', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThan0008 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThan("longValue", -9223372036854775808); @@ -994,7 +994,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThan0008 end *************"); + console.log(TAG + "************* testDataAbilityLessThan0008 end *************"); }) @@ -1003,8 +1003,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0080 * @tc.desc predicates lessThanOrEqualTo normal test */ - it('testLessThanOrEqualTo0001', 0, async function (done) { - console.log(TAG + "************* testLessThanOrEqualTo0001 start *************"); + it('testDataAbilityLessThanOrEqualTo0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThanOrEqualTo("stringValue", "ABD"); @@ -1015,7 +1015,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThanOrEqualTo0001 end *************"); + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0001 end *************"); }) /** @@ -1023,8 +1023,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0081 * @tc.desc predicates lessThanOrEqualTo normal test */ - it('testLessThanOrEqualTo0002', 0, async function (done) { - console.log(TAG + "************* testLessThanOrEqualTo0002 start *************"); + it('testDataAbilityLessThanOrEqualTo0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThanOrEqualTo("doubleValue", 0.0); @@ -1035,7 +1035,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThanOrEqualTo0002 end *************"); + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0002 end *************"); }) /** @@ -1043,8 +1043,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0082 * @tc.desc predicates lessThanOrEqualTo normal test */ - it('testLessThanOrEqualTo0003', 0, async function (done) { - console.log(TAG + "************* testLessThanOrEqualTo0003 start *************"); + it('testDataAbilityLessThanOrEqualTo0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThanOrEqualTo("integerValue", 1); @@ -1055,7 +1055,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThanOrEqualTo0003 end *************"); + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0003 end *************"); }) /** @@ -1063,8 +1063,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0083 * @tc.desc predicates lessThanOrEqualTo normal test */ - it('testLessThanOrEqualTo0004', 0, async function (done) { - console.log(TAG + "************* testLessThanOrEqualTo0004 start *************"); + it('testDataAbilityLessThanOrEqualTo0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.lessThanOrEqualTo("longValue", 1); @@ -1075,7 +1075,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testLessThanOrEqualTo0004 end *************"); + console.log(TAG + "************* testDataAbilityLessThanOrEqualTo0004 end *************"); }) /** @@ -1083,8 +1083,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0090 * @tc.desc predicates between normal test */ - it('testBetween0001', 0, async function (done) { - console.log(TAG + "************* testBetween0001 start *************"); + it('testDataAbilityBetween0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("stringValue", "ABB", "ABD"); @@ -1095,7 +1095,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0001 end *************"); + console.log(TAG + "************* testDataAbilityBetween0001 end *************"); }) /** @@ -1103,8 +1103,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0091 * @tc.desc predicates between normal test */ - it('testBetween0002', 0, async function (done) { - console.log(TAG + "************* testBetween0002 start *************"); + it('testDataAbilityBetween0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("doubleValue", 0.0, DOUBLE_MAX); @@ -1115,7 +1115,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0002 end *************"); + console.log(TAG + "************* testDataAbilityBetween0002 end *************"); }) /** @@ -1123,8 +1123,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0092 * @tc.desc predicates between normal test */ - it('testBetween0003', 0, async function (done) { - console.log(TAG + "************* testBetween0003 start *************"); + it('testDataAbilityBetween0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("integerValue", 0, 1); @@ -1135,7 +1135,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0003 end *************"); + console.log(TAG + "************* testDataAbilityBetween0003 end *************"); }) /** @@ -1143,8 +1143,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0093 * @tc.desc predicates between normal test */ - it('testBetween0004', 0, async function (done) { - console.log(TAG + "************* testBetween0004 start *************"); + it('testDataAbilityBetween0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("longValue", 0, 2); @@ -1155,7 +1155,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0004 end *************"); + console.log(TAG + "************* testDataAbilityBetween0004 end *************"); }) /** @@ -1163,8 +1163,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0094 * @tc.desc predicates between normal test */ - it('testBetween0005', 0, async function (done) { - console.log(TAG + "************* testBetween0005 start *************"); + it('testDataAbilityBetween0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0005 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("stringValue", "ABB", "ABB"); @@ -1175,7 +1175,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0005 end *************"); + console.log(TAG + "************* testDataAbilityBetween0005 end *************"); }) /** @@ -1183,8 +1183,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0095 * @tc.desc predicates between normal test */ - it('testBetween0006', 0, async function (done) { - console.log(TAG + "************* testBetween0006 start *************"); + it('testDataAbilityBetween0006', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0006 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("doubleValue", DOUBLE_MAX, DOUBLE_MAX); @@ -1195,7 +1195,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0006 end *************"); + console.log(TAG + "************* testDataAbilityBetween0006 end *************"); }) /** @@ -1203,8 +1203,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0096 * @tc.desc predicates between normal test */ - it('testBetween0007', 0, async function (done) { - console.log(TAG + "************* testBetween0007 start *************"); + it('testDataAbilityBetween0007', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0007 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("integerValue", 1, 0); @@ -1215,7 +1215,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0007 end *************"); + console.log(TAG + "************* testDataAbilityBetween0007 end *************"); }) /** @@ -1223,8 +1223,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0097 * @tc.desc predicates between normal test */ - it('testBetween0008', 0, async function (done) { - console.log(TAG + "************* testBetween0008 start *************"); + it('testDataAbilityBetween0008', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBetween0008 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.between("longValue", 2, -1); @@ -1235,7 +1235,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBetween0008 end *************"); + console.log(TAG + "************* testDataAbilityBetween0008 end *************"); }) /** @@ -1243,8 +1243,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc test string value with notBetween. */ - it('testNotBetween0001', 0, async function (done) { - console.log(TAG + "************* testNotBetween0001 start *************"); + it('testDataAbilityNotBetween0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotBetween0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notBetween("stringValue", "ABB", "ABD"); @@ -1256,7 +1256,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotBetween0001 end *************"); + console.log(TAG + "************* testDataAbilityNotBetween0001 end *************"); }) /** @@ -1264,8 +1264,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc test double value with notBetween. */ - it('testNotBetween0002', 0, async function (done) { - console.log(TAG + "************* testNotBetween0002 start *************"); + it('testDataAbilityNotBetween0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotBetween0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notBetween("doubleValue", 0.0, DOUBLE_MAX); @@ -1277,7 +1277,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotBetween0002 end *************"); + console.log(TAG + "************* testDataAbilityNotBetween0002 end *************"); }) /** @@ -1285,8 +1285,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc test integer value with notBetween. */ - it('testNotBetween0003', 0, async function (done) { - console.log(TAG + "************* testNotBetween0003 start *************"); + it('testDataAbilityNotBetween0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotBetween0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notBetween("integerValue", 0, 1); @@ -1298,7 +1298,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotBetween0003 end *************"); + console.log(TAG + "************* testDataAbilityNotBetween0003 end *************"); }) /** @@ -1306,8 +1306,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc test long value with notBetween. */ - it('testNotBetween0004', 0, async function (done) { - console.log(TAG + "************* testNotBetween0004 start *************"); + it('testDataAbilityNotBetween0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotBetween0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notBetween("longValue", 0, 2); @@ -1319,7 +1319,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testNotBetween0004 end *************"); + console.log(TAG + "************* testDataAbilityNotBetween0004 end *************"); }) /** @@ -1327,8 +1327,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc end with ? by glob. */ - it('testGlob0001', 0, async function (done) { - console.log(TAG + "************* testGlob0001 start *************"); + it('testDataAbilityGlob0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGlob0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.glob("stringValue", "ABC*"); @@ -1340,7 +1340,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGlob0001 end *************"); + console.log(TAG + "************* testDataAbilityGlob0001 end *************"); }) /** @@ -1348,8 +1348,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc begin with * by glob. */ - it('testGlob0002', 0, async function (done) { - console.log(TAG + "************* testGlob0002 start *************"); + it('testDataAbilityGlob0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGlob0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.glob("stringValue", "*LMN"); @@ -1361,7 +1361,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGlob0002 end *************"); + console.log(TAG + "************* testDataAbilityGlob0002 end *************"); }) /** @@ -1369,8 +1369,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc end with ? by glob. */ - it('testGlob0003', 0, async function (done) { - console.log(TAG + "************* testGlob0003 start *************"); + it('testDataAbilityGlob0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGlob0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.glob("stringValue", "ABCDEFGHIJKLM?"); @@ -1382,7 +1382,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGlob0003 end *************"); + console.log(TAG + "************* testDataAbilityGlob0003 end *************"); }) /** @@ -1390,8 +1390,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc begin with ? by glob. */ - it('testGlob0004', 0, async function (done) { - console.log(TAG + "************* testGlob0004 start *************"); + it('testDataAbilityGlob0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGlob0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.glob("stringValue", "?BCDEFGHIJKLMN"); @@ -1403,7 +1403,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGlob0004 end *************"); + console.log(TAG + "************* testDataAbilityGlob0004 end *************"); }) /** @@ -1411,8 +1411,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc begin and end with * by glob. */ - it('testGlob0005', 0, async function (done) { - console.log(TAG + "************* testGlob0005 start *************"); + it('testDataAbilityGlob0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGlob0005 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.glob("stringValue", "*FGHI*"); @@ -1424,7 +1424,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGlob0005 end *************"); + console.log(TAG + "************* testDataAbilityGlob0005 end *************"); }) /** @@ -1432,8 +1432,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc begin and end with ? by glob. */ - it('testGlob0006', 0, async function (done) { - console.log(TAG + "************* testGlob0006 start *************"); + it('testDataAbilityGlob0006', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGlob0006 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.glob("stringValue", "?BCDEFGHIJKLM?"); @@ -1445,7 +1445,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testGlob0006 end *************"); + console.log(TAG + "************* testDataAbilityGlob0006 end *************"); }) /** @@ -1453,8 +1453,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0100 * @tc.desc predicates contains normal test */ - it('testContains0001', 0, async function (done) { - console.log(TAG + "************* testContains0001 start *************"); + it('testDataAbilityContains0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityContains0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.contains("stringValue", "DEF"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1463,7 +1463,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testContains0001 end *************"); + console.log(TAG + "************* testDataAbilityContains0001 end *************"); }) /** @@ -1471,8 +1471,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0101 * @tc.desc predicates contains normal test */ - it('testContains0002', 0, async function (done) { - console.log(TAG + "************* testContains0002 start *************"); + it('testDataAbilityContains0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityContains0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.contains("stringValue", "DEFX"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1481,7 +1481,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testContains0002 end *************"); + console.log(TAG + "************* testDataAbilityContains0002 end *************"); }) /** @@ -1489,8 +1489,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0102 * @tc.desc predicates contains normal test */ - it('testContains0003', 0, async function (done) { - console.log(TAG + "************* testContains0003 start *************"); + it('testDataAbilityContains0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityContains0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.contains("characterValue", "中"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1499,7 +1499,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testContains0003 end *************"); + console.log(TAG + "************* testDataAbilityContains0003 end *************"); }) /** @@ -1507,8 +1507,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0103 * @tc.desc predicates contains normal test */ - it('testContains0004', 0, async function (done) { - console.log(TAG + "************* testContains0004 start *************"); + it('testDataAbilityContains0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityContains0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.contains("characterValue", "#"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1517,7 +1517,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testContains0004 end *************"); + console.log(TAG + "************* testDataAbilityContains0004 end *************"); }) /** @@ -1525,8 +1525,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0110 * @tc.desc predicates beginsWith normal test */ - it('testBeginsWith0001', 0, async function (done) { - console.log(TAG + "************* testBeginsWith0001 start *************"); + it('testDataAbilityBeginsWith0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginsWith0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.beginsWith("stringValue", "ABC"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1535,7 +1535,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testBeginsWith0001 end *************"); + console.log(TAG + "************* testDataAbilityBeginsWith0001 end *************"); }) /** @@ -1543,8 +1543,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0111 * @tc.desc predicates beginsWith normal test */ - it('testBeginsWith0002', 0, async function (done) { - console.log(TAG + "************* testBeginsWith0002 start *************"); + it('testDataAbilityBeginsWith0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginsWith0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.beginsWith("stringValue", "ABCX"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1553,7 +1553,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testBeginsWith0002 end *************"); + console.log(TAG + "************* testDataAbilityBeginsWith0002 end *************"); }) /** @@ -1561,8 +1561,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0112 * @tc.desc predicates beginsWith normal test */ - it('testBeginsWith0003', 0, async function (done) { - console.log(TAG + "************* testBeginsWith0003 start *************"); + it('testDataAbilityBeginsWith0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginsWith0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.beginsWith("characterValue", "中"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1571,7 +1571,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testBeginsWith0003 end *************"); + console.log(TAG + "************* testDataAbilityBeginsWith0003 end *************"); }) /** @@ -1579,8 +1579,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0113 * @tc.desc predicates beginsWith normal test */ - it('testBeginsWith0004', 0, async function (done) { - console.log(TAG + "************* testBeginsWith0004 start *************"); + it('testDataAbilityBeginsWith0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginsWith0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.beginsWith("characterValue", "#"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1589,7 +1589,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testBeginsWith0004 end *************"); + console.log(TAG + "************* testDataAbilityBeginsWith0004 end *************"); }) /** @@ -1597,8 +1597,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0120 * @tc.desc predicates endsWith normal test */ - it('testEndsWith0001', 0, async function (done) { - console.log(TAG + "************* testEndsWith0001 start *************"); + it('testDataAbilityEndsWith0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEndsWith0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.endsWith("stringValue", "LMN"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1607,7 +1607,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testEndsWith0001 end *************"); + console.log(TAG + "************* testDataAbilityEndsWith0001 end *************"); }) /** @@ -1615,8 +1615,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0121 * @tc.desc predicates endsWith normal test */ - it('testEndsWith0002', 0, async function (done) { - console.log(TAG + "************* testEndsWith0002 start *************"); + it('testDataAbilityEndsWith0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEndsWith0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.endsWith("stringValue", "LMNX"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1625,7 +1625,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testEndsWith0002 end *************"); + console.log(TAG + "************* testDataAbilityEndsWith0002 end *************"); }) /** @@ -1633,8 +1633,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0122 * @tc.desc predicates endsWith normal test */ - it('testEndsWith0003', 0, async function (done) { - console.log(TAG + "************* testEndsWith0003 start *************"); + it('testDataAbilityEndsWith0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEndsWith0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.endsWith("characterValue", "中"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1643,7 +1643,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testEndsWith0003 end *************"); + console.log(TAG + "************* testDataAbilityEndsWith0003 end *************"); }) /** @@ -1651,8 +1651,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0123 * @tc.desc predicates endsWith normal test */ - it('testEndsWith0004', 0, async function (done) { - console.log(TAG + "************* testEndsWith0004 start *************"); + it('testDataAbilityEndsWith0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityEndsWith0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.endsWith("characterValue", "#"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1661,7 +1661,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testEndsWith0004 end *************"); + console.log(TAG + "************* testDataAbilityEndsWith0004 end *************"); }) /** @@ -1669,8 +1669,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0130 * @tc.desc predicates like normal test */ - it('testLike0001', 0, async function (done) { - console.log(TAG + "************* testLike0001 start *************"); + it('testDataAbilityLike0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLike0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "%LMN%"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1679,7 +1679,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLike0001 end *************"); + console.log(TAG + "************* testDataAbilityLike0001 end *************"); }) /** @@ -1687,8 +1687,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0130 * @tc.desc predicates like normal test */ - it('testLike0002', 0, async function (done) { - console.log(TAG + "************* testLike0002 start *************"); + it('testDataAbilityLike0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLike0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "%LMNX%"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1697,7 +1697,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLike0002 end *************"); + console.log(TAG + "************* testDataAbilityLike0002 end *************"); }) /** @@ -1705,8 +1705,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0132 * @tc.desc predicates like normal test */ - it('testLike0003', 0, async function (done) { - console.log(TAG + "************* testLike0003 start *************"); + it('testDataAbilityLike0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLike0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("characterValue", "%中%"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1715,7 +1715,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLike0003 end *************"); + console.log(TAG + "************* testDataAbilityLike0003 end *************"); }) /** @@ -1723,8 +1723,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0133 * @tc.desc predicates like normal test */ - it('testLike0004', 0, async function (done) { - console.log(TAG + "************* testLike0004 start *************"); + it('testDataAbilityLike0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLike0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("characterValue", "%#%"); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -1733,7 +1733,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLike0004 end *************"); + console.log(TAG + "************* testDataAbilityLike0004 end *************"); }) /** @@ -1741,8 +1741,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0140 * @tc.desc predicates beginWrap normal test */ - it('testBeginWrap0001', 0, async function (done) { - console.log(TAG + "************* testBeginWrap0001 start *************"); + it('testDataAbilityBeginWrap0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginWrap0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN") @@ -1758,7 +1758,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBeginWrap0001 end *************"); + console.log(TAG + "************* testDataAbilityBeginWrap0001 end *************"); }) /** @@ -1766,8 +1766,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0141 * @tc.desc predicates beginWrap normal test */ - it('testBeginWrap0002', 0, async function (done) { - console.log(TAG + "************* testBeginWrap0002 start *************"); + it('testDataAbilityBeginWrap0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginWrap0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN") @@ -1781,7 +1781,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBeginWrap0002 end *************"); + console.log(TAG + "************* testDataAbilityBeginWrap0002 end *************"); }) /** @@ -1789,8 +1789,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0142 * @tc.desc predicates beginWrap normal test */ - it('testBeginWrap0003', 0, async function (done) { - console.log(TAG + "************* testBeginWrap0003 start *************"); + it('testDataAbilityBeginWrap0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginWrap0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN") @@ -1804,7 +1804,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBeginWrap0003 end *************"); + console.log(TAG + "************* testDataAbilityBeginWrap0003 end *************"); }) /** @@ -1812,8 +1812,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0143 * @tc.desc predicates beginWrap normal test */ - it('testBeginWrap0004', 0, async function (done) { - console.log(TAG + "************* testBeginWrap0004 start *************"); + it('testDataAbilityBeginWrap0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginWrap0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN") @@ -1826,7 +1826,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBeginWrap0004 end *************"); + console.log(TAG + "************* testDataAbilityBeginWrap0004 end *************"); }) /** @@ -1834,8 +1834,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0144 * @tc.desc predicates beginWrap normal test */ - it('testBeginWrap0005', 0, async function (done) { - console.log(TAG + "************* testBeginWrap0005 start *************"); + it('testDataAbilityBeginWrap0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityBeginWrap0005 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN") @@ -1848,7 +1848,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testBeginWrap0005 end *************"); + console.log(TAG + "************* testDataAbilityBeginWrap0005 end *************"); }) /** @@ -1856,8 +1856,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0150 * @tc.desc predicates and normal test */ - it('testAnd0001', 0, async function (done) { - console.log(TAG + "************* testAnd0001 start *************"); + it('testDataAbilityAnd0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityAnd0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN") @@ -1870,7 +1870,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testAnd0001 end *************"); + console.log(TAG + "************* testDataAbilityAnd0001 end *************"); }) /** @@ -1878,8 +1878,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0151 * @tc.desc predicates or normal test */ - it('testAnd0002', 0, async function (done) { - console.log(TAG + "************* testAnd0002 start *************"); + it('testDataAbilityAnd0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityAnd0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN") @@ -1895,7 +1895,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testAnd0002 end *************"); + console.log(TAG + "************* testDataAbilityAnd0002 end *************"); }) /** @@ -1903,8 +1903,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0152 * @tc.desc predicates and normal test */ - it('testAnd0003', 0, async function (done) { - console.log(TAG + "************* testAnd0003 start *************"); + it('testDataAbilityAnd0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityAnd0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN").or().and().equalTo("integerValue", 1); @@ -1913,7 +1913,7 @@ describe('dataAbilityPredicatesTest', function () { console.log(TAG + "you should not start a request" + " with \"and\" or use or() before this function"); } done(); - console.log(TAG + "************* testAnd0003 end *************"); + console.log(TAG + "************* testDataAbilityAnd0003 end *************"); }) /** @@ -1921,8 +1921,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0153 * @tc.desc predicates and normal test */ - it('testAnd0004', 0, async function (done) { - console.log(TAG + "************* testAnd0004 start *************"); + it('testDataAbilityAnd0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityAnd0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN").or().or().equalTo("integerValue", 1); @@ -1932,7 +1932,7 @@ describe('dataAbilityPredicatesTest', function () { + "using function or() immediately after another or(). that is ridiculous."); } done(); - console.log(TAG + "************* testAnd0004 end *************"); + console.log(TAG + "************* testDataAbilityAnd0004 end *************"); }) /** @@ -1940,8 +1940,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0160 * @tc.desc predicates order normal test */ - it('testOrder0001', 0, async function (done) { - console.log(TAG + "************* testOrder0001 start *************"); + it('testDataAbilityOrder0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOrder0001 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN").orderByAsc("integerValue").distinct(); @@ -1958,7 +1958,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testOrder0001 end *************"); + console.log(TAG + "************* testDataAbilityOrder0001 end *************"); }) /** @@ -1966,8 +1966,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0161 * @tc.desc predicates order normal test */ - it('testOrder0002', 0, async function (done) { - console.log(TAG + "************* testOrder0002 start *************"); + it('testDataAbilityOrder0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOrder0002 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN").orderByDesc("integerValue").distinct(); @@ -1984,7 +1984,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testOrder0002 end *************"); + console.log(TAG + "************* testDataAbilityOrder0002 end *************"); }) /** @@ -1992,8 +1992,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0162 * @tc.desc predicates order normal test */ - it('testOrder0003', 0, async function (done) { - console.log(TAG + "************* testOrder0003 start *************"); + it('testDataAbilityOrder0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOrder0003 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN").orderByDesc("integerValueX").distinct(); @@ -2004,7 +2004,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testOrder0003 end *************"); + console.log(TAG + "************* testDataAbilityOrder0003 end *************"); }) /** @@ -2012,8 +2012,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0163 * @tc.desc predicates order normal test */ - it('testOrder0004', 0, async function (done) { - console.log(TAG + "************* testOrder0004 start *************"); + it('testDataAbilityOrder0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOrder0004 start *************"); { let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.equalTo("stringValue", "ABCDEFGHIJKLMN").orderByAsc("integerValueX").distinct(); @@ -2024,7 +2024,7 @@ describe('dataAbilityPredicatesTest', function () { result = null } done(); - console.log(TAG + "************* testOrder0004 end *************"); + console.log(TAG + "************* testDataAbilityOrder0004 end *************"); }) /** @@ -2032,8 +2032,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0170 * @tc.desc predicates limit normal test */ - it('testLimit0001', 0, async function (done) { - console.log(TAG + "************* testLimit0001 start *************"); + it('testDataAbilityLimit0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLimit0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(1); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2042,7 +2042,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLimit0001 end *************"); + console.log(TAG + "************* testDataAbilityLimit0001 end *************"); }) /** @@ -2050,8 +2050,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0171 * @tc.desc predicates limit normal test */ - it('testLimit0002', 0, async function (done) { - console.log(TAG + "************* testLimit0002 start *************"); + it('testDataAbilityLimit0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLimit0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(3); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2060,7 +2060,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLimit0002 end *************"); + console.log(TAG + "************* testDataAbilityLimit0002 end *************"); }) /** @@ -2068,8 +2068,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0172 * @tc.desc predicates limit normal test */ - it('testLimit0003', 0, async function (done) { - console.log(TAG + "************* testLimit0003 start *************"); + it('testDataAbilityLimit0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLimit0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(100); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2078,7 +2078,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLimit0003 end *************"); + console.log(TAG + "************* testDataAbilityLimit0003 end *************"); }) /** @@ -2086,8 +2086,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0173 * @tc.desc predicates limit normal test */ - it('testLimit0004', 0, async function (done) { - console.log(TAG + "************* testLimit0004 start *************"); + it('testDataAbilityLimit0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLimit0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "中").limitAs(1); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2096,7 +2096,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLimit0004 end *************"); + console.log(TAG + "************* testDataAbilityLimit0004 end *************"); }) /** @@ -2104,8 +2104,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0174 * @tc.desc predicates limit normal test */ - it('testLimit0005', 0, async function (done) { - console.log(TAG + "************* testLimit0005 start *************"); + it('testDataAbilityLimit0005', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLimit0005 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(0); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2114,7 +2114,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLimit0005 end *************"); + console.log(TAG + "************* testDataAbilityLimit0005 end *************"); }) /** @@ -2122,8 +2122,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0175 * @tc.desc predicates limit normal test */ - it('testLimit0006', 0, async function (done) { - console.log(TAG + "************* testLimit0006 start *************"); + it('testDataAbilityLimit0006', 0, async function (done) { + console.log(TAG + "************* testDataAbilityLimit0006 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(-1); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2132,7 +2132,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testLimit0006 end *************"); + console.log(TAG + "************* testDataAbilityLimit0006 end *************"); }) /** @@ -2140,8 +2140,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0180 * @tc.desc predicates offset normal test */ - it('testOffset0001', 0, async function (done) { - console.log(TAG + "************* testOffset0001 start *************"); + it('testDataAbilityOffset0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOffset0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(3).offsetAs(1); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2150,7 +2150,7 @@ describe('dataAbilityPredicatesTest', function () { expect(2).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testOffset0001 end *************"); + console.log(TAG + "************* testDataAbilityOffset0001 end *************"); }) /** @@ -2158,8 +2158,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0181 * @tc.desc predicates offset normal test */ - it('testOffset0002', 0, async function (done) { - console.log(TAG + "************* testOffset0002 start *************"); + it('testDataAbilityOffset0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOffset0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(3).offsetAs(0); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2168,7 +2168,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testOffset0002 end *************"); + console.log(TAG + "************* testDataAbilityOffset0002 end *************"); }) /** @@ -2176,8 +2176,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0182 * @tc.desc predicates offset normal test */ - it('testOffset0003', 0, async function (done) { - console.log(TAG + "************* testOffset0003 start *************"); + it('testDataAbilityOffset0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOffset0003 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(3).offsetAs(5); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2186,7 +2186,7 @@ describe('dataAbilityPredicatesTest', function () { expect(0).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testOffset0003 end *************"); + console.log(TAG + "************* testDataAbilityOffset0003 end *************"); }) /** @@ -2194,8 +2194,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0183 * @tc.desc predicates offset normal test */ - it('testOffset0004', 0, async function (done) { - console.log(TAG + "************* testOffset0004 start *************"); + it('testDataAbilityOffset0004', 0, async function (done) { + console.log(TAG + "************* testDataAbilityOffset0004 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").limitAs(3).offsetAs(-1); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2204,7 +2204,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testOffset0004 end *************"); + console.log(TAG + "************* testDataAbilityOffset0004 end *************"); }) /** @@ -2212,14 +2212,14 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0200 * @tc.desc predicates constructor test */ - it('testCreate0001', 0, async function (done) { - console.log(TAG + "************* testCreate0001 start *************"); + it('testDataAbilityCreate0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityCreate0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); let result = await rdbStore.query(predicates); expect(3).assertEqual(result.rowCount); done(); - console.log(TAG + "************* testCreate0001 end *************"); + console.log(TAG + "************* testDataAbilityCreate0001 end *************"); }) /** @@ -2227,14 +2227,14 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0201 * @tc.desc predicates constructor test */ - it('testCreate0002', 0, async function (done) { - console.log(TAG + "************* testCreate0002 start *************"); + it('testDataAbilityCreate0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityCreate0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); let predicates = dataAbility.createRdbPredicates("test", dataAbilityPredicates); let result = await rdbStore.query(predicates); expect(-1).assertEqual(result.rowCount); done(); - console.log(TAG + "************* testCreate0002 end *************"); + console.log(TAG + "************* testDataAbilityCreate0002 end *************"); }) @@ -2243,8 +2243,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0210 * @tc.desc predicates groupBy test */ - it('testGroupBy0001', 0, async function (done) { - console.log(TAG + "************* testGroupBy0001 start *************"); + it('testDataAbilityGroupBy0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGroupBy0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").groupBy(["characterValue"]); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2253,7 +2253,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testGroupBy0001 end *************"); + console.log(TAG + "************* testDataAbilityGroupBy0001 end *************"); }) /** @@ -2261,8 +2261,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0211 * @tc.desc predicates groupBy test */ - it('testGroupBy0002', 0, async function (done) { - console.log(TAG + "************* testGroupBy0002 start *************"); + it('testDataAbilityGroupBy0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityGroupBy0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").groupBy(["characterValueX"]); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2271,7 +2271,7 @@ describe('dataAbilityPredicatesTest', function () { expect(-1).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testGroupBy0002 end *************"); + console.log(TAG + "************* testDataAbilityGroupBy0002 end *************"); }) /** @@ -2279,8 +2279,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0220 * @tc.desc predicates indexedBy test */ - it('testIndexedBy0001', 0, async function (done) { - console.log(TAG + "************* testIndexedBy0001 start *************"); + it('testDataAbilityIndexedBy0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIndexedBy0001 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").indexedBy(["characterValue"]); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2289,7 +2289,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIndexedBy0001 end *************"); + console.log(TAG + "************* testDataAbilityIndexedBy0001 end *************"); }) /** @@ -2297,8 +2297,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number SUB_DDM_AppDataFWK_JSRDB_DataAbilityPredicates_0221 * @tc.desc predicates indexedBy test */ - it('testIndexedBy0002', 0, async function (done) { - console.log(TAG + "************* testIndexedBy0002 start *************"); + it('testDataAbilityIndexedBy0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityIndexedBy0002 start *************"); let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.like("stringValue", "ABCDEFGHIJKLMN").indexedBy(["characterValueX"]); let predicates = dataAbility.createRdbPredicates("AllDataType", dataAbilityPredicates); @@ -2306,7 +2306,7 @@ describe('dataAbilityPredicatesTest', function () { expect(3).assertEqual(result.rowCount); result = null done(); - console.log(TAG + "************* testIndexedBy0002 end *************"); + console.log(TAG + "************* testDataAbilityIndexedBy0002 end *************"); }) /** @@ -2314,8 +2314,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc the common and min value test with notin. */ - it('testNotIn0001', 0, async function (done) { - console.log(TAG + "************* testNotIn0001 start *************"); + it('testDataAbilityNotIn0001', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotIn0001 start *************"); var values = [1, -2147483648]; let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notIn("integerValue", values); @@ -2325,7 +2325,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result.close(); done(); - console.log(TAG + "************* testNotIn0001 end *************"); + console.log(TAG + "************* testDataAbilityNotIn0001 end *************"); }) /** @@ -2333,8 +2333,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc the common and max value test with notin. */ - it('testNotIn0002', 0, async function (done) { - console.log(TAG + "************* testNotIn0002 start *************"); + it('testDataAbilityNotIn0002', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotIn0002 start *************"); let values = [1, 2147483647]; let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notIn("integerValue", values); @@ -2344,7 +2344,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result.close(); done(); - console.log(TAG + "************* testNotIn0002 end *************"); + console.log(TAG + "************* testDataAbilityNotIn0002 end *************"); }) /** @@ -2352,8 +2352,8 @@ describe('dataAbilityPredicatesTest', function () { * @tc.number I4JWCV * @tc.desc the min and max value test with notin. */ - it('testNotIn0003', 0, async function (done) { - console.log(TAG + "************* testNotIn0003 start *************"); + it('testDataAbilityNotIn0003', 0, async function (done) { + console.log(TAG + "************* testDataAbilityNotIn0003 start *************"); var values = [-2147483648, 2147483647]; let dataAbilityPredicates = await new dataAbility.DataAbilityPredicates(); dataAbilityPredicates.notIn("integerValue", values); @@ -2363,7 +2363,7 @@ describe('dataAbilityPredicatesTest', function () { expect(1).assertEqual(result.rowCount); result.close(); done(); - console.log(TAG + "************* testNotIn0003 end *************"); + console.log(TAG + "************* testDataAbilityNotIn0003 end *************"); }) console.log(TAG + "*************Unit Test End*************"); }) \ No newline at end of file diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js index 19a3b0996a058d09473f608c4a82c0d1fe5c4ec0..aac7489cfbd2a51938a550c1efc4347c9572545b 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js @@ -75,6 +75,7 @@ describe('rdbStoreDistributedTest', function () { try { await rdbStore.executeSql(sqlStatement, null) console.log(TAG + "create table product success") + done() } catch (err) { console.log(TAG + "create table product failed") expect(null).assertFail() diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js index e89c3ecadb235685b03b6411b2323287eec3c181..206a015b7a206bb20c44406023b1df6860b39b58 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js @@ -44,7 +44,7 @@ describe('rdbResultSetTest', function () { rdbStore = null await dataRdb.deleteRdbStore("Resultset.db"); }) - //insert data + // insert data async function createTest() { console.log(TAG + "createTest data start"); { @@ -1563,10 +1563,8 @@ describe('rdbResultSetTest', function () { { let predicates = await new dataRdb.RdbPredicates("test") let resultSet = await rdbStore.query(predicates) - { - resultSet.goToRow(5) - expect(false).assertEqual(resultSet.isColumnNull(1)); - } + resultSet.goToRow(5) + expect(false).assertEqual(resultSet.isColumnNull(1)); resultSet = null; done(); console.log(TAG + "************* testIsColumnNull0003 end *************"); @@ -1659,10 +1657,13 @@ describe('rdbResultSetTest', function () { { let predicates = await new dataRdb.RdbPredicates("test") let resultSet = await rdbStore.query(predicates) - expect(-1).assertEqual(resultSet.getColumnIndex("")) - - resultSet = null; - done(); + try{ + expect(-1).assertEqual(resultSet.getColumnIndex("")) + } catch(err) { + expect("401").assertEqual(err.code) + } + resultSet = null + done() console.log(TAG + "************* testGetColumnIndex0004 end *************"); } }) @@ -1919,8 +1920,8 @@ describe('rdbResultSetTest', function () { let rows = [1, 2, -1, -2]; for (const i of rows) { - resultSet.goToRow(i); - expect(true).assertEqual(resultSet.isStarted); + resultSet.goToRow(i) + expect(true).assertEqual(resultSet.isStarted) expect("").assertEqual(resultSet.getString(1)) } diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js index 58908cf708768613c5416fee282e260c22069574..58951234aa6c560833a2e696b255515a3006c5e7 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js @@ -309,35 +309,8 @@ describe('rdbStoreDeleteTest', function () { */ it('testRdbStoreDelete0006', 0, async function (done) { console.log(TAG + "************* testRdbStoreDelete0006 start *************"); - var u8 = new Uint8Array([1, 2, 3]) - { - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - await rdbStore.insert("test", valueBucket) - } - { - const valueBucket = { - "name": "lisi", - "age": 28, - "salary": 100.5, - "blobType": u8, - } - await rdbStore.insert("test", valueBucket) - } - { - const valueBucket = { - "name": "lisi", - "age": 38, - "salary": 100.5, - "blobType": u8, - } - await rdbStore.insert("test", valueBucket) - } - { + + try { let predicates = await new dataRdb.RdbPredicates("") let deletePromise = rdbStore.delete(predicates) deletePromise.then(async (ret) => { @@ -346,6 +319,10 @@ describe('rdbStoreDeleteTest', function () { }).catch((err) => { console.log(TAG + "delete with null") }) + } catch (err) { + console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + done() } done() console.log(TAG + "************* testRdbStoreDelete0006 end *************"); diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js index 52a1865d3163affd8e238ba0504fe9b8ff7b8703..74e2da5ef7359856708e6a76cb0289899b001254 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js @@ -156,14 +156,21 @@ describe('rdbStoreInsertTest', function () { "salary": 100.5, "blobType": u8, } - let insertPromise = rdbStore.insert(null, valueBucket) - insertPromise.then(async (ret) => { - expect(1).assertEqual(ret) - console.log(TAG + "insert first done: " + ret) - expect(null).assertFail() - }).catch((err) => { - console.log(TAG + "insert with null table") - }) + try { + let insertPromise = rdbStore.insert(null, valueBucket) + insertPromise.then(async (ret) => { + expect(1).assertEqual(ret) + console.log(TAG + "insert first done: " + ret) + expect(null).assertFail() + }).catch((err) => { + console.log(TAG + "insert with null table") + expect(null).assertFail() + }) + } catch(err) { + console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + done() + } } done() console.log(TAG + "************* testRdbStoreInsert0003 end *************"); diff --git a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinBJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinBJsunit.test.js index 3e7aaba81bda47088b9dde06b23b50237fb5d662..45611edcd8336ff55cbb07cdfaa73470024924a0 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinBJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinBJsunit.test.js @@ -159,8 +159,8 @@ describe('rdbStorePredicatesJoinBTest', function () { expect(1004).assertEqual(resultSet.getInt(3)); expect("2000-12-17").assertEqual(resultSet.getString(4)); expect(8000.00).assertEqual(resultSet.getDouble(5)); - expect(8000.00).assertEqual(resultSet.getDouble(6)); - expect(true).assertEqual(resultSet.IsColumnNull(7)); + expect(true).assertEqual(resultSet.isColumnNull(6)); + expect(20).assertEqual(resultSet.getInt(7)); expect(20).assertEqual(resultSet.getInt(8)); expect("XueGongBu").assertEqual(resultSet.getString(9)); expect("ShangHai").assertEqual(resultSet.getString(10)); diff --git a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js index fea5b43981b71e0e0d16cc72d8129d41ef4387f3..55c9e3a0fa85a44223e61a385bfb6117cc922ce9 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js @@ -2175,9 +2175,10 @@ describe('rdbPredicatesTest', function () { it('testIndexedBy0001', 0, async function (done) { console.log(TAG + "************* testIndexedBy0001 start *************"); let predicates = await new dataRdb.RdbPredicates("AllDataType"); - predicates.like("stringValue", "ABCDEFGHIJKLMN").indexedBy(["characterValue"]); + predicates.like("stringValue", "ABCDEFGHIJKLMN").indexedBy("characterValue"); let result = await rdbStore.query(predicates); - expect(3).assertEqual(result.rowCount); + //test table have no indexe column, so return -1 + expect(-1).assertEqual(result.rowCount); result = null done(); console.log(TAG + "************* testIndexedBy0001 end *************"); @@ -2191,10 +2192,15 @@ describe('rdbPredicatesTest', function () { it('testIndexedBy0002', 0, async function (done) { console.log(TAG + "************* testIndexedBy0002 start *************"); let predicates = await new dataRdb.RdbPredicates("AllDataType"); - predicates.like("stringValue", "ABCDEFGHIJKLMN").indexedBy(["characterValueX"]); - let result = await rdbStore.query(predicates); - expect(3).assertEqual(result.rowCount); - result = null + try { + predicates.like("stringValue", "ABCDEFGHIJKLMN").indexedBy(["characterValueX"]); + let result = await rdbStore.query(predicates); + expect(3).assertEqual(result.rowCount); + result = null + } catch (err) { + console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + } done(); console.log(TAG + "************* testIndexedBy0002 end *************"); }) diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js index 3ef51216e01818f216bcf3bf6cfa27989f77ab24..58c55a78cc779abacff0c92749c971e0e5400d0a 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js @@ -15,6 +15,8 @@ import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; +import ability_featureAbility from '@ohos.ability.featureAbility' +var context const TAG = "[RDB_JSKITS_TEST]" const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; @@ -123,9 +125,11 @@ describe('rdbStoreTest', function () { let storePromise = dataRdb.getRdbStore(STORE_CONFIG, 6); storePromise.then(async (store) => { + console.log(TAG + "getRdbStore done:" + store); try { await store.executeSql(CREATE_TABLE_TEST); } catch (e) { + console.log(TAG + "create table error"); expect(null).assertFail(); } }).catch((err) => { @@ -187,7 +191,8 @@ describe('rdbStoreTest', function () { name: "secure.db", securityLevel: dataRdb.SecurityLevel.S3 } - let storePromise = dataRdb.getRdbStoreV9(config, 1); + context = ability_featureAbility.getContext() + let storePromise = dataRdb.getRdbStoreV9(context, config, 1); storePromise.then(async (store) => { try { await store.executeSql(CREATE_TABLE_TEST); @@ -216,12 +221,18 @@ describe('rdbStoreTest', function () { name: "secure.db", securityLevel: 8 } - let storePromise = dataRdb.getRdbStoreV9(config, 1); - storePromise.then(async (ret) => { - expect(null).assertFail(); - }).catch((err) => { - console.log(TAG + "getRdbStoreV9 with invalid securityLevel"); - }) + context = ability_featureAbility.getContext() + try{ + let storePromise = dataRdb.getRdbStoreV9(context, config, 1); + storePromise.then(async (ret) => { + expect(null).assertFail(); + }).catch((err) => { + console.log(TAG + "getRdbStoreV9 with invalid securityLevel"); + }) + } catch (err) { + expect("401").assertEqual(err.code) + done() + } storePromise = null done(); console.log(TAG + "************* testRdbStore0007 end *************"); diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js index 42fad51708d573de8b3c63a090e94e7cb22f2763..d3049d8255bffa5c67181791e4c1b943e53341c9 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js @@ -109,7 +109,7 @@ describe('rdbStoreUpdateTest', function () { console.log(TAG + "update error"); expect(null).assertFail(); }) - //await updatePromise + // await updatePromise } done(); @@ -131,7 +131,7 @@ describe('rdbStoreUpdateTest', function () { "salary": 100.5, "blobType": u8, } - { + try { let predicates = new dataRdb.RdbPredicates("") let updatePromise = rdbStore.update(valueBucket, predicates) updatePromise.then(async (ret) => { @@ -140,8 +140,12 @@ describe('rdbStoreUpdateTest', function () { }).catch((err) => { console.log(TAG + "update with null table name"); }) + } catch (err) { + console.log( + "catch err: update with null table name failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) } - { + try { const emptyBucket = {}; let predicates = await new dataRdb.RdbPredicates("test") let updatePromise = rdbStore.update(emptyBucket, predicates) @@ -151,8 +155,12 @@ describe('rdbStoreUpdateTest', function () { }).catch((err) => { console.log(TAG + "update with wrong valueBucket"); }) + } catch (err) { + console.log("catch err: update with wrong valueBucket failed, err: code=" + err.code + + " message=" + err.message) + expect("401").assertEqual(err.code) } - { + try { let predicates = await new dataRdb.RdbPredicates("test") await predicates.equalTo("aaa", "null") let updatePromise = rdbStore.update(valueBucket, predicates) @@ -162,6 +170,9 @@ describe('rdbStoreUpdateTest', function () { }).catch((err) => { console.log(TAG + "update with wrong condition"); }) + } catch (err) { + console.log("catch err: update with wrong condition failed, err: code=" + err.code + + " message=" + err.message) } } done(); @@ -193,7 +204,7 @@ describe('rdbStoreUpdateTest', function () { }).catch((err) => { console.log(TAG + "update with wrong table name"); }) - //await updatePromise + // await updatePromise } { let predicates = await new dataRdb.RdbPredicates("test") @@ -204,7 +215,7 @@ describe('rdbStoreUpdateTest', function () { }).catch((err) => { console.log(TAG + "update with wrong column name"); }) - //await updatePromise + // await updatePromise } } done(); @@ -236,7 +247,7 @@ describe('rdbStoreUpdateTest', function () { }).catch((err) => { console.log(TAG + "update with wrong condition"); }) - //await updatePromise + // await updatePromise } { const emptyBucket = {}; diff --git a/relational_store/test/js/rdb/unittest/src/V9_RdbstoreCallBackJsunit.test.js b/relational_store/test/js/rdb/unittest/src/V9_RdbstoreCallBackJsunit.test.js new file mode 100644 index 0000000000000000000000000000000000000000..423232123e5c9330ba6bdcc45e0df6ac32206f77 --- /dev/null +++ b/relational_store/test/js/rdb/unittest/src/V9_RdbstoreCallBackJsunit.test.js @@ -0,0 +1,249 @@ +/* + * 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 dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; + +const TAG = "[RDB_JSKITS_TEST]" +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + +const STORE_CONFIG = { + name: "V9_RDBCallbackTest.db", + securityLevel: dataRdb.SecurityLevel.S1, +} + +describe('V9_rdbStoreCallBackTest', async function () { + beforeAll(function () { + console.log(TAG + 'beforeAll') + }) + + beforeEach(async function () { + console.log(TAG + 'beforeEach') + }) + + afterEach(async function () { + console.log(TAG + 'afterEach') + }) + + afterAll(async function () { + console.log(TAG + 'afterAll') + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + /** + * @tc.name rdb callback test + * @tc.number testV9RdbStoreCallBackTest0001 + * @tc.desc rdb callback test + */ + it('testV9RdbStoreCallBackTest0001', 0, async function (done) { + console.log(TAG + "************* testV9RdbStoreCallBackTest0001 start *************"); + let context = featureAbility.getContext() + try{ + await dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1, async (err, rdbStoreV9) => { + if (err) { + console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + console.log("Get RdbStore successfully.") + await rdbStoreV9.executeSql(CREATE_TABLE_TEST, null) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + let rowId = await rdbStoreV9.insert("test", valueBucket) + console.log("Insert is successful, rowId = " + rowId) + let predicates = new dataRdb.RdbPredicatesV9("test") + predicates.equalTo("name", "zhangsan") + let resultSetV9 = await rdbStoreV9.query(predicates,[]) + expect(1).assertEqual(resultSetV9.rowCount) + expect(true).assertEqual(resultSetV9.goToFirstRow()) + const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id")) + const name = resultSetV9.getString(resultSetV9.getColumnIndex("name")) + const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age")) + const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary")) + const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType")) + console.log(TAG + "id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", blobType=" + blobType); + expect(1).assertEqual(id); + expect("zhangsan").assertEqual(name); + expect(18).assertEqual(age); + expect(100.5).assertEqual(salary); + expect(1).assertEqual(blobType[0]); + expect(2).assertEqual(blobType[1]); + expect(3).assertEqual(blobType[2]); + expect(false).assertEqual(resultSetV9.goToNextRow()) + let rows = await rdbStoreV9.delete(predicates) + expect(1).assertEqual(rows) + dataRdb.deleteRdbStoreV9(context, "V9_RDBCallbackTest.db", (err) => { + if (err) { + console.log("Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + console.log("Delete RdbStore successfully.") + done() + console.log(TAG + "************* testV9RdbStoreCallBackTest0001 end *************") + }); + }) + } catch(err) { + console.log("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + done() + console.log(TAG + "************* testV9RdbStoreCallBackTest0001 end *************") + } + }) + + /** + * @tc.name rdb callback test getRdbStoreV9 err params + * @tc.number testV9RdbStoreCallBackTest0002 + * @tc.desc rdb callback test getRdbStoreV9 err params + */ + it('testV9RdbStoreCallBackTest0002', 0, function (done) { + console.log(TAG + "************* testV9RdbStoreCallBackTest0002 start *************") + let context = featureAbility.getContext() + try{ + dataRdb.getRdbStoreV9(context, {dbname: "V9_RDBCallbackTest.db"}, 1, (err, rdbStoreV9) => { + if (err) { + console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + console.log("Get RdbStore successfully.") + expect(false).assertTrue() + }) + } catch(err) { + console.log("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + } + + done() + console.log(TAG + "************* testV9RdbStoreCallBackTest0002 end *************") + }) + + /** + * @tc.name rdb callback test getRdbStoreV9 err params + * @tc.number testV9RdbStoreCallBackTest0003 + * @tc.desc rdb callback test getRdbStoreV9 err params + */ + it('testV9RdbStoreCallBackTest0003', 0, function (done) { + console.log(TAG + "************* testV9RdbStoreCallBackTest0003 start *************") + let context = featureAbility.getContext() + try{ + dataRdb.getRdbStoreV9(null, {name: "V9_RDBCallbackTest.db"}, 1, (err, rdbStoreV9) => { + if (err) { + console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + console.log("Get RdbStore successfully.") + expect(false).assertTrue() + }) + } catch(err) { + console.log("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + } + + done() + console.log(TAG + "************* testV9RdbStoreCallBackTest0003 end *************") + }) + + /** + * @tc.name rdb callback test getRdbStoreV9 ok params + * @tc.number testV9RdbStoreCallBackTest0004 + * @tc.desc rdb callback test getRdbStoreV9 ok params + */ + it('testV9RdbStoreCallBackTest0004', 0, function (done) { + console.log(TAG + "************* testV9RdbStoreCallBackTest0004 start *************") + let context = featureAbility.getContext() + try{ + dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1, (err, rdbStoreV9) => { + if (err) { + console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + console.log("Get RdbStore successfully.") + done() + }) + } catch(err) { + console.log("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + done() + console.log(TAG + "************* testV9RdbStoreCallBackTest0004 end *************") + }) + + /** + * @tc.name rdb callback test deleteRdbStoreV9 err params + * @tc.number testV9RdbStoreCallBackTest0005 + * @tc.desc rdb callback test deleteRdbStoreV9 err params + */ + it('testV9RdbStoreCallBackTest0005', 0, async function (done) { + console.log(TAG + "************* testV9RdbStoreCallBackTest0005 start *************"); + let context = featureAbility.getContext() + let rdbStoreV9; + try{ + rdbStoreV9 = await dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1) + } catch(err) { + console.log("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + try{ + dataRdb.deleteRdbStoreV9(context, 12345, (err) => { + if (err) { + console.log("Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + console.log("Delete RdbStore successfully.") + expect(false).assertTrue() + }); + } catch(err) { + console.log("catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + done() + } + done() + console.log(TAG + "************* testV9RdbStoreCallBackTest0005 end *************"); + }) + + /** + * @tc.name rdb callback test deleteRdbStoreV9 OK params + * @tc.number testV9RdbStoreCallBackTest0006 + * @tc.desc rdb callback test deleteRdbStoreV9 OK params + */ + it('testV9RdbStoreCallBackTest0006', 0, async function (done) { + console.log(TAG + "************* testV9RdbStoreCallBackTest0006 start *************") + let context = featureAbility.getContext() + dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1).then((rdbStoreV9)=>{ + try{ + dataRdb.deleteRdbStoreV9(context, "V9_RDBCallbackTest.db", (err) => { + if (err) { + console.log("Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + console.log("Delete RdbStore successfully.") + done() + console.log(TAG + "************* testV9RdbStoreCallBackTest0006 end *************") + }); + } catch(err) { + console.log("222catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + }).catch((err) => { + console.info("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + }) + }) + + console.log(TAG + "*************Unit Test End*************"); +}) \ No newline at end of file diff --git a/relational_store/test/js/rdb/unittest/src/V9_RdbstorePromiseJsunit.test.js b/relational_store/test/js/rdb/unittest/src/V9_RdbstorePromiseJsunit.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6e9aad5e893929bf2bf79ee6033fb24566de7188 --- /dev/null +++ b/relational_store/test/js/rdb/unittest/src/V9_RdbstorePromiseJsunit.test.js @@ -0,0 +1,204 @@ +/* + * 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 dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; + +const TAG = "[RDB_JSKITS_TEST]" +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + +const STORE_CONFIG = { + name: "V9_RDBPromiseTest.db", + securityLevel: dataRdb.SecurityLevel.S1, +} + +describe('V9_rdbStorePromiseTest', function () { + beforeAll(function () { + console.info(TAG + 'beforeAll') + }) + + beforeEach(async function () { + console.info(TAG + 'beforeEach') + }) + + afterEach(async function () { + console.info(TAG + 'afterEach') + }) + + afterAll(async function () { + console.info(TAG + 'afterAll') + }) + + console.log(TAG + "*************Unit Test Begin*************"); + /** + * @tc.name rdb V9 base use + * @tc.number testV9RdbStorePromiseTest0001 + * @tc.desc rdb V9 base use + */ + it('testV9RdbStorePromiseTest0001', 0, async function (done) { + console.log(TAG + "************* testV9RdbStorePromiseTest0001 start *************"); + let context = featureAbility.getContext() + try{ + dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1).then(async (rdbStoreV9) => { + console.log("Get RdbStore successfully.") + await rdbStoreV9.executeSql(CREATE_TABLE_TEST, null) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStoreV9.insert("test", valueBucket) + let predicates = new dataRdb.RdbPredicatesV9("test") + console.log("Create RdbPredicates OK") + predicates.equalTo("name", "zhangsan") + rdbStoreV9.query(predicates, []).then((resultSetV9) => { + expect(1).assertEqual(resultSetV9.rowCount) + expect(true).assertEqual(resultSetV9.goToFirstRow()) + const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id")) + const name = resultSetV9.getString(resultSetV9.getColumnIndex("name")) + const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age")) + const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary")) + const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType")) + console.log(TAG + "id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", blobType=" + blobType); + expect(1).assertEqual(id); + expect("zhangsan").assertEqual(name); + expect(18).assertEqual(age); + expect(100.5).assertEqual(salary); + expect(1).assertEqual(blobType[0]); + expect(2).assertEqual(blobType[1]); + expect(3).assertEqual(blobType[2]); + expect(false).assertEqual(resultSetV9.goToNextRow()) + rdbStoreV9.delete(predicates).then((rows) => { + console.log("Delete rows: " + rows) + expect(1).assertEqual(rows) + dataRdb.deleteRdbStoreV9(context, "V9_RDBPromiseTest.db").then(() => { + console.log("Delete RdbStore successfully.") + done() + console.log(TAG + "************* testV9RdbStorePromiseTest0001 end *************"); + }) + }) + }) + }) + } catch(err) { + console.info("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(null).assertFail() + done() + console.log(TAG + "************* testV9RdbStorePromiseTest0001 end *************"); + } + }) + + /** + * @tc.name rdb getRdbStoreV9 err params + * @tc.number testV9RdbStorePromiseTest0002 + * @tc.desc rdb getRdbStoreV9 err params + */ + it('testV9RdbStorePromiseTest0002', 0, async function (done) { + console.log(TAG + "************* testV9RdbStorePromiseTest0002 start *************") + let context = featureAbility.getContext() + try{ + dataRdb.getRdbStoreV9(context, {dbname: "V9_RDBCallbackTest.db"}, 1).then((rdbStoreV9) => { + console.log("Get RdbStore successfully.") + expect(false).assertTrue() + }).catch((err) => { + console.info("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + }) + } catch(err) { + console.info("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + done() + } + done() + console.log(TAG + "************* testV9RdbStorePromiseTest0002 end *************") + }) + + /** + * @tc.name rdb getRdbStoreV9 ok params + * @tc.number testV9RdbStorePromiseTest0003 + * @tc.desc rdb getRdbStoreV9 ok params + */ + it('testV9RdbStorePromiseTest0003', 0, async function (done) { + console.log(TAG + "************* testV9RdbStorePromiseTest0003 start *************"); + let context = featureAbility.getContext() + try{ + dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1).then((rdbStoreV9) => { + console.log("Get RdbStore successfully.") + done() + }).catch((err) => { + console.info("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + }) + } catch(err) { + console.info("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + done() + console.log(TAG + "************* testV9RdbStorePromiseTest0003 end *************") + }) + + /** + * @tc.name rdb deleteRdbStoreV9 err params + * @tc.number testV9RdbStorePromiseTest0004 + * @tc.desc rdb deleteRdbStoreV9 err params + */ + it('testV9RdbStorePromiseTest0004', 0, async function (done) { + console.log(TAG + "************* testV9RdbStorePromiseTest0004 start *************") + let context = featureAbility.getContext() + let rdbStoreV9 = await dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1) + try{ + dataRdb.deleteRdbStoreV9(context, 123454345).then((rdbStoreV9) => { + console.log("Delete RdbStore successfully.") + expect(false).assertTrue() + }).catch((err) => { + console.info("Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + }) + } catch(err) { + console.info("catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + done() + } + done() + console.log(TAG + "************* testV9RdbStorePromiseTest0004 end *************") + }) + + /** + * @tc.name rdb deleteRdbStoreV9 OK params + * @tc.number testV9RdbStorePromiseTest0004 + * @tc.desc rdb deleteRdbStoreV9 OK params + */ + it('testV9RdbStorePromiseTest0005', 0, async function (done) { + console.log(TAG + "************* testV9RdbStorePromiseTest0005 start *************"); + let context = featureAbility.getContext() + let rdbStoreV9 = await dataRdb.getRdbStoreV9(context, STORE_CONFIG, 1) + try{ + dataRdb.deleteRdbStoreV9(context, "V9_RDBCallbackTest.db").then((err) => { + console.log("Delete RdbStore successfully.") + done() + }).catch((err) => { + console.info("Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + }) + } catch(err) { + console.info("catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect(false).assertTrue() + } + done() + console.log(TAG + "************* testV9RdbStorePromiseTest0005 end *************") + }) + + console.log(TAG + "*************Unit Test End*************"); +}) \ No newline at end of file diff --git a/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test_agent.cpp b/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test_agent.cpp index cca16ac25aee13dfbf9ccc3436c1df7d1b0cd95a..8d84bfd5ca78493080ae3ea9076f7babce2d863a 100644 --- a/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test_agent.cpp +++ b/relational_store/test/native/rdb/distributedtest/rdb_store_impl_test/distributed_test_agent.cpp @@ -134,14 +134,12 @@ int DistributedTestAgent::OnProcessMsg(const std::string &strMsg, int len, std:: std::unique_ptr resultSet = store_->QuerySql("SELECT * FROM test WHERE name = ?", std::vector { "zhangsan" }); if (resultSet!= nullptr) { - int ret; int position; int columnIndex; std::string strVal; - ret = resultSet->GetRowIndex(position); - status = position; + resultSet->GetRowIndex(position); resultSet->GoToFirstRow(); - ret = resultSet->GetColumnIndex("name", columnIndex); + resultSet->GetColumnIndex("name", columnIndex); resultSet->GetString(columnIndex, strVal); strReturnValue = strVal; } else { diff --git a/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp b/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp index 79370859e502fed03be4cd887faf1b8ead9091b0..d5f28d2a37831870f1152068da8ac39f0c0877a3 100644 --- a/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_attach_test.cpp @@ -18,10 +18,10 @@ #include #include "common.h" -#include "logger.h" #include "rdb_errno.h" #include "rdb_helper.h" #include "rdb_open_callback.h" +#include "rdb_store_config.h" using namespace testing::ext; using namespace OHOS::NativeRdb; @@ -124,9 +124,6 @@ HWTEST_F(RdbAttachTest, RdbStore_Attach_001, TestSize.Level1) int ret = store->ExecuteSql("ATTACH '" + ATTACHED_DATABASE_NAME + "' as attached"); EXPECT_EQ(ret, E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE); - - ret = store->ExecuteSql("attach '" + ATTACHED_DATABASE_NAME + "' as attached"); - EXPECT_EQ(ret, E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE); } /** diff --git a/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp b/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp index d2194538c61af0f80acb75602eadf6972add7781..410d66571bb8ac0612762564092a5237409fbc6c 100644 --- a/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_distributed_test.cpp @@ -135,7 +135,7 @@ void RdbStoreDistributedTest::CheckResultSet(std::shared_ptr &store) EXPECT_EQ(position, -1); ret = resultSet->GetColumnType(0, columnType); - EXPECT_EQ(ret, E_ERROR); + EXPECT_EQ(ret, E_INVALID_STATEMENT); ret = resultSet->GoToFirstRow(); EXPECT_EQ(ret, E_OK); diff --git a/relational_store/test/native/rdb/unittest/rdb_encrypt_decrypt_test.cpp b/relational_store/test/native/rdb/unittest/rdb_encrypt_decrypt_test.cpp index f542fd4a995902194914a1de8b71f5d44a99f2b6..fb3a576780599852353da9e8958e96254d974f78 100644 --- a/relational_store/test/native/rdb/unittest/rdb_encrypt_decrypt_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_encrypt_decrypt_test.cpp @@ -235,24 +235,6 @@ HWTEST_F(RdbEncryptTest, RdbStore_Encrypt_04, TestSize.Level1) EXPECT_EQ(ret, -1); } -/** - * @tc.name: RdbStore_Encrypt_Decrypt_Test_005 - * @tc.desc: test RdbStore Get Encrypted Store with empty boundlename - * @tc.type: FUNC - * @tc.require: - * @tc.author: - */ -HWTEST_F(RdbEncryptTest, RdbStore_Encrypt_05, TestSize.Level1) -{ - RdbStoreConfig config(RdbEncryptTest::ENCRYPTED_DATABASE_NAME); - config.SetEncryptStatus(true); - config.SetBundleName(""); - EncryptTestOpenCallback helper; - int errCode; - std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); - EXPECT_EQ(store, nullptr); -} - /** * @tc.name: RdbStore_Encrypt_Decrypt_Test_006 * @tc.desc: test SaveSecretKeyToFile when KeyFileType isNot PUB_KEY_FILE diff --git a/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp b/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp index f94382f406a4272b779af385d994bea1038077db..06024f27b9a2ca73bbb52d884401e1ef6cdfdee9 100644 --- a/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp @@ -239,6 +239,11 @@ HWTEST_F(RdbExecuteTest, RdbStore_Execute_003, TestSize.Level1) EXPECT_EQ(ret, E_OK); EXPECT_EQ(pageSize, 4096); + int64_t journalSize; + ret = store->ExecuteAndGetLong(journalSize, "PRAGMA journal_size_limit"); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(journalSize, 1048576); + std::string journalMode; ret = store->ExecuteAndGetString(journalMode, "PRAGMA journal_mode"); EXPECT_EQ(ret, E_OK); diff --git a/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp b/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp index 3e491ceaf465d5636bf13c6f20474ce02dc23ee3..94bb34f76788ccea00dd2406a7f6ad58f1bdf08e 100644 --- a/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_insert_test.cpp @@ -155,7 +155,7 @@ void RdbStoreInsertTest::CheckResultSet(std::shared_ptr &store) EXPECT_EQ(position, -1); ret = resultSet->GetColumnType(0, columnType); - EXPECT_EQ(ret, E_ERROR); + EXPECT_EQ(ret, E_INVALID_STATEMENT); ret = resultSet->GoToFirstRow(); EXPECT_EQ(ret, E_OK); @@ -187,7 +187,7 @@ void RdbStoreInsertTest::CheckResultSet(std::shared_ptr &store) EXPECT_EQ(ret, E_ERROR); ret = resultSet->GetColumnType(columnIndex, columnType); - EXPECT_EQ(ret, E_OK); + EXPECT_EQ(ret, E_INVALID_STATEMENT); ret = resultSet->Close(); EXPECT_EQ(ret, E_OK); @@ -719,4 +719,4 @@ HWTEST_F(RdbStoreInsertTest, RdbStore_BatchInsert_001, TestSize.Level1) int rowCount = 0; resultSet->GetRowCount(rowCount); EXPECT_EQ(100, rowCount); -} \ No newline at end of file +} diff --git a/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp b/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp index 67e88f868cee471880628bb34a6cfb24f89ed61f..327348ff77459e8eb6a67008e2f0e8626fd96ed0 100644 --- a/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_predicates_test.cpp @@ -1,1564 +1,1560 @@ -/* - * 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 -#include -#include -#include -#include -#include -#include - -#include "common.h" -#include "rdb_errno.h" -#include "rdb_helper.h" -#include "rdb_open_callback.h" -#include "rdb_predicates.h" - -using namespace testing::ext; -using namespace OHOS::NativeRdb; - -class AllDataType { -public: - int GetId() const - { - return id; - } - - void SetId(int id) - { - this->id = id; - } - - int GetIntegerValue() const - { - return integerValue; - } - - void SetIntegerValue(int integerValue) - { - this->integerValue = integerValue; - } - - int64_t GetLongValue() const - { - return longValue; - } - - void SetLongValue(int64_t longValue) - { - this->longValue = longValue; - } - - short GetShortValue() const - { - return shortValue; - } - - void SetShortValue(short shortValue) - { - this->shortValue = shortValue; - } - - bool GetBooleanValue() const - { - return booleanValue; - } - - void SetBooleanValue(bool booleanValue) - { - this->booleanValue = booleanValue; - } - - double GetDoubleValue() const - { - return doubleValue; - } - - void SetDoubleValue(double doubleValue) - { - this->doubleValue = doubleValue; - } - - float GetFloatValue() const - { - return floatValue; - } - - void SetFloatValue(float floatValue) - { - this->floatValue = floatValue; - } - - std::string GetStringValue() const - { - return stringValue; - } - - void SetStringValue(std::string stringValue) - { - this->stringValue = stringValue; - } - - std::vector GetBlobValue() const - { - return blobValue; - } - - void SetBlobValue(std::vector blobValue) - { - this->blobValue = blobValue; - } - - std::string GetClobValue() const - { - return clobValue; - } - - void SetClobValue(std::string clobValue) - { - this->clobValue = clobValue; - } - - int8_t GetByteValue() const - { - return byteValue; - } - - void SetByteValue(int8_t byteValue) - { - this->byteValue = byteValue; - } - - time_t GetTimeValue() const - { - return timeValue; - } - - void SetTimeValue(time_t timeValue) - { - this->timeValue = timeValue; - } - - char GetCharacterValue() const - { - return characterValue; - } - - void SetCharacterValue(char characterValue) - { - this->characterValue = characterValue; - } - - int GetPrimIntValue() const - { - return primIntValue; - } - - void SetPrimIntValue(int primIntValue) - { - this->primIntValue = primIntValue; - } - - int64_t GetPrimLongValue() const - { - return primLongValue; - } - - void SetPrimLongValue(int64_t primLongValue) - { - this->primLongValue = primLongValue; - } - - short GetPrimShortValue() const - { - return primShortValue; - } - - void SetPrimShortValue(short primShortValue) - { - this->primShortValue = primShortValue; - } - - float GetPrimFloatValue() const - { - return primFloatValue; - } - - void SetPrimFloatValue(float primFloatValue) - { - this->primFloatValue = primFloatValue; - } - - double GetPrimDoubleValue() const - { - return primDoubleValue; - } - - void SetPrimDoubleValue(double primDoubleValue) - { - this->primDoubleValue = primDoubleValue; - } - - bool IsPrimBooleanValue() const - { - return primBooleanValue; - } - - void SetPrimBooleanValue(bool primBooleanValue) - { - this->primBooleanValue = primBooleanValue; - } - - int8_t GetPrimByteValue() const - { - return primByteValue; - } - - void SetPrimByteValue(int8_t primByteValue) - { - this->primByteValue = primByteValue; - } - - char GetPrimCharValue() const - { - return primCharValue; - } - - void SetPrimCharValue(char primCharValue) - { - this->primCharValue = primCharValue; - } - - int GetOrder() const - { - return order; - } - - void SetOrder(int order) - { - this->order = order; - } - -private: - int id; - - int integerValue; - - int64_t longValue; - - short shortValue; - - bool booleanValue = false; - - double doubleValue; - - float floatValue; - - std::string stringValue; - - std::vector blobValue; - - std::string clobValue; - - int8_t byteValue; - - time_t timeValue; - - int primIntValue; - - char characterValue; - - int64_t primLongValue; - - short primShortValue; - - float primFloatValue; - - double primDoubleValue; - - bool primBooleanValue = false; - - int8_t primByteValue; - - char primCharValue; - - int order; -}; - -class RdbStorePredicateTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - - static const std::string DATABASE_NAME; - static std::shared_ptr store; - - time_t DateMakeTime(std::vector data); - void InsertDates(std::vector dataTypes); - AllDataType *BuildAllDataType1(); - AllDataType *BuildAllDataType2(); - AllDataType *BuildAllDataType3(); - void GenerateAllDataTypeTable(); - void CalendarTest(RdbPredicates predicates1); - void BasicDataTypeTest(RdbPredicates predicates1); - int ResultSize(std::unique_ptr &resultSet); - void BasicDataTypeTest002(RdbPredicates predicates1); - void CalendarTest002(RdbPredicates predicates1); -}; - -std::shared_ptr RdbStorePredicateTest::store = nullptr; -const std::string RdbStorePredicateTest::DATABASE_NAME = RDB_TEST_PATH + "predicates_test.db"; -const std::string CREATE_TABLE_ALL_DATA_TYPE_SQL = std::string("CREATE TABLE IF NOT EXISTS AllDataType ") + - std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, integerValue INTEGER , longValue INTEGER , ") + - std::string("shortValue INTEGER , booleanValue INTEGER , doubleValue REAL , floatValue REAL , ") + - std::string("stringValue TEXT , blobValue BLOB , clobValue TEXT , byteValue INTEGER , ") + - std::string("timeValue INTEGER , characterValue TEXT , primIntValue INTEGER ,") + - std::string("primLongValue INTEGER NOT NULL, primShortValue INTEGER NOT NULL, ") + - std::string("primFloatValue REAL NOT NULL, primDoubleValue REAL NOT NULL, ") + - std::string("primBooleanValue INTEGER NOT NULL, primByteValue INTEGER NOT NULL, ") + - std::string("primCharValue TEXT, `order` INTEGER);"); - -const std::string ALL_DATA_TYPE_INSERT_SQL = std::string("INSERT INTO AllDataType (id, integerValue, longValue, ") + - std::string("shortValue, booleanValue, doubleValue, floatValue, stringValue, blobValue, ") + - std::string("clobValue, byteValue, timeValue, characterValue, primIntValue, primLongValue, ") + - std::string("primShortValue, primFloatValue, primDoubleValue, ") + - std::string("primBooleanValue, primByteValue, primCharValue, `order`) ") + - std::string("VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"); - -class PredicateTestOpenCallback : public RdbOpenCallback { -public: - int OnCreate(RdbStore &rdbStore) override; - int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override; -}; - -int PredicateTestOpenCallback::OnCreate(RdbStore &store) -{ - return E_OK; -} - -int PredicateTestOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion) -{ - return E_OK; -} - -void RdbStorePredicateTest::SetUpTestCase() -{} - -void RdbStorePredicateTest::TearDownTestCase() -{ - RdbHelper::DeleteRdbStore(RdbStorePredicateTest::DATABASE_NAME); -} - -void RdbStorePredicateTest::SetUp() -{ - if (access(RdbStorePredicateTest::DATABASE_NAME.c_str(), F_OK) != 0) { - remove(RdbStorePredicateTest::DATABASE_NAME.c_str()); - } - - int errCode = E_OK; - RdbStoreConfig config(RdbStorePredicateTest::DATABASE_NAME); - PredicateTestOpenCallback helper; - RdbStorePredicateTest::store = RdbHelper::GetRdbStore(config, 1, helper, errCode); - EXPECT_NE(RdbStorePredicateTest::store, nullptr); - - RdbStorePredicateTest::GenerateAllDataTypeTable(); -} - -void RdbStorePredicateTest::TearDown(void) {} - -void RdbStorePredicateTest::GenerateAllDataTypeTable() -{ - RdbStorePredicateTest::store->ExecuteSql(CREATE_TABLE_ALL_DATA_TYPE_SQL); - - AllDataType *dataType1 = RdbStorePredicateTest::BuildAllDataType1(); - - AllDataType *dataType2 = RdbStorePredicateTest::BuildAllDataType2(); - - AllDataType *dataType3 = RdbStorePredicateTest::BuildAllDataType3(); - - std::vector dataTypes; - dataTypes.push_back(*dataType1); - dataTypes.push_back(*dataType2); - dataTypes.push_back(*dataType3); - RdbStorePredicateTest::InsertDates(dataTypes); - - delete dataType1; - dataType1 = nullptr; - delete dataType2; - dataType2 = nullptr; - delete dataType3; - dataType3 = nullptr; -} - -AllDataType *RdbStorePredicateTest::RdbStorePredicateTest::BuildAllDataType1() -{ - std::vector blob = {1, 2, 3}; - AllDataType *dataType = new AllDataType(); - dataType->SetId(1); - dataType->SetIntegerValue(INT_MAX); - dataType->SetDoubleValue(DBL_MAX); - dataType->SetBooleanValue(true); - dataType->SetFloatValue(FLT_MAX); - dataType->SetLongValue(LONG_MAX); - dataType->SetShortValue(SHRT_MAX); - dataType->SetCharacterValue(' '); - dataType->SetStringValue("ABCDEFGHIJKLMN"); - dataType->SetBlobValue(blob); - dataType->SetClobValue("ABCDEFGHIJKLMN"); - dataType->SetByteValue(INT8_MAX); - - std::vector date = {2019, 7, 10}; - time_t timeValue = RdbStorePredicateTest::DateMakeTime(date); - dataType->SetTimeValue(timeValue); - - dataType->SetPrimIntValue(INT_MAX); - dataType->SetPrimDoubleValue(DBL_MAX); - dataType->SetPrimFloatValue(FLT_MAX); - dataType->SetPrimBooleanValue(true); - dataType->SetPrimByteValue(INT8_MAX); - dataType->SetPrimCharValue(' '); - dataType->SetPrimLongValue(LONG_MAX); - dataType->SetPrimShortValue(SHRT_MAX); - return dataType; -} - -AllDataType *RdbStorePredicateTest::BuildAllDataType2() -{ - std::vector blob = {1, 2, 3}; - AllDataType *dataType2 = new AllDataType(); - dataType2->SetId(2); - dataType2->SetIntegerValue(1); - dataType2->SetDoubleValue(1.0); - dataType2->SetBooleanValue(false); - dataType2->SetFloatValue(1.0); - dataType2->SetLongValue(static_cast(1)); - dataType2->SetShortValue(static_cast(1)); - dataType2->SetCharacterValue(' '); - dataType2->SetStringValue("ABCDEFGHIJKLMN"); - dataType2->SetBlobValue(blob); - dataType2->SetClobValue("ABCDEFGHIJKLMN"); - dataType2->SetByteValue(INT8_MIN); - - std::vector date = {2019, 7, 17}; - time_t timeValue2 = RdbStorePredicateTest::DateMakeTime(date); - dataType2->SetTimeValue(timeValue2); - - dataType2->SetPrimIntValue(1); - dataType2->SetPrimDoubleValue(1.0); - dataType2->SetPrimFloatValue(1.0); - dataType2->SetPrimBooleanValue(false); - dataType2->SetPrimByteValue(static_cast(1)); - dataType2->SetPrimCharValue(' '); - dataType2->SetPrimLongValue(static_cast(1)); - dataType2->SetPrimShortValue(static_cast(1)); - return dataType2; -} - -AllDataType *RdbStorePredicateTest::BuildAllDataType3() -{ - std::vector blob = {1, 2, 3}; - AllDataType *dataType3 = new AllDataType(); - dataType3->SetId(3); - dataType3->SetIntegerValue(INT_MIN); - dataType3->SetDoubleValue(DBL_MIN); - dataType3->SetBooleanValue(false); - dataType3->SetFloatValue(FLT_MIN); - dataType3->SetLongValue(LONG_MIN); - dataType3->SetShortValue(SHRT_MIN); - dataType3->SetCharacterValue(' '); - dataType3->SetStringValue("ABCDEFGHIJKLMN"); - dataType3->SetBlobValue(blob); - dataType3->SetClobValue("ABCDEFGHIJKLMN"); - dataType3->SetByteValue(INT8_MIN); - - std::vector date = {2019, 6, 10}; - time_t timeValue3 = RdbStorePredicateTest::DateMakeTime(date); - dataType3->SetTimeValue(timeValue3); - - dataType3->SetPrimIntValue(INT_MIN); - dataType3->SetPrimDoubleValue(DBL_MIN); - dataType3->SetPrimFloatValue(FLT_MIN); - dataType3->SetPrimBooleanValue(false); - dataType3->SetPrimByteValue(INT8_MIN); - dataType3->SetPrimCharValue(' '); - dataType3->SetPrimLongValue(LONG_MIN); - dataType3->SetPrimShortValue(SHRT_MIN); - return dataType3; -} - -void RdbStorePredicateTest::InsertDates(std::vector dataTypes) -{ - for (size_t i = 0; i < dataTypes.size(); i++) { - char characterValue = dataTypes[i].GetCharacterValue(); - char primCharValue = dataTypes[i].GetPrimCharValue(); - std::stringstream strByte; - std::vector objects; - objects.push_back(ValueObject(dataTypes[i].GetId())); - objects.push_back(ValueObject(dataTypes[i].GetIntegerValue())); - objects.push_back(ValueObject(dataTypes[i].GetLongValue())); - objects.push_back(ValueObject(dataTypes[i].GetShortValue())); - objects.push_back(ValueObject(dataTypes[i].GetBooleanValue())); - - strByte << dataTypes[i].GetDoubleValue(); - objects.push_back(ValueObject(strByte.str())); - - strByte.str(""); - strByte << dataTypes[i].GetFloatValue(); - objects.push_back(ValueObject(strByte.str())); - objects.push_back(ValueObject(dataTypes[i].GetStringValue())); - objects.push_back(ValueObject(dataTypes[i].GetBlobValue())); - objects.push_back(ValueObject(dataTypes[i].GetClobValue())); - objects.push_back(ValueObject(dataTypes[i].GetByteValue())); - objects.push_back(ValueObject(static_cast(dataTypes[i].GetTimeValue()))); - - strByte.str(""); - strByte << characterValue; - string str1 = strByte.str(); - objects.push_back(ValueObject(str1)); - objects.push_back(ValueObject(dataTypes[i].GetPrimIntValue())); - objects.push_back(ValueObject(dataTypes[i].GetPrimLongValue())); - objects.push_back(ValueObject(dataTypes[i].GetPrimShortValue())); - - strByte.str(""); - strByte << dataTypes[i].GetPrimFloatValue(); - objects.push_back(ValueObject(strByte.str())); - - strByte.str(""); - strByte << dataTypes[i].GetPrimDoubleValue(); - objects.push_back(ValueObject(strByte.str())); - objects.push_back(ValueObject(dataTypes[i].IsPrimBooleanValue() ? (char) 1 : (char) 0)); - objects.push_back(ValueObject(dataTypes[i].GetPrimByteValue())); - - strByte.str(""); - strByte << primCharValue; - string str2 = strByte.str(); - objects.push_back(ValueObject(str2)); - RdbStorePredicateTest::store->ExecuteSql(ALL_DATA_TYPE_INSERT_SQL, objects); - } -} - -time_t RdbStorePredicateTest::DateMakeTime(std::vector data) -{ - struct tm t1 = {0}; - t1.tm_year = data[0] - 1990; - t1.tm_mon = data[1] - 1; - t1.tm_hour = data[2]; - t1.tm_sec = 0; - t1.tm_min = 0; - t1.tm_mday = 0; - time_t time = mktime(&t1); - return time; -} - -/* * - * @tc.name: RdbStore_EqualTo_001 - * @tc.desc: Normal testCase of RdbPredicates for EqualTo - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_EqualTo_001, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - - BasicDataTypeTest(predicates1); - - CalendarTest(predicates1); -} - -void RdbStorePredicateTest::CalendarTest(RdbPredicates predicates1) -{ - std::vector sqlArgs; - std::vector columns; - std::string sql; - - predicates1.Clear(); - std::vector date = {2019, 7, 17}; - time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); - - predicates1.EqualTo("timeValue", std::to_string(calendarTime)); - std::unique_ptr allDataTypes9 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(E_OK, allDataTypes9->GoToFirstRow()); - int valueInt = 0; - allDataTypes9->GetInt(0, valueInt); - EXPECT_EQ(2, valueInt); -} -void RdbStorePredicateTest::BasicDataTypeTest(RdbPredicates predicates1) -{ - std::vector columns; - std::stringstream tempValue; - predicates1.EqualTo("booleanValue", "1"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes1)); - - predicates1.Clear(); - predicates1.EqualTo("byteValue", std::to_string(INT8_MIN))->Or()->EqualTo("byteValue", std::to_string(1)); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes3)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MIN; - predicates1.EqualTo("doubleValue", tempValue.str()); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes4)); - - predicates1.Clear(); - predicates1.EqualTo("shortValue", std::to_string(SHRT_MIN)); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes5)); - - predicates1.Clear(); - predicates1.EqualTo("integerValue", std::to_string(1)); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(E_OK, allDataTypes6->GoToFirstRow()); - int valueInt = 0; - allDataTypes6->GetInt(0, valueInt); - EXPECT_EQ(2, valueInt); - - predicates1.Clear(); - predicates1.EqualTo("longValue", std::to_string(1)); - std::unique_ptr allDataTypes7 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(E_OK, allDataTypes7->GoToFirstRow()); - allDataTypes7->GetInt(0, valueInt); - EXPECT_EQ(2, valueInt); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.EqualTo("floatValue", tempValue.str()); - std::unique_ptr allDataTypes8 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(E_OK, allDataTypes8->GoToFirstRow()); - allDataTypes8->GetInt(0, valueInt); - EXPECT_EQ(3, valueInt); -} - -int RdbStorePredicateTest::ResultSize(std::unique_ptr &resultSet) -{ - if (resultSet->GoToFirstRow() != E_OK) { - return 0; - } - int count = 1; - while (resultSet->GoToNextRow() == E_OK) { - count++; - } - return count; -} - -/* * - * @tc.name: RdbStore_NotEqualTo_002 - * @tc.desc: Normal testCase of RdbPredicates for NotEqualTo - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_NotEqualTo_002, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - - BasicDataTypeTest002(predicates1); - - CalendarTest002(predicates1); -} - -void RdbStorePredicateTest::CalendarTest002(RdbPredicates predicates1) -{ - std::vector sqlArgs; - std::vector columns; - std::string sql; - - predicates1.Clear(); - std::vector date = {2019, 7, 17}; - time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); - - predicates1.NotEqualTo("timeValue", std::to_string(calendarTime)); - std::unique_ptr allDataTypes9 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes9)); -} -void RdbStorePredicateTest::BasicDataTypeTest002(RdbPredicates predicates1) -{ - std::vector columns; - std::stringstream tempValue; - - predicates1.NotEqualTo("primBooleanValue", "1"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes1)); - - predicates1.Clear(); - predicates1.NotEqualTo("primByteValue", std::to_string(INT8_MIN))->NotEqualTo("primByteValue", std::to_string(1)); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.NotEqualTo("stringValue", "ABCDEFGHIJKLMN"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes3)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MIN; - predicates1.NotEqualTo("doubleValue", tempValue.str()); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes4)); - - predicates1.Clear(); - predicates1.NotEqualTo("shortValue", std::to_string(SHRT_MIN)); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes5)); - - predicates1.Clear(); - predicates1.NotEqualTo("integerValue", "1"); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes6)); - - predicates1.Clear(); - predicates1.NotEqualTo("longValue", "1"); - std::unique_ptr allDataTypes7 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes7)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.NotEqualTo("floatValue", tempValue.str()); - std::unique_ptr allDataTypes8 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes8)); -} - -/* * - * @tc.name: RdbStore_IsNull_003 - * @tc.desc: Normal testCase of RdbPredicates for IsNull - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_IsNull_003, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - predicates1.IsNull("primLongValue"); - std::vector columns; - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_NotNull_004 - * @tc.desc: Normal testCase of RdbPredicates for NotNull - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_NotNull_003, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - predicates1.IsNotNull("primLongValue"); - std::vector columns; - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_GreaterThan_005 - * @tc.desc: Normal testCase of RdbPredicates for GreaterThan - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_GreaterThan_005, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - std::stringstream tempValue; - - predicates1.GreaterThan("stringValue", "ABC"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MIN; - predicates1.GreaterThan("doubleValue", tempValue.str()); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.GreaterThan("integerValue", "1"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes3)); - - predicates1.Clear(); - predicates1.GreaterThan("longValue", "1"); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes4)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.GreaterThan("floatValue", tempValue.str()); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes5)); - - predicates1.Clear(); - std::vector date = {2019, 6, 9}; - time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); - predicates1.GreaterThan("timeValue", std::to_string(calendarTime).c_str()); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes6)); -} - -/* * - * @tc.name: RdbStore_GreaterThanOrEqualTo_006 - * @tc.desc: Normal testCase of RdbPredicates for GreaterThanOrEqualTo - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_GreaterThanOrEqualTo_006, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - std::stringstream tempValue; - - predicates1.GreaterThanOrEqualTo("stringValue", "ABC"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MIN; - predicates1.GreaterThanOrEqualTo("doubleValue", tempValue.str()); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.GreaterThanOrEqualTo("integerValue", "1"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes3)); - - predicates1.Clear(); - predicates1.GreaterThanOrEqualTo("longValue", "1"); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes4)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.GreaterThanOrEqualTo("floatValue", tempValue.str()); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes5)); - - predicates1.Clear(); - std::vector date = {2019, 6, 9}; - time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); - predicates1.GreaterThanOrEqualTo("timeValue", std::to_string(calendarTime).c_str()); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes6)); -} - -/* * - * @tc.name: RdbStore_lessThan_007 - * @tc.desc: Normal testCase of RdbPredicates for LessThan - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_lessThan_007, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - std::stringstream tempValue; - - predicates1.LessThan("stringValue", "ABD"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MIN; - predicates1.LessThan("doubleValue", tempValue.str()); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.LessThan("integerValue", "1"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes3)); - - predicates1.Clear(); - predicates1.LessThan("longValue", "1"); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes4)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.LessThan("floatValue", tempValue.str()); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes5)); - - predicates1.Clear(); - std::vector date = {2019, 6, 9}; - time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); - predicates1.LessThan("timeValue", std::to_string(calendarTime).c_str()); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes6)); -} - -/* * - * @tc.name: RdbStore_LessThanOrEqualTo_008 - * @tc.desc: Normal testCase of RdbPredicates for LessThanOrEqualTo - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_LessThanOrEqualTo_008, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - std::stringstream tempValue; - - predicates1.LessThanOrEqualTo("stringValue", "ABD"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MIN; - predicates1.LessThanOrEqualTo("doubleValue", tempValue.str()); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.LessThanOrEqualTo("integerValue", "1"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes3)); - - predicates1.Clear(); - predicates1.LessThanOrEqualTo("longValue", "1"); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes4)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.LessThanOrEqualTo("floatValue", tempValue.str()); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes5)); - - predicates1.Clear(); - std::vector date = {2019, 6, 9}; - time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); - predicates1.LessThanOrEqualTo("timeValue", std::to_string(calendarTime).c_str()); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes6)); -} - -/* * - * @tc.name: RdbStore_Between_009 - * @tc.desc: Normal testCase of RdbPredicates for Between - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_Between_009, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - std::stringstream tempValue; - - predicates1.Between("stringValue", "ABB", "ABD"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MAX; - predicates1.Between("doubleValue", "0.0", tempValue.str()); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.Between("integerValue", "0", "1"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes3)); - - predicates1.Clear(); - predicates1.Between("longValue", "0", "2"); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes4)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MAX; - std::string floatMax = tempValue.str(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.Between("floatValue", tempValue.str(), floatMax); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes5)); - - predicates1.Clear(); - std::vector lowCalendar = {2019, 6, 9}; - time_t lowCalendarTime = RdbStorePredicateTest::DateMakeTime(lowCalendar); - std::vector highCalendar = {2019, 7, 17}; - time_t highCalendarTime = RdbStorePredicateTest::DateMakeTime(highCalendar); - predicates1.Between("timeValue", std::to_string(lowCalendarTime).c_str(), std::to_string(highCalendarTime).c_str()); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes6)); -} - -/* * - * @tc.name: RdbStore_Contain_010 - * @tc.desc: Normal testCase of RdbPredicates for Contain - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_Contain_010, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.Contains("stringValue", "DEF"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_BeginsWith_011 - * @tc.desc: Normal testCase of RdbPredicates for BeginsWith - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_BeginsWith_011, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.BeginsWith("stringValue", "ABC"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_EndsWith_012 - * @tc.desc: Normal testCase of RdbPredicates for EndsWith - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_EndsWith_012, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.EndsWith("stringValue", "LMN"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_Like_013 - * @tc.desc: Normal testCase of RdbPredicates for Like - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_Like_013, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.Like("stringValue", "%LMN%"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_BeginEndWrap_014 - * @tc.desc: Normal testCase of RdbPredicates for BeginEndWrap - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_BeginEndWrap_014, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") - ->BeginWrap() - ->EqualTo("integerValue", "1") - ->Or() - ->EqualTo("integerValue", std::to_string(INT_MAX)) - ->EndWrap(); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes1)); - - predicates1.Clear(); - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->And()->EqualTo("integerValue", "1"); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes2)); -} - -/* * - * @tc.name: RdbStore_AndOR_015 - * @tc.desc: Normal testCase of RdbPredicates for AndOR - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_AndOR_015, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") - ->BeginWrap() - ->EqualTo("integerValue", "1") - ->Or() - ->EqualTo("integerValue", std::to_string(INT_MAX)) - ->EndWrap(); - - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes1)); - - predicates1.Clear(); - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->And()->EqualTo("integerValue", "1"); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes2)); -} - -/* * - * @tc.name: RdbStore_Order_016 - * @tc.desc: Normal testCase of RdbPredicates for Order - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_Order_016, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->OrderByAsc("integerValue")->Distinct(); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(E_OK, allDataTypes1->GoToFirstRow()); - int valueInt = 0; - allDataTypes1->GetInt(0, valueInt); - EXPECT_EQ(3, valueInt); - EXPECT_EQ(E_OK, allDataTypes1->GoToNextRow()); - allDataTypes1->GetInt(0, valueInt); - EXPECT_EQ(2, valueInt); - EXPECT_EQ(E_OK, allDataTypes1->GoToNextRow()); - allDataTypes1->GetInt(0, valueInt); - EXPECT_EQ(1, valueInt); - - predicates1.Clear(); - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->OrderByDesc("integerValue")->Distinct(); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(E_OK, allDataTypes2->GoToFirstRow()); - allDataTypes2->GetInt(0, valueInt); - EXPECT_EQ(1, valueInt); - EXPECT_EQ(E_OK, allDataTypes2->GoToNextRow()); - allDataTypes2->GetInt(0, valueInt); - EXPECT_EQ(2, valueInt); - EXPECT_EQ(E_OK, allDataTypes2->GoToNextRow()); - allDataTypes2->GetInt(0, valueInt); - EXPECT_EQ(3, valueInt); -} - -/* * - * @tc.name: RdbStore_Limit_017 - * @tc.desc: Normal testCase of RdbPredicates for Limit - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_Limit_017, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->Limit(1); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_JoinTypes_018 - * @tc.desc: Normal testCase of RdbPredicates for JoinTypes - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_JoinTypes_018, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector joinEntityNames; - - joinEntityNames.push_back("AllDataType"); - predicates1.SetJoinTableNames(joinEntityNames); - - std::vector joinTypes; - joinTypes.push_back("INNER JOIN"); - predicates1.SetJoinTypes(joinTypes); - - std::vector joinConditions; - joinConditions.push_back("ON"); - predicates1.SetJoinConditions(joinConditions); - predicates1.SetJoinCount(1); - - EXPECT_EQ(joinConditions, predicates1.GetJoinConditions()); - EXPECT_EQ(joinEntityNames, predicates1.GetJoinTableNames()); - EXPECT_EQ(joinTypes, predicates1.GetJoinTypes()); - EXPECT_EQ(1, predicates1.GetJoinCount()); -} - -/* * - * @tc.name: RdbStore_Glob_019 - * @tc.desc: Normal testCase of RdbPredicates for Glob - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_Glob_019, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.Glob("stringValue", "ABC*"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes1)); - - predicates1.Clear(); - predicates1.Glob("stringValue", "*EFG*"); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.Glob("stringValue", "?B*"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes3)); - - predicates1.Clear(); - predicates1.Glob("stringValue", "A????????????N"); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes4)); - - predicates1.Clear(); - predicates1.Glob("stringValue", "A?????????????N"); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes5)); - - predicates1.Clear(); - predicates1.Glob("stringValue", "?B*N"); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(3, ResultSize(allDataTypes6)); -} - -/* * - * @tc.name: RdbStore_NotBetween_020 - * @tc.desc: Normal testCase of RdbPredicates for NotBetween - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_NotBetween_020, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - std::stringstream tempValue; - - predicates1.NotBetween("stringValue", "ABB", "ABD"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes1)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << DBL_MAX; - predicates1.NotBetween("doubleValue", "0.0", tempValue.str()); - std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes2)); - - predicates1.Clear(); - predicates1.NotBetween("integerValue", "0", "1"); - std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes3)); - - predicates1.Clear(); - predicates1.NotBetween("longValue", "0", "2"); - std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes4)); - - predicates1.Clear(); - tempValue.str(""); - tempValue << FLT_MAX; - std::string floatMax = tempValue.str(); - tempValue.str(""); - tempValue << FLT_MIN; - predicates1.NotBetween("floatValue", tempValue.str(), floatMax); - std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes5)); - - std::vector lowCalendar = {2019, 6, 9}; - time_t lowCalendarTime = RdbStorePredicateTest::DateMakeTime(lowCalendar); - std::vector highCalendar = {2019, 7, 17}; - time_t highCalendarTime = RdbStorePredicateTest::DateMakeTime(highCalendar); - predicates1.Clear(); - predicates1.NotBetween("timeValue", std::to_string(lowCalendarTime), std::to_string(highCalendarTime)); - std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(0, ResultSize(allDataTypes6)); -} - -/* * - * @tc.name: RdbStore_ComplexPredicate_021 - * @tc.desc: Normal testCase of RdbPredicates for complex combine sql - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_ComplexPredicate_021, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.Glob("stringValue", "ABC*")->EqualTo("booleanValue", "1") - ->NotBetween("longValue", "0", "2"); - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(1, ResultSize(allDataTypes1)); -} - -/* * - * @tc.name: RdbStore_ClearMethod_022 - * @tc.desc: Normal testCase of RdbPredicates for Clear Method - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_ClearMethod_022, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - std::vector columns; - - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") - ->BeginWrap() - ->EqualTo("integerValue", "1") - ->Or() - ->EqualTo("integerValue", std::to_string(INT_MAX)) - ->EndWrap() - ->OrderByDesc("integerValue") - ->Limit(2); - - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - EXPECT_EQ(2, ResultSize(allDataTypes1)); - - EXPECT_EQ("AllDataType", predicates1.GetTableName()); - EXPECT_EQ(2, predicates1.GetLimit()); - EXPECT_EQ(true, predicates1.GetWhereClause().find("stringValue") != std::string::npos); - - std::vector agrs = predicates1.GetWhereArgs(); - auto ret = find(agrs.begin(), agrs.end(), "ABCDEFGHIJKLMN"); - EXPECT_EQ(true, ret != agrs.end()); - - std::vector lists = {"ohos", "bazhahei", "zhaxidelie"}; - predicates1.SetJoinTableNames(lists); - predicates1.SetJoinCount(1); - predicates1.SetJoinConditions(lists); - predicates1.SetJoinTypes(lists); - predicates1.SetOrder("ohos"); - predicates1.Distinct(); - - agrs = predicates1.GetJoinTableNames(); - ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); - EXPECT_EQ(true, ret != agrs.end()); - EXPECT_EQ(1, predicates1.GetJoinCount()); - - agrs = predicates1.GetJoinConditions(); - ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); - EXPECT_EQ(true, ret != agrs.end()); - - agrs = predicates1.GetJoinTypes(); - ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); - EXPECT_EQ(true, ret != agrs.end()); - EXPECT_EQ(true, predicates1.GetJoinClause().find("ohos") != std::string::npos); - EXPECT_EQ("ohos", predicates1.GetOrder()); - EXPECT_EQ(true, predicates1.IsDistinct()); - - predicates1.Clear(); - EXPECT_EQ("AllDataType", predicates1.GetTableName()); - EXPECT_EQ(-1, predicates1.GetLimit()); - EXPECT_EQ(true, predicates1.GetWhereClause().empty()); - EXPECT_EQ(true, predicates1.GetWhereArgs().empty()); - - EXPECT_EQ(true, predicates1.GetJoinTableNames().empty()); - EXPECT_EQ(0, predicates1.GetJoinCount()); - EXPECT_EQ(true, predicates1.GetJoinConditions().empty()); - EXPECT_EQ(true, predicates1.GetJoinTypes().empty()); - EXPECT_EQ("AllDataType", predicates1.GetJoinClause()); - EXPECT_EQ(true, predicates1.GetOrder().empty()); - EXPECT_EQ(false, predicates1.IsDistinct()); -} - -/* * - * @tc.name: RdbStore_InMethod_023 - * @tc.desc: Normal testCase of RdbPredicates for in method - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_InMethod_023, TestSize.Level1) -{ - RdbPredicates rdbPredicates1("AllDataType"); - std::vector columns; - std::vector agrs = {std::to_string(INT_MAX)}; - rdbPredicates1.In("integerValue", agrs); - std::unique_ptr resultSet1 = RdbStorePredicateTest::store->Query(rdbPredicates1, columns); - int count = 0; - resultSet1->GetRowCount(count); - EXPECT_EQ(1, count); - - RdbPredicates rdbPredicates2("AllDataType"); - agrs[0] = "1"; - rdbPredicates2.In("longValue", agrs); - std::unique_ptr resultSet2 = RdbStorePredicateTest::store->Query(rdbPredicates2, columns); - resultSet2->GetRowCount(count); - EXPECT_EQ(1, count); - - RdbPredicates rdbPredicates3("AllDataType"); - agrs[0] = "1.0"; - rdbPredicates3.In("doubleValue", agrs); - std::unique_ptr resultSet3 = RdbStorePredicateTest::store->Query(rdbPredicates3, columns); - resultSet3->GetRowCount(count); - EXPECT_EQ(1, count); - - RdbPredicates rdbPredicates4("AllDataType"); - rdbPredicates4.In("floatValue", agrs); - std::unique_ptr resultSet4 = RdbStorePredicateTest::store->Query(rdbPredicates4, columns); - resultSet4->GetRowCount(count); - EXPECT_EQ(1, count); - - std::vector date = {2019, 6, 10}; - time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); - RdbPredicates rdbPredicates5("AllDataType"); - agrs[0] = std::to_string(calendarTime); - rdbPredicates5.In("timeValue", agrs); - std::unique_ptr resultSet5 = RdbStorePredicateTest::store->Query(rdbPredicates5, columns); - resultSet5->GetRowCount(count); - EXPECT_EQ(1, count); -} - -/* * - * @tc.name: RdbStore_NotInMethod_023 - * @tc.desc: Normal testCase of RdbPredicates for notIn method - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_NotInMethod_023, TestSize.Level1) -{ - std::vector columns; - std::vector agrs = {std::to_string(INT_MAX), std::to_string(INT_MIN)}; - std::stringstream tempValue; - - RdbPredicates rdbPredicates1("AllDataType"); - rdbPredicates1.NotIn("integerValue", agrs); - std::unique_ptr resultSet1 = RdbStorePredicateTest::store->Query(rdbPredicates1, columns); - int count = 0; - resultSet1->GetRowCount(count); - EXPECT_EQ(1, count); - - RdbPredicates rdbPredicates2("AllDataType"); - agrs[0] = "1"; - agrs[1] = std::to_string(LONG_MAX); - rdbPredicates2.NotIn("longValue", agrs); - std::unique_ptr resultSet2 = RdbStorePredicateTest::store->Query(rdbPredicates2, columns); - resultSet2->GetRowCount(count); - EXPECT_EQ(1, count); - - RdbPredicates rdbPredicates3("AllDataType"); - tempValue.str(""); - tempValue << DBL_MIN; - agrs[0] = "1.0"; - agrs[1] = tempValue.str(); - rdbPredicates3.NotIn("doubleValue", agrs); - std::unique_ptr resultSet3 = RdbStorePredicateTest::store->Query(rdbPredicates3, columns); - resultSet3->GetRowCount(count); - EXPECT_EQ(1, count); - - RdbPredicates rdbPredicates4("AllDataType"); - tempValue.str(""); - tempValue << FLT_MAX; - agrs[0] = "1.0"; - agrs[1] = tempValue.str(); - rdbPredicates4.NotIn("floatValue", agrs); - std::unique_ptr resultSet4 = RdbStorePredicateTest::store->Query(rdbPredicates4, columns); - resultSet4->GetRowCount(count); - EXPECT_EQ(1, count); -} - -/* * - * @tc.name: RdbStore_KeywordMethod_024 - * @tc.desc: Normal testCase of RdbPredicates for clear method - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbStorePredicateTest, RdbStore_KeywordMethod_024, TestSize.Level1) -{ - RdbPredicates predicates1("AllDataType"); - predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") - ->BeginWrap() - ->EqualTo("integerValue", "1") - ->Or() - ->EqualTo("integerValue", std::to_string(INT_MAX)) - ->EndWrap()->OrderByDesc("integerValue")->Limit(2); - std::vector columns = {"booleanValue", "doubleValue", "order"}; - std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); - allDataTypes1->GoToFirstRow(); - EXPECT_EQ(2, ResultSize(allDataTypes1)); - - EXPECT_EQ("AllDataType", predicates1.GetTableName()); - EXPECT_EQ(2, predicates1.GetLimit()); - - EXPECT_EQ(true, predicates1.GetWhereClause().find("stringValue") != std::string::npos); - std::vector agrs = predicates1.GetWhereArgs(); - auto ret = find(agrs.begin(), agrs.end(), "ABCDEFGHIJKLMN"); - EXPECT_EQ(true, ret != agrs.end()); - - std::vector lists = {"ohos", "bazhahei", "zhaxidelie"}; - predicates1.SetJoinTableNames(lists); - predicates1.SetJoinCount(1); - predicates1.SetJoinConditions(lists); - predicates1.SetJoinTypes(lists); - predicates1.SetOrder("ohos"); - predicates1.Distinct(); - - agrs = predicates1.GetJoinTableNames(); - ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); - EXPECT_EQ(true, ret != agrs.end()); - EXPECT_EQ(1, predicates1.GetJoinCount()); - - agrs = predicates1.GetJoinConditions(); - ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); - EXPECT_EQ(true, ret != agrs.end()); - - agrs = predicates1.GetJoinTypes(); - ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); - EXPECT_EQ(true, ret != agrs.end()); - EXPECT_EQ(true, predicates1.GetJoinClause().find("ohos") != std::string::npos); - EXPECT_EQ("ohos", predicates1.GetOrder()); - EXPECT_EQ(true, predicates1.IsDistinct()); - - predicates1.Clear(); - EXPECT_EQ("AllDataType", predicates1.GetTableName()); - EXPECT_EQ(-1, predicates1.GetLimit()); - EXPECT_EQ(true, predicates1.GetWhereClause().empty()); - EXPECT_EQ(true, predicates1.GetWhereArgs().empty()); - - EXPECT_EQ(true, predicates1.GetJoinTableNames().empty()); - EXPECT_EQ(0, predicates1.GetJoinCount()); - EXPECT_EQ(true, predicates1.GetJoinConditions().empty()); - EXPECT_EQ(true, predicates1.GetJoinTypes().empty()); - EXPECT_EQ("AllDataType", predicates1.GetJoinClause()); - EXPECT_EQ(true, predicates1.GetOrder().empty()); - EXPECT_EQ(false, predicates1.IsDistinct()); -} +/* + * 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 +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "rdb_errno.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" +#include "rdb_predicates.h" + +using namespace testing::ext; +using namespace OHOS::NativeRdb; + +class AllDataType { +public: + int GetId() const + { + return id; + } + + void SetId(int id) + { + this->id = id; + } + + int GetIntegerValue() const + { + return integerValue; + } + + void SetIntegerValue(int integerValue) + { + this->integerValue = integerValue; + } + + int64_t GetLongValue() const + { + return longValue; + } + + void SetLongValue(int64_t longValue) + { + this->longValue = longValue; + } + + short GetShortValue() const + { + return shortValue; + } + + void SetShortValue(short shortValue) + { + this->shortValue = shortValue; + } + + bool GetBooleanValue() const + { + return booleanValue; + } + + void SetBooleanValue(bool booleanValue) + { + this->booleanValue = booleanValue; + } + + double GetDoubleValue() const + { + return doubleValue; + } + + void SetDoubleValue(double doubleValue) + { + this->doubleValue = doubleValue; + } + + float GetFloatValue() const + { + return floatValue; + } + + void SetFloatValue(float floatValue) + { + this->floatValue = floatValue; + } + + std::string GetStringValue() const + { + return stringValue; + } + + void SetStringValue(std::string stringValue) + { + this->stringValue = stringValue; + } + + std::vector GetBlobValue() const + { + return blobValue; + } + + void SetBlobValue(std::vector blobValue) + { + this->blobValue = blobValue; + } + + std::string GetClobValue() const + { + return clobValue; + } + + void SetClobValue(std::string clobValue) + { + this->clobValue = clobValue; + } + + int8_t GetByteValue() const + { + return byteValue; + } + + void SetByteValue(int8_t byteValue) + { + this->byteValue = byteValue; + } + + time_t GetTimeValue() const + { + return timeValue; + } + + void SetTimeValue(time_t timeValue) + { + this->timeValue = timeValue; + } + + char GetCharacterValue() const + { + return characterValue; + } + + void SetCharacterValue(char characterValue) + { + this->characterValue = characterValue; + } + + int GetPrimIntValue() const + { + return primIntValue; + } + + void SetPrimIntValue(int primIntValue) + { + this->primIntValue = primIntValue; + } + + int64_t GetPrimLongValue() const + { + return primLongValue; + } + + void SetPrimLongValue(int64_t primLongValue) + { + this->primLongValue = primLongValue; + } + + short GetPrimShortValue() const + { + return primShortValue; + } + + void SetPrimShortValue(short primShortValue) + { + this->primShortValue = primShortValue; + } + + float GetPrimFloatValue() const + { + return primFloatValue; + } + + void SetPrimFloatValue(float primFloatValue) + { + this->primFloatValue = primFloatValue; + } + + double GetPrimDoubleValue() const + { + return primDoubleValue; + } + + void SetPrimDoubleValue(double primDoubleValue) + { + this->primDoubleValue = primDoubleValue; + } + + bool IsPrimBooleanValue() const + { + return primBooleanValue; + } + + void SetPrimBooleanValue(bool primBooleanValue) + { + this->primBooleanValue = primBooleanValue; + } + + int8_t GetPrimByteValue() const + { + return primByteValue; + } + + void SetPrimByteValue(int8_t primByteValue) + { + this->primByteValue = primByteValue; + } + + char GetPrimCharValue() const + { + return primCharValue; + } + + void SetPrimCharValue(char primCharValue) + { + this->primCharValue = primCharValue; + } + + int GetOrder() const + { + return order; + } + + void SetOrder(int order) + { + this->order = order; + } + +private: + int id; + + int integerValue; + + int64_t longValue; + + short shortValue; + + bool booleanValue = false; + + double doubleValue; + + float floatValue; + + std::string stringValue; + + std::vector blobValue; + + std::string clobValue; + + int8_t byteValue; + + time_t timeValue; + + int primIntValue; + + char characterValue; + + int64_t primLongValue; + + short primShortValue; + + float primFloatValue; + + double primDoubleValue; + + bool primBooleanValue = false; + + int8_t primByteValue; + + char primCharValue; + + int order; +}; + +class RdbStorePredicateTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static const std::string DATABASE_NAME; + static std::shared_ptr store; + + time_t DateMakeTime(std::vector data); + void InsertDates(std::vector dataTypes); + AllDataType *BuildAllDataType1(); + AllDataType *BuildAllDataType2(); + AllDataType *BuildAllDataType3(); + void GenerateAllDataTypeTable(); + void CalendarTest(RdbPredicates predicates1); + void BasicDataTypeTest(RdbPredicates predicates1); + int ResultSize(std::unique_ptr &resultSet); + void BasicDataTypeTest002(RdbPredicates predicates1); + void CalendarTest002(RdbPredicates predicates1); +}; + +std::shared_ptr RdbStorePredicateTest::store = nullptr; +const std::string RdbStorePredicateTest::DATABASE_NAME = RDB_TEST_PATH + "predicates_test.db"; +const std::string CREATE_TABLE_ALL_DATA_TYPE_SQL = std::string("CREATE TABLE IF NOT EXISTS AllDataType ") + + std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, integerValue INTEGER , longValue INTEGER , ") + + std::string("shortValue INTEGER , booleanValue INTEGER , doubleValue REAL , floatValue REAL , ") + + std::string("stringValue TEXT , blobValue BLOB , clobValue TEXT , byteValue INTEGER , ") + + std::string("timeValue INTEGER , characterValue TEXT , primIntValue INTEGER ,") + + std::string("primLongValue INTEGER NOT NULL, primShortValue INTEGER NOT NULL, ") + + std::string("primFloatValue REAL NOT NULL, primDoubleValue REAL NOT NULL, ") + + std::string("primBooleanValue INTEGER NOT NULL, primByteValue INTEGER NOT NULL, ") + + std::string("primCharValue TEXT, `order` INTEGER);"); + +const std::string ALL_DATA_TYPE_INSERT_SQL = std::string("INSERT INTO AllDataType (id, integerValue, longValue, ") + + std::string("shortValue, booleanValue, doubleValue, floatValue, stringValue, blobValue, ") + + std::string("clobValue, byteValue, timeValue, characterValue, primIntValue, primLongValue, ") + + std::string("primShortValue, primFloatValue, primDoubleValue, ") + + std::string("primBooleanValue, primByteValue, primCharValue, `order`) ") + + std::string("VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"); + +class PredicateTestOpenCallback : public RdbOpenCallback { +public: + int OnCreate(RdbStore &rdbStore) override; + int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override; +}; + +int PredicateTestOpenCallback::OnCreate(RdbStore &store) +{ + return E_OK; +} + +int PredicateTestOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion) +{ + return E_OK; +} + +void RdbStorePredicateTest::SetUpTestCase() +{} + +void RdbStorePredicateTest::TearDownTestCase() +{ + RdbHelper::DeleteRdbStore(RdbStorePredicateTest::DATABASE_NAME); +} + +void RdbStorePredicateTest::SetUp() +{ + if (access(RdbStorePredicateTest::DATABASE_NAME.c_str(), F_OK) != 0) { + remove(RdbStorePredicateTest::DATABASE_NAME.c_str()); + } + + int errCode = E_OK; + RdbStoreConfig config(RdbStorePredicateTest::DATABASE_NAME); + PredicateTestOpenCallback helper; + RdbStorePredicateTest::store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(RdbStorePredicateTest::store, nullptr); + + RdbStorePredicateTest::GenerateAllDataTypeTable(); +} + +void RdbStorePredicateTest::TearDown(void) {} + +void RdbStorePredicateTest::GenerateAllDataTypeTable() +{ + RdbStorePredicateTest::store->ExecuteSql(CREATE_TABLE_ALL_DATA_TYPE_SQL); + + AllDataType *dataType1 = RdbStorePredicateTest::BuildAllDataType1(); + + AllDataType *dataType2 = RdbStorePredicateTest::BuildAllDataType2(); + + AllDataType *dataType3 = RdbStorePredicateTest::BuildAllDataType3(); + + std::vector dataTypes; + dataTypes.push_back(*dataType1); + dataTypes.push_back(*dataType2); + dataTypes.push_back(*dataType3); + RdbStorePredicateTest::InsertDates(dataTypes); + + delete dataType1; + dataType1 = nullptr; + delete dataType2; + dataType2 = nullptr; + delete dataType3; + dataType3 = nullptr; +} + +AllDataType *RdbStorePredicateTest::RdbStorePredicateTest::BuildAllDataType1() +{ + std::vector blob = {1, 2, 3}; + AllDataType *dataType = new AllDataType(); + dataType->SetId(1); + dataType->SetIntegerValue(INT_MAX); + dataType->SetDoubleValue(DBL_MAX); + dataType->SetBooleanValue(true); + dataType->SetFloatValue(FLT_MAX); + dataType->SetLongValue(LONG_MAX); + dataType->SetShortValue(SHRT_MAX); + dataType->SetCharacterValue(' '); + dataType->SetStringValue("ABCDEFGHIJKLMN"); + dataType->SetBlobValue(blob); + dataType->SetClobValue("ABCDEFGHIJKLMN"); + dataType->SetByteValue(INT8_MAX); + + std::vector date = {2019, 7, 10}; + time_t timeValue = RdbStorePredicateTest::DateMakeTime(date); + dataType->SetTimeValue(timeValue); + + dataType->SetPrimIntValue(INT_MAX); + dataType->SetPrimDoubleValue(DBL_MAX); + dataType->SetPrimFloatValue(FLT_MAX); + dataType->SetPrimBooleanValue(true); + dataType->SetPrimByteValue(INT8_MAX); + dataType->SetPrimCharValue(' '); + dataType->SetPrimLongValue(LONG_MAX); + dataType->SetPrimShortValue(SHRT_MAX); + return dataType; +} + +AllDataType *RdbStorePredicateTest::BuildAllDataType2() +{ + std::vector blob = {1, 2, 3}; + AllDataType *dataType2 = new AllDataType(); + dataType2->SetId(2); + dataType2->SetIntegerValue(1); + dataType2->SetDoubleValue(1.0); + dataType2->SetBooleanValue(false); + dataType2->SetFloatValue(1.0); + dataType2->SetLongValue(static_cast(1)); + dataType2->SetShortValue(static_cast(1)); + dataType2->SetCharacterValue(' '); + dataType2->SetStringValue("ABCDEFGHIJKLMN"); + dataType2->SetBlobValue(blob); + dataType2->SetClobValue("ABCDEFGHIJKLMN"); + dataType2->SetByteValue(INT8_MIN); + + std::vector date = {2019, 7, 17}; + time_t timeValue2 = RdbStorePredicateTest::DateMakeTime(date); + dataType2->SetTimeValue(timeValue2); + + dataType2->SetPrimIntValue(1); + dataType2->SetPrimDoubleValue(1.0); + dataType2->SetPrimFloatValue(1.0); + dataType2->SetPrimBooleanValue(false); + dataType2->SetPrimByteValue(static_cast(1)); + dataType2->SetPrimCharValue(' '); + dataType2->SetPrimLongValue(static_cast(1)); + dataType2->SetPrimShortValue(static_cast(1)); + return dataType2; +} + +AllDataType *RdbStorePredicateTest::BuildAllDataType3() +{ + std::vector blob = {1, 2, 3}; + AllDataType *dataType3 = new AllDataType(); + dataType3->SetId(3); + dataType3->SetIntegerValue(INT_MIN); + dataType3->SetDoubleValue(DBL_MIN); + dataType3->SetBooleanValue(false); + dataType3->SetFloatValue(FLT_MIN); + dataType3->SetLongValue(LONG_MIN); + dataType3->SetShortValue(SHRT_MIN); + dataType3->SetCharacterValue(' '); + dataType3->SetStringValue("ABCDEFGHIJKLMN"); + dataType3->SetBlobValue(blob); + dataType3->SetClobValue("ABCDEFGHIJKLMN"); + dataType3->SetByteValue(INT8_MIN); + + std::vector date = {2019, 6, 10}; + time_t timeValue3 = RdbStorePredicateTest::DateMakeTime(date); + dataType3->SetTimeValue(timeValue3); + + dataType3->SetPrimIntValue(INT_MIN); + dataType3->SetPrimDoubleValue(DBL_MIN); + dataType3->SetPrimFloatValue(FLT_MIN); + dataType3->SetPrimBooleanValue(false); + dataType3->SetPrimByteValue(INT8_MIN); + dataType3->SetPrimCharValue(' '); + dataType3->SetPrimLongValue(LONG_MIN); + dataType3->SetPrimShortValue(SHRT_MIN); + return dataType3; +} + +void RdbStorePredicateTest::InsertDates(std::vector dataTypes) +{ + for (size_t i = 0; i < dataTypes.size(); i++) { + char characterValue = dataTypes[i].GetCharacterValue(); + char primCharValue = dataTypes[i].GetPrimCharValue(); + std::stringstream strByte; + std::vector objects; + objects.push_back(ValueObject(dataTypes[i].GetId())); + objects.push_back(ValueObject(dataTypes[i].GetIntegerValue())); + objects.push_back(ValueObject(dataTypes[i].GetLongValue())); + objects.push_back(ValueObject(dataTypes[i].GetShortValue())); + objects.push_back(ValueObject(dataTypes[i].GetBooleanValue())); + + strByte << dataTypes[i].GetDoubleValue(); + objects.push_back(ValueObject(strByte.str())); + + strByte.str(""); + strByte << dataTypes[i].GetFloatValue(); + objects.push_back(ValueObject(strByte.str())); + objects.push_back(ValueObject(dataTypes[i].GetStringValue())); + objects.push_back(ValueObject(dataTypes[i].GetBlobValue())); + objects.push_back(ValueObject(dataTypes[i].GetClobValue())); + objects.push_back(ValueObject(dataTypes[i].GetByteValue())); + objects.push_back(ValueObject(static_cast(dataTypes[i].GetTimeValue()))); + + strByte.str(""); + strByte << characterValue; + string str1 = strByte.str(); + objects.push_back(ValueObject(str1)); + objects.push_back(ValueObject(dataTypes[i].GetPrimIntValue())); + objects.push_back(ValueObject(dataTypes[i].GetPrimLongValue())); + objects.push_back(ValueObject(dataTypes[i].GetPrimShortValue())); + + strByte.str(""); + strByte << dataTypes[i].GetPrimFloatValue(); + objects.push_back(ValueObject(strByte.str())); + + strByte.str(""); + strByte << dataTypes[i].GetPrimDoubleValue(); + objects.push_back(ValueObject(strByte.str())); + objects.push_back(ValueObject(dataTypes[i].IsPrimBooleanValue() ? (char) 1 : (char) 0)); + objects.push_back(ValueObject(dataTypes[i].GetPrimByteValue())); + + strByte.str(""); + strByte << primCharValue; + string str2 = strByte.str(); + objects.push_back(ValueObject(str2)); + RdbStorePredicateTest::store->ExecuteSql(ALL_DATA_TYPE_INSERT_SQL, objects); + } +} + +time_t RdbStorePredicateTest::DateMakeTime(std::vector data) +{ + struct tm t1 = {0}; + t1.tm_year = data[0] - 1990; + t1.tm_mon = data[1] - 1; + t1.tm_hour = data[2]; + t1.tm_sec = 0; + t1.tm_min = 0; + t1.tm_mday = 0; + time_t time = mktime(&t1); + return time; +} + +/* * + * @tc.name: RdbStore_EqualTo_001 + * @tc.desc: Normal testCase of RdbPredicates for EqualTo + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_EqualTo_001, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + + BasicDataTypeTest(predicates1); + + CalendarTest(predicates1); +} + +void RdbStorePredicateTest::CalendarTest(RdbPredicates predicates1) +{ + std::vector columns; + + predicates1.Clear(); + std::vector date = {2019, 7, 17}; + time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); + + predicates1.EqualTo("timeValue", std::to_string(calendarTime)); + std::unique_ptr allDataTypes9 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(E_OK, allDataTypes9->GoToFirstRow()); + int valueInt = 0; + allDataTypes9->GetInt(0, valueInt); + EXPECT_EQ(2, valueInt); +} +void RdbStorePredicateTest::BasicDataTypeTest(RdbPredicates predicates1) +{ + std::vector columns; + std::stringstream tempValue; + predicates1.EqualTo("booleanValue", "1"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes1)); + + predicates1.Clear(); + predicates1.EqualTo("byteValue", std::to_string(INT8_MIN))->Or()->EqualTo("byteValue", std::to_string(1)); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes3)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MIN; + predicates1.EqualTo("doubleValue", tempValue.str()); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes4)); + + predicates1.Clear(); + predicates1.EqualTo("shortValue", std::to_string(SHRT_MIN)); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes5)); + + predicates1.Clear(); + predicates1.EqualTo("integerValue", std::to_string(1)); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(E_OK, allDataTypes6->GoToFirstRow()); + int valueInt = 0; + allDataTypes6->GetInt(0, valueInt); + EXPECT_EQ(2, valueInt); + + predicates1.Clear(); + predicates1.EqualTo("longValue", std::to_string(1)); + std::unique_ptr allDataTypes7 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(E_OK, allDataTypes7->GoToFirstRow()); + allDataTypes7->GetInt(0, valueInt); + EXPECT_EQ(2, valueInt); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.EqualTo("floatValue", tempValue.str()); + std::unique_ptr allDataTypes8 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(E_OK, allDataTypes8->GoToFirstRow()); + allDataTypes8->GetInt(0, valueInt); + EXPECT_EQ(3, valueInt); +} + +int RdbStorePredicateTest::ResultSize(std::unique_ptr &resultSet) +{ + if (resultSet->GoToFirstRow() != E_OK) { + return 0; + } + int count = 1; + while (resultSet->GoToNextRow() == E_OK) { + count++; + } + return count; +} + +/* * + * @tc.name: RdbStore_NotEqualTo_002 + * @tc.desc: Normal testCase of RdbPredicates for NotEqualTo + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_NotEqualTo_002, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + + BasicDataTypeTest002(predicates1); + + CalendarTest002(predicates1); +} + +void RdbStorePredicateTest::CalendarTest002(RdbPredicates predicates1) +{ + std::vector columns; + + predicates1.Clear(); + std::vector date = {2019, 7, 17}; + time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); + + predicates1.NotEqualTo("timeValue", std::to_string(calendarTime)); + std::unique_ptr allDataTypes9 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes9)); +} +void RdbStorePredicateTest::BasicDataTypeTest002(RdbPredicates predicates1) +{ + std::vector columns; + std::stringstream tempValue; + + predicates1.NotEqualTo("primBooleanValue", "1"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes1)); + + predicates1.Clear(); + predicates1.NotEqualTo("primByteValue", std::to_string(INT8_MIN))->NotEqualTo("primByteValue", std::to_string(1)); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.NotEqualTo("stringValue", "ABCDEFGHIJKLMN"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes3)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MIN; + predicates1.NotEqualTo("doubleValue", tempValue.str()); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes4)); + + predicates1.Clear(); + predicates1.NotEqualTo("shortValue", std::to_string(SHRT_MIN)); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes5)); + + predicates1.Clear(); + predicates1.NotEqualTo("integerValue", "1"); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes6)); + + predicates1.Clear(); + predicates1.NotEqualTo("longValue", "1"); + std::unique_ptr allDataTypes7 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes7)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.NotEqualTo("floatValue", tempValue.str()); + std::unique_ptr allDataTypes8 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes8)); +} + +/* * + * @tc.name: RdbStore_IsNull_003 + * @tc.desc: Normal testCase of RdbPredicates for IsNull + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_IsNull_003, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + predicates1.IsNull("primLongValue"); + std::vector columns; + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_NotNull_004 + * @tc.desc: Normal testCase of RdbPredicates for NotNull + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_NotNull_003, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + predicates1.IsNotNull("primLongValue"); + std::vector columns; + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_GreaterThan_005 + * @tc.desc: Normal testCase of RdbPredicates for GreaterThan + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_GreaterThan_005, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + std::stringstream tempValue; + + predicates1.GreaterThan("stringValue", "ABC"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MIN; + predicates1.GreaterThan("doubleValue", tempValue.str()); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.GreaterThan("integerValue", "1"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes3)); + + predicates1.Clear(); + predicates1.GreaterThan("longValue", "1"); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes4)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.GreaterThan("floatValue", tempValue.str()); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes5)); + + predicates1.Clear(); + std::vector date = {2019, 6, 9}; + time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); + predicates1.GreaterThan("timeValue", std::to_string(calendarTime).c_str()); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes6)); +} + +/* * + * @tc.name: RdbStore_GreaterThanOrEqualTo_006 + * @tc.desc: Normal testCase of RdbPredicates for GreaterThanOrEqualTo + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_GreaterThanOrEqualTo_006, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + std::stringstream tempValue; + + predicates1.GreaterThanOrEqualTo("stringValue", "ABC"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MIN; + predicates1.GreaterThanOrEqualTo("doubleValue", tempValue.str()); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.GreaterThanOrEqualTo("integerValue", "1"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes3)); + + predicates1.Clear(); + predicates1.GreaterThanOrEqualTo("longValue", "1"); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes4)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.GreaterThanOrEqualTo("floatValue", tempValue.str()); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes5)); + + predicates1.Clear(); + std::vector date = {2019, 6, 9}; + time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); + predicates1.GreaterThanOrEqualTo("timeValue", std::to_string(calendarTime).c_str()); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes6)); +} + +/* * + * @tc.name: RdbStore_lessThan_007 + * @tc.desc: Normal testCase of RdbPredicates for LessThan + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_lessThan_007, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + std::stringstream tempValue; + + predicates1.LessThan("stringValue", "ABD"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MIN; + predicates1.LessThan("doubleValue", tempValue.str()); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.LessThan("integerValue", "1"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes3)); + + predicates1.Clear(); + predicates1.LessThan("longValue", "1"); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes4)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.LessThan("floatValue", tempValue.str()); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes5)); + + predicates1.Clear(); + std::vector date = {2019, 6, 9}; + time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); + predicates1.LessThan("timeValue", std::to_string(calendarTime).c_str()); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes6)); +} + +/* * + * @tc.name: RdbStore_LessThanOrEqualTo_008 + * @tc.desc: Normal testCase of RdbPredicates for LessThanOrEqualTo + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_LessThanOrEqualTo_008, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + std::stringstream tempValue; + + predicates1.LessThanOrEqualTo("stringValue", "ABD"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MIN; + predicates1.LessThanOrEqualTo("doubleValue", tempValue.str()); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.LessThanOrEqualTo("integerValue", "1"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes3)); + + predicates1.Clear(); + predicates1.LessThanOrEqualTo("longValue", "1"); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes4)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.LessThanOrEqualTo("floatValue", tempValue.str()); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes5)); + + predicates1.Clear(); + std::vector date = {2019, 6, 9}; + time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); + predicates1.LessThanOrEqualTo("timeValue", std::to_string(calendarTime).c_str()); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes6)); +} + +/* * + * @tc.name: RdbStore_Between_009 + * @tc.desc: Normal testCase of RdbPredicates for Between + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_Between_009, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + std::stringstream tempValue; + + predicates1.Between("stringValue", "ABB", "ABD"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MAX; + predicates1.Between("doubleValue", "0.0", tempValue.str()); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.Between("integerValue", "0", "1"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes3)); + + predicates1.Clear(); + predicates1.Between("longValue", "0", "2"); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes4)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MAX; + std::string floatMax = tempValue.str(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.Between("floatValue", tempValue.str(), floatMax); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes5)); + + predicates1.Clear(); + std::vector lowCalendar = {2019, 6, 9}; + time_t lowCalendarTime = RdbStorePredicateTest::DateMakeTime(lowCalendar); + std::vector highCalendar = {2019, 7, 17}; + time_t highCalendarTime = RdbStorePredicateTest::DateMakeTime(highCalendar); + predicates1.Between("timeValue", std::to_string(lowCalendarTime).c_str(), std::to_string(highCalendarTime).c_str()); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes6)); +} + +/* * + * @tc.name: RdbStore_Contain_010 + * @tc.desc: Normal testCase of RdbPredicates for Contain + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_Contain_010, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.Contains("stringValue", "DEF"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_BeginsWith_011 + * @tc.desc: Normal testCase of RdbPredicates for BeginsWith + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_BeginsWith_011, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.BeginsWith("stringValue", "ABC"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_EndsWith_012 + * @tc.desc: Normal testCase of RdbPredicates for EndsWith + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_EndsWith_012, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.EndsWith("stringValue", "LMN"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_Like_013 + * @tc.desc: Normal testCase of RdbPredicates for Like + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_Like_013, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.Like("stringValue", "%LMN%"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_BeginEndWrap_014 + * @tc.desc: Normal testCase of RdbPredicates for BeginEndWrap + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_BeginEndWrap_014, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") + ->BeginWrap() + ->EqualTo("integerValue", "1") + ->Or() + ->EqualTo("integerValue", std::to_string(INT_MAX)) + ->EndWrap(); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes1)); + + predicates1.Clear(); + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->And()->EqualTo("integerValue", "1"); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes2)); +} + +/* * + * @tc.name: RdbStore_AndOR_015 + * @tc.desc: Normal testCase of RdbPredicates for AndOR + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_AndOR_015, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") + ->BeginWrap() + ->EqualTo("integerValue", "1") + ->Or() + ->EqualTo("integerValue", std::to_string(INT_MAX)) + ->EndWrap(); + + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes1)); + + predicates1.Clear(); + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->And()->EqualTo("integerValue", "1"); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes2)); +} + +/* * + * @tc.name: RdbStore_Order_016 + * @tc.desc: Normal testCase of RdbPredicates for Order + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_Order_016, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->OrderByAsc("integerValue")->Distinct(); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(E_OK, allDataTypes1->GoToFirstRow()); + int valueInt = 0; + allDataTypes1->GetInt(0, valueInt); + EXPECT_EQ(3, valueInt); + EXPECT_EQ(E_OK, allDataTypes1->GoToNextRow()); + allDataTypes1->GetInt(0, valueInt); + EXPECT_EQ(2, valueInt); + EXPECT_EQ(E_OK, allDataTypes1->GoToNextRow()); + allDataTypes1->GetInt(0, valueInt); + EXPECT_EQ(1, valueInt); + + predicates1.Clear(); + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->OrderByDesc("integerValue")->Distinct(); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(E_OK, allDataTypes2->GoToFirstRow()); + allDataTypes2->GetInt(0, valueInt); + EXPECT_EQ(1, valueInt); + EXPECT_EQ(E_OK, allDataTypes2->GoToNextRow()); + allDataTypes2->GetInt(0, valueInt); + EXPECT_EQ(2, valueInt); + EXPECT_EQ(E_OK, allDataTypes2->GoToNextRow()); + allDataTypes2->GetInt(0, valueInt); + EXPECT_EQ(3, valueInt); +} + +/* * + * @tc.name: RdbStore_Limit_017 + * @tc.desc: Normal testCase of RdbPredicates for Limit + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_Limit_017, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN")->Limit(1); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_JoinTypes_018 + * @tc.desc: Normal testCase of RdbPredicates for JoinTypes + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_JoinTypes_018, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector joinEntityNames; + + joinEntityNames.push_back("AllDataType"); + predicates1.SetJoinTableNames(joinEntityNames); + + std::vector joinTypes; + joinTypes.push_back("INNER JOIN"); + predicates1.SetJoinTypes(joinTypes); + + std::vector joinConditions; + joinConditions.push_back("ON"); + predicates1.SetJoinConditions(joinConditions); + predicates1.SetJoinCount(1); + + EXPECT_EQ(joinConditions, predicates1.GetJoinConditions()); + EXPECT_EQ(joinEntityNames, predicates1.GetJoinTableNames()); + EXPECT_EQ(joinTypes, predicates1.GetJoinTypes()); + EXPECT_EQ(1, predicates1.GetJoinCount()); +} + +/* * + * @tc.name: RdbStore_Glob_019 + * @tc.desc: Normal testCase of RdbPredicates for Glob + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_Glob_019, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.Glob("stringValue", "ABC*"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes1)); + + predicates1.Clear(); + predicates1.Glob("stringValue", "*EFG*"); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.Glob("stringValue", "?B*"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes3)); + + predicates1.Clear(); + predicates1.Glob("stringValue", "A????????????N"); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes4)); + + predicates1.Clear(); + predicates1.Glob("stringValue", "A?????????????N"); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes5)); + + predicates1.Clear(); + predicates1.Glob("stringValue", "?B*N"); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(3, ResultSize(allDataTypes6)); +} + +/* * + * @tc.name: RdbStore_NotBetween_020 + * @tc.desc: Normal testCase of RdbPredicates for NotBetween + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_NotBetween_020, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + std::stringstream tempValue; + + predicates1.NotBetween("stringValue", "ABB", "ABD"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes1)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << DBL_MAX; + predicates1.NotBetween("doubleValue", "0.0", tempValue.str()); + std::unique_ptr allDataTypes2 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes2)); + + predicates1.Clear(); + predicates1.NotBetween("integerValue", "0", "1"); + std::unique_ptr allDataTypes3 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes3)); + + predicates1.Clear(); + predicates1.NotBetween("longValue", "0", "2"); + std::unique_ptr allDataTypes4 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes4)); + + predicates1.Clear(); + tempValue.str(""); + tempValue << FLT_MAX; + std::string floatMax = tempValue.str(); + tempValue.str(""); + tempValue << FLT_MIN; + predicates1.NotBetween("floatValue", tempValue.str(), floatMax); + std::unique_ptr allDataTypes5 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes5)); + + std::vector lowCalendar = {2019, 6, 9}; + time_t lowCalendarTime = RdbStorePredicateTest::DateMakeTime(lowCalendar); + std::vector highCalendar = {2019, 7, 17}; + time_t highCalendarTime = RdbStorePredicateTest::DateMakeTime(highCalendar); + predicates1.Clear(); + predicates1.NotBetween("timeValue", std::to_string(lowCalendarTime), std::to_string(highCalendarTime)); + std::unique_ptr allDataTypes6 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(0, ResultSize(allDataTypes6)); +} + +/* * + * @tc.name: RdbStore_ComplexPredicate_021 + * @tc.desc: Normal testCase of RdbPredicates for complex combine sql + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_ComplexPredicate_021, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.Glob("stringValue", "ABC*")->EqualTo("booleanValue", "1") + ->NotBetween("longValue", "0", "2"); + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(1, ResultSize(allDataTypes1)); +} + +/* * + * @tc.name: RdbStore_ClearMethod_022 + * @tc.desc: Normal testCase of RdbPredicates for Clear Method + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_ClearMethod_022, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + std::vector columns; + + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") + ->BeginWrap() + ->EqualTo("integerValue", "1") + ->Or() + ->EqualTo("integerValue", std::to_string(INT_MAX)) + ->EndWrap() + ->OrderByDesc("integerValue") + ->Limit(2); + + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + EXPECT_EQ(2, ResultSize(allDataTypes1)); + + EXPECT_EQ("AllDataType", predicates1.GetTableName()); + EXPECT_EQ(2, predicates1.GetLimit()); + EXPECT_EQ(true, predicates1.GetWhereClause().find("stringValue") != std::string::npos); + + std::vector agrs = predicates1.GetWhereArgs(); + auto ret = find(agrs.begin(), agrs.end(), "ABCDEFGHIJKLMN"); + EXPECT_EQ(true, ret != agrs.end()); + + std::vector lists = {"ohos", "bazhahei", "zhaxidelie"}; + predicates1.SetJoinTableNames(lists); + predicates1.SetJoinCount(1); + predicates1.SetJoinConditions(lists); + predicates1.SetJoinTypes(lists); + predicates1.SetOrder("ohos"); + predicates1.Distinct(); + + agrs = predicates1.GetJoinTableNames(); + ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); + EXPECT_EQ(true, ret != agrs.end()); + EXPECT_EQ(1, predicates1.GetJoinCount()); + + agrs = predicates1.GetJoinConditions(); + ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); + EXPECT_EQ(true, ret != agrs.end()); + + agrs = predicates1.GetJoinTypes(); + ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); + EXPECT_EQ(true, ret != agrs.end()); + EXPECT_EQ(true, predicates1.GetJoinClause().find("ohos") != std::string::npos); + EXPECT_EQ("ohos", predicates1.GetOrder()); + EXPECT_EQ(true, predicates1.IsDistinct()); + + predicates1.Clear(); + EXPECT_EQ("AllDataType", predicates1.GetTableName()); + EXPECT_EQ(-1, predicates1.GetLimit()); + EXPECT_EQ(true, predicates1.GetWhereClause().empty()); + EXPECT_EQ(true, predicates1.GetWhereArgs().empty()); + + EXPECT_EQ(true, predicates1.GetJoinTableNames().empty()); + EXPECT_EQ(0, predicates1.GetJoinCount()); + EXPECT_EQ(true, predicates1.GetJoinConditions().empty()); + EXPECT_EQ(true, predicates1.GetJoinTypes().empty()); + EXPECT_EQ("AllDataType", predicates1.GetJoinClause()); + EXPECT_EQ(true, predicates1.GetOrder().empty()); + EXPECT_EQ(false, predicates1.IsDistinct()); +} + +/* * + * @tc.name: RdbStore_InMethod_023 + * @tc.desc: Normal testCase of RdbPredicates for in method + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_InMethod_023, TestSize.Level1) +{ + RdbPredicates rdbPredicates1("AllDataType"); + std::vector columns; + std::vector agrs = {std::to_string(INT_MAX)}; + rdbPredicates1.In("integerValue", agrs); + std::unique_ptr resultSet1 = RdbStorePredicateTest::store->Query(rdbPredicates1, columns); + int count = 0; + resultSet1->GetRowCount(count); + EXPECT_EQ(1, count); + + RdbPredicates rdbPredicates2("AllDataType"); + agrs[0] = "1"; + rdbPredicates2.In("longValue", agrs); + std::unique_ptr resultSet2 = RdbStorePredicateTest::store->Query(rdbPredicates2, columns); + resultSet2->GetRowCount(count); + EXPECT_EQ(1, count); + + RdbPredicates rdbPredicates3("AllDataType"); + agrs[0] = "1.0"; + rdbPredicates3.In("doubleValue", agrs); + std::unique_ptr resultSet3 = RdbStorePredicateTest::store->Query(rdbPredicates3, columns); + resultSet3->GetRowCount(count); + EXPECT_EQ(1, count); + + RdbPredicates rdbPredicates4("AllDataType"); + rdbPredicates4.In("floatValue", agrs); + std::unique_ptr resultSet4 = RdbStorePredicateTest::store->Query(rdbPredicates4, columns); + resultSet4->GetRowCount(count); + EXPECT_EQ(1, count); + + std::vector date = {2019, 6, 10}; + time_t calendarTime = RdbStorePredicateTest::DateMakeTime(date); + RdbPredicates rdbPredicates5("AllDataType"); + agrs[0] = std::to_string(calendarTime); + rdbPredicates5.In("timeValue", agrs); + std::unique_ptr resultSet5 = RdbStorePredicateTest::store->Query(rdbPredicates5, columns); + resultSet5->GetRowCount(count); + EXPECT_EQ(1, count); +} + +/* * + * @tc.name: RdbStore_NotInMethod_023 + * @tc.desc: Normal testCase of RdbPredicates for notIn method + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_NotInMethod_023, TestSize.Level1) +{ + std::vector columns; + std::vector agrs = {std::to_string(INT_MAX), std::to_string(INT_MIN)}; + std::stringstream tempValue; + + RdbPredicates rdbPredicates1("AllDataType"); + rdbPredicates1.NotIn("integerValue", agrs); + std::unique_ptr resultSet1 = RdbStorePredicateTest::store->Query(rdbPredicates1, columns); + int count = 0; + resultSet1->GetRowCount(count); + EXPECT_EQ(1, count); + + RdbPredicates rdbPredicates2("AllDataType"); + agrs[0] = "1"; + agrs[1] = std::to_string(LONG_MAX); + rdbPredicates2.NotIn("longValue", agrs); + std::unique_ptr resultSet2 = RdbStorePredicateTest::store->Query(rdbPredicates2, columns); + resultSet2->GetRowCount(count); + EXPECT_EQ(1, count); + + RdbPredicates rdbPredicates3("AllDataType"); + tempValue.str(""); + tempValue << DBL_MIN; + agrs[0] = "1.0"; + agrs[1] = tempValue.str(); + rdbPredicates3.NotIn("doubleValue", agrs); + std::unique_ptr resultSet3 = RdbStorePredicateTest::store->Query(rdbPredicates3, columns); + resultSet3->GetRowCount(count); + EXPECT_EQ(1, count); + + RdbPredicates rdbPredicates4("AllDataType"); + tempValue.str(""); + tempValue << FLT_MAX; + agrs[0] = "1.0"; + agrs[1] = tempValue.str(); + rdbPredicates4.NotIn("floatValue", agrs); + std::unique_ptr resultSet4 = RdbStorePredicateTest::store->Query(rdbPredicates4, columns); + resultSet4->GetRowCount(count); + EXPECT_EQ(1, count); +} + +/* * + * @tc.name: RdbStore_KeywordMethod_024 + * @tc.desc: Normal testCase of RdbPredicates for clear method + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStorePredicateTest, RdbStore_KeywordMethod_024, TestSize.Level1) +{ + RdbPredicates predicates1("AllDataType"); + predicates1.EqualTo("stringValue", "ABCDEFGHIJKLMN") + ->BeginWrap() + ->EqualTo("integerValue", "1") + ->Or() + ->EqualTo("integerValue", std::to_string(INT_MAX)) + ->EndWrap()->OrderByDesc("integerValue")->Limit(2); + std::vector columns = {"booleanValue", "doubleValue", "order"}; + std::unique_ptr allDataTypes1 = RdbStorePredicateTest::store->Query(predicates1, columns); + allDataTypes1->GoToFirstRow(); + EXPECT_EQ(2, ResultSize(allDataTypes1)); + + EXPECT_EQ("AllDataType", predicates1.GetTableName()); + EXPECT_EQ(2, predicates1.GetLimit()); + + EXPECT_EQ(true, predicates1.GetWhereClause().find("stringValue") != std::string::npos); + std::vector agrs = predicates1.GetWhereArgs(); + auto ret = find(agrs.begin(), agrs.end(), "ABCDEFGHIJKLMN"); + EXPECT_EQ(true, ret != agrs.end()); + + std::vector lists = {"ohos", "bazhahei", "zhaxidelie"}; + predicates1.SetJoinTableNames(lists); + predicates1.SetJoinCount(1); + predicates1.SetJoinConditions(lists); + predicates1.SetJoinTypes(lists); + predicates1.SetOrder("ohos"); + predicates1.Distinct(); + + agrs = predicates1.GetJoinTableNames(); + ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); + EXPECT_EQ(true, ret != agrs.end()); + EXPECT_EQ(1, predicates1.GetJoinCount()); + + agrs = predicates1.GetJoinConditions(); + ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); + EXPECT_EQ(true, ret != agrs.end()); + + agrs = predicates1.GetJoinTypes(); + ret = find(agrs.begin(), agrs.end(), "zhaxidelie"); + EXPECT_EQ(true, ret != agrs.end()); + EXPECT_EQ(true, predicates1.GetJoinClause().find("ohos") != std::string::npos); + EXPECT_EQ("ohos", predicates1.GetOrder()); + EXPECT_EQ(true, predicates1.IsDistinct()); + + predicates1.Clear(); + EXPECT_EQ("AllDataType", predicates1.GetTableName()); + EXPECT_EQ(-1, predicates1.GetLimit()); + EXPECT_EQ(true, predicates1.GetWhereClause().empty()); + EXPECT_EQ(true, predicates1.GetWhereArgs().empty()); + + EXPECT_EQ(true, predicates1.GetJoinTableNames().empty()); + EXPECT_EQ(0, predicates1.GetJoinCount()); + EXPECT_EQ(true, predicates1.GetJoinConditions().empty()); + EXPECT_EQ(true, predicates1.GetJoinTypes().empty()); + EXPECT_EQ("AllDataType", predicates1.GetJoinClause()); + EXPECT_EQ(true, predicates1.GetOrder().empty()); + EXPECT_EQ(false, predicates1.IsDistinct()); +} diff --git a/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp b/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp index e3527c50b7b8b7e3907bec373225a7a08b1be0ad..5dd2b02b08ed7fcfd9719106bd3e18b3580ba4a6 100644 --- a/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp @@ -1,909 +1,909 @@ -/* - * 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 "sqlite_shared_result_set.h" -#include "shared_block.h" -#include "logger.h" -#include "common.h" -#include "rdb_errno.h" -#include "rdb_helper.h" -#include "rdb_open_callback.h" - -using namespace testing::ext; -using namespace OHOS::NativeRdb; -class RdbSqliteSharedResultSetTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - void GenerateDefaultTable(); - - static const std::string DATABASE_NAME; - static std::shared_ptr store; - static const int E_SQLITE_ERROR; -}; - -const std::string RdbSqliteSharedResultSetTest::DATABASE_NAME = RDB_TEST_PATH + "shared_test.db"; -std::shared_ptr RdbSqliteSharedResultSetTest::store = nullptr; -const int RdbSqliteSharedResultSetTest::E_SQLITE_ERROR = -1; - -class SqliteSharedOpenCallback : public RdbOpenCallback { -public: - int OnCreate(RdbStore &rdbStore) override; - int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override; - static const std::string CREATE_TABLE_TEST; -}; - -std::string const SqliteSharedOpenCallback::CREATE_TABLE_TEST = - "CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 TEXT,data2 INTEGER, data3 FLOAT, data4 BLOB);"; - - -int SqliteSharedOpenCallback::OnCreate(RdbStore &rdbStore) -{ - return rdbStore.ExecuteSql(CREATE_TABLE_TEST); -} - -int SqliteSharedOpenCallback::OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) -{ - return E_OK; -} - -void RdbSqliteSharedResultSetTest::SetUpTestCase(void) -{ - RdbStoreConfig sqliteSharedRstConfig(RdbSqliteSharedResultSetTest::DATABASE_NAME); - SqliteSharedOpenCallback sqliteSharedRstHelper; - int errCode = E_OK; - RdbSqliteSharedResultSetTest::store = - RdbHelper::GetRdbStore(sqliteSharedRstConfig, 1, sqliteSharedRstHelper, errCode); - EXPECT_NE(RdbSqliteSharedResultSetTest::store, nullptr); -} - -void RdbSqliteSharedResultSetTest::TearDownTestCase(void) -{ - RdbHelper::DeleteRdbStore(RdbSqliteSharedResultSetTest::DATABASE_NAME); -} - -void RdbSqliteSharedResultSetTest::SetUp() -{ - store->ExecuteSql("DELETE FROM test"); -} - -void RdbSqliteSharedResultSetTest::TearDown() -{} - -void RdbSqliteSharedResultSetTest::GenerateDefaultTable() -{ - std::shared_ptr &store = RdbSqliteSharedResultSetTest::store; - - int64_t id; - ValuesBucket values; - - values.PutInt("id", 1); - values.PutString("data1", std::string("hello")); - values.PutInt("data2", 10); - values.PutDouble("data3", 1.0); - values.PutBlob("data4", std::vector { 66 }); - store->Insert(id, "test", values); - - values.Clear(); - values.PutInt("id", 2); - values.PutString("data1", std::string("2")); - values.PutInt("data2", -5); - values.PutDouble("data3", 2.5); - values.PutBlob("data4", std::vector {}); - store->Insert(id, "test", values); - - values.Clear(); - values.PutInt("id", 3); - values.PutString("data1", std::string("hello world")); - values.PutInt("data2", 3); - values.PutDouble("data3", 1.8); - values.PutBlob("data4", std::vector {}); - store->Insert(id, "test", values); -} - -/* * - * @tc.name: RdbStore_Delete_001 - * @tc.desc: normal testcase of SqliteSharedResultSet for move - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_001, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int ret = rstSet->GoToRow(1); - EXPECT_EQ(ret, E_OK); - - int rowCnt = -1; - ret = rstSet->GetRowCount(rowCnt); - EXPECT_EQ(rowCnt, 3); - - std::string colName = ""; - rstSet->GetColumnName(1, colName); - EXPECT_EQ(colName, "data1"); - - rstSet->GetColumnName(2, colName); - EXPECT_EQ(colName, "data2"); - - rstSet->GetColumnName(3, colName); - EXPECT_EQ(colName, "data3"); - - rstSet->GetColumnName(4, colName); - EXPECT_EQ(colName, "data4"); - - std::string valueStr = ""; - rstSet->GetString(0, valueStr); - EXPECT_EQ(valueStr, "2"); - - rstSet->GetString(1, valueStr); - EXPECT_EQ(valueStr, "2"); - - int64_t valuelg = 0; - rstSet->GetLong(2, valuelg); - EXPECT_EQ(valuelg, -5); - - double valueDb = 0.0; - rstSet->GetDouble(3, valueDb); - EXPECT_EQ(valueDb, 2.5); - - std::vector blob; - rstSet->GetBlob(4, blob); - int sz = blob.size(); - EXPECT_EQ(sz, 0); - - rstSet->GoTo(1); - rstSet->GetString(0, valueStr); - EXPECT_EQ(valueStr, "3"); - - rstSet->GetString(1, valueStr); - EXPECT_EQ(valueStr, "hello world"); - - rstSet->GetLong(2, valuelg); - EXPECT_EQ(valuelg, 3); - - rstSet->GetDouble(3, valueDb); - EXPECT_EQ(valueDb, 1.8); - - rstSet->GetBlob(4, blob); - sz = blob.size(); - EXPECT_EQ(sz, 0); - - bool isNull = false; - rstSet->IsColumnNull(4, isNull); - EXPECT_EQ(isNull, true); - - ret = -1; - ret = rstSet->GoToPreviousRow(); - EXPECT_EQ(ret, E_OK); - ret = -1; - ret = rstSet->GoToPreviousRow(); - EXPECT_EQ(ret, E_OK); - - rstSet->GetString(0, valueStr); - EXPECT_EQ(valueStr, "1"); - - rstSet->GetString(1, valueStr); - EXPECT_EQ(valueStr, "hello"); - - rstSet->GetLong(2, valuelg); - EXPECT_EQ(valuelg, 10); - - rstSet->GetDouble(3, valueDb); - EXPECT_EQ(valueDb, 1.0); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_002 - * @tc.desc: normal testcase of SqliteSharedResultSet for goToNextRow - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_002, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int pos = -2; - rstSet->GetRowIndex(pos); - EXPECT_EQ(pos, -1); - bool isStart = true; - rstSet->IsStarted(isStart); - EXPECT_EQ(isStart, false); - bool isAtFirstRow = true; - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, false); - bool isEnded = true; - rstSet->IsEnded(isEnded); - EXPECT_EQ(isEnded, false); - - int retN1 = rstSet->GoToNextRow(); - EXPECT_EQ(retN1, E_OK); - rstSet->GetRowIndex(pos); - EXPECT_EQ(pos, 0); - rstSet->IsStarted(isStart); - EXPECT_EQ(isStart, true); - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, true); - isEnded = true; - rstSet->IsEnded(isEnded); - EXPECT_EQ(isEnded, false); - - int retN2 = rstSet->GoToNextRow(); - EXPECT_EQ(retN2, E_OK); - rstSet->GetRowIndex(pos); - EXPECT_EQ(pos, 1); - isStart = false; - rstSet->IsStarted(isStart); - EXPECT_EQ(isStart, true); - isAtFirstRow = true; - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, false); - isEnded = true; - rstSet->IsEnded(isEnded); - EXPECT_EQ(isEnded, false); - - int retN3 = rstSet->GoToNextRow(); - EXPECT_EQ(retN3, E_OK); - rstSet->GetRowIndex(pos); - EXPECT_EQ(pos, 2); - isStart = false; - rstSet->IsStarted(isStart); - EXPECT_EQ(isStart, true); - isAtFirstRow = true; - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, false); - bool isAtLastRow = false; - rstSet->IsAtLastRow(isAtLastRow); - EXPECT_EQ(isAtLastRow, true); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_ERROR); - rstSet->GetRowIndex(pos); - EXPECT_EQ(pos, 3); - isStart = false; - rstSet->IsStarted(isStart); - EXPECT_EQ(isStart, true); - isAtFirstRow = true; - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, false); - isEnded = false; - rstSet->IsEnded(isEnded); - EXPECT_EQ(isEnded, true); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_003 - * @tc.desc: normal testcase of SqliteSharedResultSet for moveFirst - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_003, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - int index = -1; - rstSet->GetRowIndex(index); - EXPECT_EQ(index, 0); - bool isAtFirstRow = false; - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, true); - bool isStd = false; - rstSet->IsStarted(isStd); - EXPECT_EQ(isStd, true); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_OK); - rstSet->GetRowIndex(index); - EXPECT_EQ(index, 1); - isAtFirstRow = true; - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, false); - isStd = false; - rstSet->IsStarted(isStd); - EXPECT_EQ(isStd, true); - - int retGf = rstSet->GoToFirstRow(); - EXPECT_EQ(retGf, E_OK); - rstSet->GetRowIndex(index); - EXPECT_EQ(index, 0); - isAtFirstRow = false; - rstSet->IsAtFirstRow(isAtFirstRow); - EXPECT_EQ(isAtFirstRow, true); - isStd = false; - rstSet->IsStarted(isStd); - EXPECT_EQ(isStd, true); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_004 - * @tc.desc: normal testcase of SqliteSharedResultSet for getInt - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_004, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int64_t valueInt = 0; - int ret = rstSet->GetLong(0, valueInt); - EXPECT_EQ(ret, E_INVALID_STATEMENT); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - rstSet->GetLong(0, valueInt); - EXPECT_EQ(valueInt, 1); - rstSet->GetLong(2, valueInt); - EXPECT_EQ(valueInt, 10); - rstSet->GetLong(3, valueInt); - EXPECT_EQ(valueInt, 1); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_OK); - rstSet->GetLong(0, valueInt); - EXPECT_EQ(valueInt, 2); - valueInt = 0; - rstSet->GetLong(0, valueInt); - EXPECT_EQ(valueInt, 2); - valueInt = 0; - rstSet->GetLong(1, valueInt); - EXPECT_EQ(valueInt, 2); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_005 - * @tc.desc: normal testcase of SqliteSharedResultSet for getString - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ - -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_005, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - std::string valueStr = ""; - int ret1 = rstSet->GetString(0, valueStr); - EXPECT_EQ(ret1, E_INVALID_STATEMENT); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - valueStr = ""; - rstSet->GetString(1, valueStr); - EXPECT_EQ(valueStr, "hello"); - rstSet->GetString(2, valueStr); - EXPECT_EQ(valueStr, "10"); - rstSet->GetString(3, valueStr); - EXPECT_EQ(valueStr, "1"); - - int ret2 = rstSet->GetString(4, valueStr); - EXPECT_EQ(ret2, E_ERROR); - - valueStr = ""; - int colCnt = 0; - rstSet->GetColumnCount(colCnt); - int ret3 = rstSet->GetString(colCnt, valueStr); - EXPECT_EQ(ret3, E_INVALID_COLUMN_INDEX); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_OK); - rstSet->GetString(0, valueStr); - EXPECT_EQ(valueStr, "2"); - valueStr = ""; - rstSet->GetString(1, valueStr); - EXPECT_EQ(valueStr, "2"); - rstSet->GetString(2, valueStr); - EXPECT_EQ(valueStr, "-5"); - rstSet->GetString(3, valueStr); - EXPECT_EQ(valueStr, "2.5"); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_006 - * @tc.desc: normal testcase of SqliteSharedResultSet for getDouble - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_006, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - double valueDb = 0.0; - int ret = rstSet->GetDouble(0, valueDb); - EXPECT_EQ(ret, E_INVALID_STATEMENT); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - rstSet->GetDouble(0, valueDb); - EXPECT_EQ(valueDb, 1.0); - std::string valueStr = ""; - rstSet->GetString(1, valueStr); - EXPECT_EQ(valueStr, "hello"); - rstSet->GetDouble(2, valueDb); - EXPECT_EQ(valueDb, 10.0); - rstSet->GetDouble(3, valueDb); - EXPECT_EQ(valueDb, 1.0); - - int colCnt = 0; - rstSet->GetColumnCount(colCnt); - int ret1 = rstSet->GetDouble(colCnt, valueDb); - EXPECT_EQ(ret1, E_INVALID_COLUMN_INDEX); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_OK); - rstSet->GetDouble(0, valueDb); - EXPECT_EQ(valueDb, 2.0); - valueDb = 0.0; - rstSet->GetDouble(1, valueDb); - EXPECT_EQ(valueDb, 2.0); - - rstSet->GetDouble(2, valueDb); - EXPECT_EQ(valueDb, -5.0); - rstSet->GetDouble(3, valueDb); - EXPECT_EQ(valueDb, 2.5); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_007 - * @tc.desc: normal testcase of SqliteSharedResultSet for getBlob - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_007, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - - std::vector blobVec; - rstSet->GetBlob(4, blobVec); - EXPECT_EQ(blobVec[0], 66); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_OK); - blobVec.clear(); - rstSet->GetBlob(4, blobVec); - int blobSz = blobVec.size(); - EXPECT_EQ(blobSz, 0); - - int retN1 = rstSet->GoToNextRow(); - EXPECT_EQ(retN1, E_OK); - blobVec.clear(); - rstSet->GetBlob(4, blobVec); - EXPECT_EQ(blobSz, 0); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_008 - * @tc.desc: normal testcase of SqliteSharedResultSet for getColumnTypeForIndex - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ - -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_008, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - ColumnType colType; - int ret = rstSet->GetColumnType(0, colType); - EXPECT_EQ(ret, E_ERROR); - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - - rstSet->GetColumnType(0, colType); - EXPECT_EQ(colType, ColumnType::TYPE_INTEGER); - - bool isColNull = true; - rstSet->IsColumnNull(0, isColNull); - EXPECT_EQ(isColNull, false); - - rstSet->GetColumnType(1, colType); - EXPECT_EQ(colType, ColumnType::TYPE_STRING); - - isColNull = true; - rstSet->IsColumnNull(0, isColNull); - EXPECT_EQ(isColNull, false); - - rstSet->GetColumnType(2, colType); - EXPECT_EQ(colType, ColumnType::TYPE_INTEGER); - rstSet->GetColumnType(3, colType); - EXPECT_EQ(colType, ColumnType::TYPE_FLOAT); - rstSet->GetColumnType(4, colType); - EXPECT_EQ(colType, ColumnType::TYPE_BLOB); - - int colCnt = 0; - rstSet->GetColumnCount(colCnt); - int ret1 = rstSet->GetColumnType(colCnt, colType); - EXPECT_EQ(ret1, E_ERROR); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_009 - * @tc.desc: normal testcase of SqliteSharedResultSet for getColumnIndexForName - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_009, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int colIndex = 0; - rstSet->GetColumnIndex("data1", colIndex); - EXPECT_EQ(colIndex, 1); - - rstSet->GetColumnIndex("data2", colIndex); - EXPECT_EQ(colIndex, 2); - - rstSet->GetColumnIndex("data3", colIndex); - EXPECT_EQ(colIndex, 3); - - rstSet->GetColumnIndex("data4", colIndex); - EXPECT_EQ(colIndex, 4); - - rstSet->GetColumnIndex("datax", colIndex); - EXPECT_EQ(colIndex, -1); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_010 - * @tc.desc: normal testcase of SqliteSharedResultSet for getColumnNameForIndex - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_010, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - std::vector allColNamesVec; - rstSet->GetAllColumnNames(allColNamesVec); - - std::string colName = ""; - rstSet->GetColumnName(1, colName); - EXPECT_EQ(colName, "data1"); - EXPECT_EQ(allColNamesVec[1], colName); - - rstSet->GetColumnName(2, colName); - EXPECT_EQ(colName, "data2"); - EXPECT_EQ(allColNamesVec[2], colName); - - rstSet->GetColumnName(3, colName); - EXPECT_EQ(colName, "data3"); - rstSet->GetColumnName(4, colName); - EXPECT_EQ(colName, "data4"); - - int colCnt = 0; - rstSet->GetColumnCount(colCnt); - int ret = rstSet->GetColumnName(colCnt, colName); - EXPECT_EQ(ret, E_INVALID_COLUMN_INDEX); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_011 - * @tc.desc: normal testcase of SqliteSharedResultSet - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_011, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - - bool isAtFrtRow = false; - rstSet->IsAtFirstRow(isAtFrtRow); - EXPECT_EQ(isAtFrtRow, true); - - bool isStarted = false; - rstSet->IsStarted(isStarted); - EXPECT_EQ(isStarted, true); - - int64_t valueInt = 0; - rstSet->GetLong(2, valueInt); - EXPECT_EQ(valueInt, 10); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_012 - * @tc.desc: normal testcase of SqliteSharedResultSet for getLong - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_012, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int64_t valueInt = 0; - int ret = rstSet->GetLong(0, valueInt); - EXPECT_EQ(ret, E_INVALID_STATEMENT); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - rstSet->GetLong(0, valueInt); - EXPECT_EQ(valueInt, 1.0); - std::string valueStr = ""; - rstSet->GetString(1, valueStr); - EXPECT_EQ(valueStr, "hello"); - rstSet->GetLong(2, valueInt); - EXPECT_EQ(valueInt, 10.0); - rstSet->GetLong(3, valueInt); - EXPECT_EQ(valueInt, 1.0); - - int colCnt = 0; - rstSet->GetColumnCount(colCnt); - int ret1 = rstSet->GetLong(colCnt, valueInt); - EXPECT_EQ(ret1, E_INVALID_COLUMN_INDEX); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_OK); - rstSet->GetLong(0, valueInt); - EXPECT_EQ(valueInt, 2.0); - valueInt = 0; - rstSet->GetLong(1, valueInt); - EXPECT_EQ(valueInt, 2.0); - rstSet->GetLong(2, valueInt); - EXPECT_EQ(valueInt, -5.0); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_013 - * @tc.desc: normal testcase of SqliteSharedResultSet for fillBlock - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_013, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); - bool isBk = pSqlSharedRstSet->HasBlock(); - EXPECT_EQ(isBk, true); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} -/* * - * @tc.name: Sqlite_Shared_Result_Set_014 - * @tc.desc: normal testcase of SqliteSharedResultSet for getBlock - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_014, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); - bool isBk = pSqlSharedRstSet->HasBlock(); - EXPECT_EQ(isBk, true); - - int retF = rstSet->GoToFirstRow(); - EXPECT_EQ(retF, E_OK); - OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); - EXPECT_NE(pBk, nullptr); - - std::string path = RdbSqliteSharedResultSetTest::store->GetPath(); - std::string path1 = pBk->Name(); - - EXPECT_EQ(path, "/data/test/shared_test.db"); - EXPECT_EQ(path1, "/data/test/shared_test.db"); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} -/* * - * @tc.name: Sqlite_Shared_Result_Set_015 - * @tc.desc: normal testcase of SqliteSharedResultSet for setBlock - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_015, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); - bool isBk = pSqlSharedRstSet->HasBlock(); - EXPECT_EQ(isBk, true); - - int retN = rstSet->GoToNextRow(); - EXPECT_EQ(retN, E_OK); - - std::string path = RdbSqliteSharedResultSetTest::store->GetPath(); - OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); - std::string path1 = pBk->Name(); - - EXPECT_EQ(path, "/data/test/shared_test.db"); - EXPECT_EQ(path1, "/data/test/shared_test.db"); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_016 - * @tc.desc: normal testcase of SqliteSharedResultSet for setFillWindowForwardOnly - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_016, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); - bool isBk = pSqlSharedRstSet->HasBlock(); - EXPECT_EQ(isBk, true); - - pSqlSharedRstSet->PickFillBlockStartPosition(0, 0); - pSqlSharedRstSet->SetFillBlockForwardOnly(true); - pSqlSharedRstSet->GoToFirstRow(); - - OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); - EXPECT_NE(pBk, nullptr); - std::string path = RdbSqliteSharedResultSetTest::store->GetPath(); - std::string path1 = pBk->Name(); - - EXPECT_EQ(path, "/data/test/shared_test.db"); - EXPECT_EQ(path1, "/data/test/shared_test.db"); - - int rowCnt = 0; - pSqlSharedRstSet->GetRowCount(rowCnt); - int rowCntBk = pBk->GetRowNum(); - - EXPECT_EQ(rowCnt, rowCntBk); - - rstSet->Close(); - bool isClosedFlag = rstSet->IsClosed(); - EXPECT_EQ(isClosedFlag, true); -} - -/* * - * @tc.name: Sqlite_Shared_Result_Set_017 - * @tc.desc: normal testcase of SqliteSharedResultSet for setExtensions and getExtensions - * @tc.type: FUNC - * @tc.require: AR000FKD4F - */ -HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_017, TestSize.Level1) -{ - GenerateDefaultTable(); - std::vector selectionArgs; - std::unique_ptr rstSet = - RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); - EXPECT_NE(rstSet, nullptr); - - int rowCnt = 0; - rstSet->GetRowCount(rowCnt); - EXPECT_EQ(rowCnt, 3); - int ret = rstSet->GoToLastRow(); - EXPECT_EQ(ret, E_OK); -} +/* + * 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 "sqlite_shared_result_set.h" +#include "shared_block.h" +#include "logger.h" +#include "common.h" +#include "rdb_errno.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" + +using namespace testing::ext; +using namespace OHOS::NativeRdb; +class RdbSqliteSharedResultSetTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + void GenerateDefaultTable(); + + static const std::string DATABASE_NAME; + static std::shared_ptr store; + static const int E_SQLITE_ERROR; +}; + +const std::string RdbSqliteSharedResultSetTest::DATABASE_NAME = RDB_TEST_PATH + "shared_test.db"; +std::shared_ptr RdbSqliteSharedResultSetTest::store = nullptr; +const int RdbSqliteSharedResultSetTest::E_SQLITE_ERROR = -1; + +class SqliteSharedOpenCallback : public RdbOpenCallback { +public: + int OnCreate(RdbStore &rdbStore) override; + int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override; + static const std::string CREATE_TABLE_TEST; +}; + +std::string const SqliteSharedOpenCallback::CREATE_TABLE_TEST = + "CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 TEXT,data2 INTEGER, data3 FLOAT, data4 BLOB);"; + + +int SqliteSharedOpenCallback::OnCreate(RdbStore &rdbStore) +{ + return rdbStore.ExecuteSql(CREATE_TABLE_TEST); +} + +int SqliteSharedOpenCallback::OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) +{ + return E_OK; +} + +void RdbSqliteSharedResultSetTest::SetUpTestCase(void) +{ + RdbStoreConfig sqliteSharedRstConfig(RdbSqliteSharedResultSetTest::DATABASE_NAME); + SqliteSharedOpenCallback sqliteSharedRstHelper; + int errCode = E_OK; + RdbSqliteSharedResultSetTest::store = + RdbHelper::GetRdbStore(sqliteSharedRstConfig, 1, sqliteSharedRstHelper, errCode); + EXPECT_NE(RdbSqliteSharedResultSetTest::store, nullptr); +} + +void RdbSqliteSharedResultSetTest::TearDownTestCase(void) +{ + RdbHelper::DeleteRdbStore(RdbSqliteSharedResultSetTest::DATABASE_NAME); +} + +void RdbSqliteSharedResultSetTest::SetUp() +{ + store->ExecuteSql("DELETE FROM test"); +} + +void RdbSqliteSharedResultSetTest::TearDown() +{} + +void RdbSqliteSharedResultSetTest::GenerateDefaultTable() +{ + std::shared_ptr &store = RdbSqliteSharedResultSetTest::store; + + int64_t id; + ValuesBucket values; + + values.PutInt("id", 1); + values.PutString("data1", std::string("hello")); + values.PutInt("data2", 10); + values.PutDouble("data3", 1.0); + values.PutBlob("data4", std::vector { 66 }); + store->Insert(id, "test", values); + + values.Clear(); + values.PutInt("id", 2); + values.PutString("data1", std::string("2")); + values.PutInt("data2", -5); + values.PutDouble("data3", 2.5); + values.PutBlob("data4", std::vector {}); + store->Insert(id, "test", values); + + values.Clear(); + values.PutInt("id", 3); + values.PutString("data1", std::string("hello world")); + values.PutInt("data2", 3); + values.PutDouble("data3", 1.8); + values.PutBlob("data4", std::vector {}); + store->Insert(id, "test", values); +} + +/* * + * @tc.name: RdbStore_Delete_001 + * @tc.desc: normal testcase of SqliteSharedResultSet for move + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_001, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int ret = rstSet->GoToRow(1); + EXPECT_EQ(ret, E_OK); + + int rowCnt = -1; + ret = rstSet->GetRowCount(rowCnt); + EXPECT_EQ(rowCnt, 3); + + std::string colName = ""; + rstSet->GetColumnName(1, colName); + EXPECT_EQ(colName, "data1"); + + rstSet->GetColumnName(2, colName); + EXPECT_EQ(colName, "data2"); + + rstSet->GetColumnName(3, colName); + EXPECT_EQ(colName, "data3"); + + rstSet->GetColumnName(4, colName); + EXPECT_EQ(colName, "data4"); + + std::string valueStr = ""; + rstSet->GetString(0, valueStr); + EXPECT_EQ(valueStr, "2"); + + rstSet->GetString(1, valueStr); + EXPECT_EQ(valueStr, "2"); + + int64_t valuelg = 0; + rstSet->GetLong(2, valuelg); + EXPECT_EQ(valuelg, -5); + + double valueDb = 0.0; + rstSet->GetDouble(3, valueDb); + EXPECT_EQ(valueDb, 2.5); + + std::vector blob; + rstSet->GetBlob(4, blob); + int sz = blob.size(); + EXPECT_EQ(sz, 0); + + rstSet->GoTo(1); + rstSet->GetString(0, valueStr); + EXPECT_EQ(valueStr, "3"); + + rstSet->GetString(1, valueStr); + EXPECT_EQ(valueStr, "hello world"); + + rstSet->GetLong(2, valuelg); + EXPECT_EQ(valuelg, 3); + + rstSet->GetDouble(3, valueDb); + EXPECT_EQ(valueDb, 1.8); + + rstSet->GetBlob(4, blob); + sz = blob.size(); + EXPECT_EQ(sz, 0); + + bool isNull = false; + rstSet->IsColumnNull(4, isNull); + EXPECT_EQ(isNull, true); + + ret = -1; + ret = rstSet->GoToPreviousRow(); + EXPECT_EQ(ret, E_OK); + ret = -1; + ret = rstSet->GoToPreviousRow(); + EXPECT_EQ(ret, E_OK); + + rstSet->GetString(0, valueStr); + EXPECT_EQ(valueStr, "1"); + + rstSet->GetString(1, valueStr); + EXPECT_EQ(valueStr, "hello"); + + rstSet->GetLong(2, valuelg); + EXPECT_EQ(valuelg, 10); + + rstSet->GetDouble(3, valueDb); + EXPECT_EQ(valueDb, 1.0); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_002 + * @tc.desc: normal testcase of SqliteSharedResultSet for goToNextRow + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_002, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int pos = -2; + rstSet->GetRowIndex(pos); + EXPECT_EQ(pos, -1); + bool isStart = true; + rstSet->IsStarted(isStart); + EXPECT_EQ(isStart, false); + bool isAtFirstRow = true; + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, false); + bool isEnded = true; + rstSet->IsEnded(isEnded); + EXPECT_EQ(isEnded, false); + + int retN1 = rstSet->GoToNextRow(); + EXPECT_EQ(retN1, E_OK); + rstSet->GetRowIndex(pos); + EXPECT_EQ(pos, 0); + rstSet->IsStarted(isStart); + EXPECT_EQ(isStart, true); + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, true); + isEnded = true; + rstSet->IsEnded(isEnded); + EXPECT_EQ(isEnded, false); + + int retN2 = rstSet->GoToNextRow(); + EXPECT_EQ(retN2, E_OK); + rstSet->GetRowIndex(pos); + EXPECT_EQ(pos, 1); + isStart = false; + rstSet->IsStarted(isStart); + EXPECT_EQ(isStart, true); + isAtFirstRow = true; + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, false); + isEnded = true; + rstSet->IsEnded(isEnded); + EXPECT_EQ(isEnded, false); + + int retN3 = rstSet->GoToNextRow(); + EXPECT_EQ(retN3, E_OK); + rstSet->GetRowIndex(pos); + EXPECT_EQ(pos, 2); + isStart = false; + rstSet->IsStarted(isStart); + EXPECT_EQ(isStart, true); + isAtFirstRow = true; + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, false); + bool isAtLastRow = false; + rstSet->IsAtLastRow(isAtLastRow); + EXPECT_EQ(isAtLastRow, true); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_ERROR); + rstSet->GetRowIndex(pos); + EXPECT_EQ(pos, 3); + isStart = false; + rstSet->IsStarted(isStart); + EXPECT_EQ(isStart, true); + isAtFirstRow = true; + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, false); + isEnded = false; + rstSet->IsEnded(isEnded); + EXPECT_EQ(isEnded, true); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_003 + * @tc.desc: normal testcase of SqliteSharedResultSet for moveFirst + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_003, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + int index = -1; + rstSet->GetRowIndex(index); + EXPECT_EQ(index, 0); + bool isAtFirstRow = false; + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, true); + bool isStd = false; + rstSet->IsStarted(isStd); + EXPECT_EQ(isStd, true); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_OK); + rstSet->GetRowIndex(index); + EXPECT_EQ(index, 1); + isAtFirstRow = true; + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, false); + isStd = false; + rstSet->IsStarted(isStd); + EXPECT_EQ(isStd, true); + + int retGf = rstSet->GoToFirstRow(); + EXPECT_EQ(retGf, E_OK); + rstSet->GetRowIndex(index); + EXPECT_EQ(index, 0); + isAtFirstRow = false; + rstSet->IsAtFirstRow(isAtFirstRow); + EXPECT_EQ(isAtFirstRow, true); + isStd = false; + rstSet->IsStarted(isStd); + EXPECT_EQ(isStd, true); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_004 + * @tc.desc: normal testcase of SqliteSharedResultSet for getInt + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_004, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int64_t valueInt = 0; + int ret = rstSet->GetLong(0, valueInt); + EXPECT_EQ(ret, E_INVALID_STATEMENT); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + rstSet->GetLong(0, valueInt); + EXPECT_EQ(valueInt, 1); + rstSet->GetLong(2, valueInt); + EXPECT_EQ(valueInt, 10); + rstSet->GetLong(3, valueInt); + EXPECT_EQ(valueInt, 1); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_OK); + rstSet->GetLong(0, valueInt); + EXPECT_EQ(valueInt, 2); + valueInt = 0; + rstSet->GetLong(0, valueInt); + EXPECT_EQ(valueInt, 2); + valueInt = 0; + rstSet->GetLong(1, valueInt); + EXPECT_EQ(valueInt, 2); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_005 + * @tc.desc: normal testcase of SqliteSharedResultSet for getString + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ + +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_005, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + std::string valueStr = ""; + int ret1 = rstSet->GetString(0, valueStr); + EXPECT_EQ(ret1, E_INVALID_STATEMENT); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + valueStr = ""; + rstSet->GetString(1, valueStr); + EXPECT_EQ(valueStr, "hello"); + rstSet->GetString(2, valueStr); + EXPECT_EQ(valueStr, "10"); + rstSet->GetString(3, valueStr); + EXPECT_EQ(valueStr, "1"); + + int ret2 = rstSet->GetString(4, valueStr); + EXPECT_EQ(ret2, E_OK); + + valueStr = ""; + int colCnt = 0; + rstSet->GetColumnCount(colCnt); + int ret3 = rstSet->GetString(colCnt, valueStr); + EXPECT_EQ(ret3, E_INVALID_COLUMN_INDEX); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_OK); + rstSet->GetString(0, valueStr); + EXPECT_EQ(valueStr, "2"); + valueStr = ""; + rstSet->GetString(1, valueStr); + EXPECT_EQ(valueStr, "2"); + rstSet->GetString(2, valueStr); + EXPECT_EQ(valueStr, "-5"); + rstSet->GetString(3, valueStr); + EXPECT_EQ(valueStr, "2.5"); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_006 + * @tc.desc: normal testcase of SqliteSharedResultSet for getDouble + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_006, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + double valueDb = 0.0; + int ret = rstSet->GetDouble(0, valueDb); + EXPECT_EQ(ret, E_INVALID_STATEMENT); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + rstSet->GetDouble(0, valueDb); + EXPECT_EQ(valueDb, 1.0); + std::string valueStr = ""; + rstSet->GetString(1, valueStr); + EXPECT_EQ(valueStr, "hello"); + rstSet->GetDouble(2, valueDb); + EXPECT_EQ(valueDb, 10.0); + rstSet->GetDouble(3, valueDb); + EXPECT_EQ(valueDb, 1.0); + + int colCnt = 0; + rstSet->GetColumnCount(colCnt); + int ret1 = rstSet->GetDouble(colCnt, valueDb); + EXPECT_EQ(ret1, E_INVALID_COLUMN_INDEX); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_OK); + rstSet->GetDouble(0, valueDb); + EXPECT_EQ(valueDb, 2.0); + valueDb = 0.0; + rstSet->GetDouble(1, valueDb); + EXPECT_EQ(valueDb, 2.0); + + rstSet->GetDouble(2, valueDb); + EXPECT_EQ(valueDb, -5.0); + rstSet->GetDouble(3, valueDb); + EXPECT_EQ(valueDb, 2.5); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_007 + * @tc.desc: normal testcase of SqliteSharedResultSet for getBlob + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_007, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + + std::vector blobVec; + rstSet->GetBlob(4, blobVec); + EXPECT_EQ(blobVec[0], 66); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_OK); + blobVec.clear(); + rstSet->GetBlob(4, blobVec); + int blobSz = blobVec.size(); + EXPECT_EQ(blobSz, 0); + + int retN1 = rstSet->GoToNextRow(); + EXPECT_EQ(retN1, E_OK); + blobVec.clear(); + rstSet->GetBlob(4, blobVec); + EXPECT_EQ(blobSz, 0); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_008 + * @tc.desc: normal testcase of SqliteSharedResultSet for getColumnTypeForIndex + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ + +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_008, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + ColumnType colType; + int ret = rstSet->GetColumnType(0, colType); + EXPECT_EQ(ret, E_INVALID_STATEMENT); + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + + rstSet->GetColumnType(0, colType); + EXPECT_EQ(colType, ColumnType::TYPE_INTEGER); + + bool isColNull = true; + rstSet->IsColumnNull(0, isColNull); + EXPECT_EQ(isColNull, false); + + rstSet->GetColumnType(1, colType); + EXPECT_EQ(colType, ColumnType::TYPE_STRING); + + isColNull = true; + rstSet->IsColumnNull(0, isColNull); + EXPECT_EQ(isColNull, false); + + rstSet->GetColumnType(2, colType); + EXPECT_EQ(colType, ColumnType::TYPE_INTEGER); + rstSet->GetColumnType(3, colType); + EXPECT_EQ(colType, ColumnType::TYPE_FLOAT); + rstSet->GetColumnType(4, colType); + EXPECT_EQ(colType, ColumnType::TYPE_BLOB); + + int colCnt = 0; + rstSet->GetColumnCount(colCnt); + int ret1 = rstSet->GetColumnType(colCnt, colType); + EXPECT_EQ(ret1, E_INVALID_COLUMN_INDEX); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_009 + * @tc.desc: normal testcase of SqliteSharedResultSet for getColumnIndexForName + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_009, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int colIndex = 0; + rstSet->GetColumnIndex("data1", colIndex); + EXPECT_EQ(colIndex, 1); + + rstSet->GetColumnIndex("data2", colIndex); + EXPECT_EQ(colIndex, 2); + + rstSet->GetColumnIndex("data3", colIndex); + EXPECT_EQ(colIndex, 3); + + rstSet->GetColumnIndex("data4", colIndex); + EXPECT_EQ(colIndex, 4); + + rstSet->GetColumnIndex("datax", colIndex); + EXPECT_EQ(colIndex, -1); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_010 + * @tc.desc: normal testcase of SqliteSharedResultSet for getColumnNameForIndex + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_010, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + std::vector allColNamesVec; + rstSet->GetAllColumnNames(allColNamesVec); + + std::string colName = ""; + rstSet->GetColumnName(1, colName); + EXPECT_EQ(colName, "data1"); + EXPECT_EQ(allColNamesVec[1], colName); + + rstSet->GetColumnName(2, colName); + EXPECT_EQ(colName, "data2"); + EXPECT_EQ(allColNamesVec[2], colName); + + rstSet->GetColumnName(3, colName); + EXPECT_EQ(colName, "data3"); + rstSet->GetColumnName(4, colName); + EXPECT_EQ(colName, "data4"); + + int colCnt = 0; + rstSet->GetColumnCount(colCnt); + int ret = rstSet->GetColumnName(colCnt, colName); + EXPECT_EQ(ret, E_INVALID_COLUMN_INDEX); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_011 + * @tc.desc: normal testcase of SqliteSharedResultSet + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_011, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + + bool isAtFrtRow = false; + rstSet->IsAtFirstRow(isAtFrtRow); + EXPECT_EQ(isAtFrtRow, true); + + bool isStarted = false; + rstSet->IsStarted(isStarted); + EXPECT_EQ(isStarted, true); + + int64_t valueInt = 0; + rstSet->GetLong(2, valueInt); + EXPECT_EQ(valueInt, 10); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_012 + * @tc.desc: normal testcase of SqliteSharedResultSet for getLong + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_012, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int64_t valueInt = 0; + int ret = rstSet->GetLong(0, valueInt); + EXPECT_EQ(ret, E_INVALID_STATEMENT); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + rstSet->GetLong(0, valueInt); + EXPECT_EQ(valueInt, 1.0); + std::string valueStr = ""; + rstSet->GetString(1, valueStr); + EXPECT_EQ(valueStr, "hello"); + rstSet->GetLong(2, valueInt); + EXPECT_EQ(valueInt, 10.0); + rstSet->GetLong(3, valueInt); + EXPECT_EQ(valueInt, 1.0); + + int colCnt = 0; + rstSet->GetColumnCount(colCnt); + int ret1 = rstSet->GetLong(colCnt, valueInt); + EXPECT_EQ(ret1, E_INVALID_COLUMN_INDEX); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_OK); + rstSet->GetLong(0, valueInt); + EXPECT_EQ(valueInt, 2.0); + valueInt = 0; + rstSet->GetLong(1, valueInt); + EXPECT_EQ(valueInt, 2.0); + rstSet->GetLong(2, valueInt); + EXPECT_EQ(valueInt, -5.0); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_013 + * @tc.desc: normal testcase of SqliteSharedResultSet for fillBlock + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_013, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); + bool isBk = pSqlSharedRstSet->HasBlock(); + EXPECT_EQ(isBk, true); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} +/* * + * @tc.name: Sqlite_Shared_Result_Set_014 + * @tc.desc: normal testcase of SqliteSharedResultSet for getBlock + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_014, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); + bool isBk = pSqlSharedRstSet->HasBlock(); + EXPECT_EQ(isBk, true); + + int retF = rstSet->GoToFirstRow(); + EXPECT_EQ(retF, E_OK); + OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); + EXPECT_NE(pBk, nullptr); + + std::string path = RdbSqliteSharedResultSetTest::store->GetPath(); + std::string path1 = pBk->Name(); + + EXPECT_EQ(path, "/data/test/shared_test.db"); + EXPECT_EQ(path1, "/data/test/shared_test.db"); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} +/* * + * @tc.name: Sqlite_Shared_Result_Set_015 + * @tc.desc: normal testcase of SqliteSharedResultSet for setBlock + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_015, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); + bool isBk = pSqlSharedRstSet->HasBlock(); + EXPECT_EQ(isBk, true); + + int retN = rstSet->GoToNextRow(); + EXPECT_EQ(retN, E_OK); + + std::string path = RdbSqliteSharedResultSetTest::store->GetPath(); + OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); + std::string path1 = pBk->Name(); + + EXPECT_EQ(path, "/data/test/shared_test.db"); + EXPECT_EQ(path1, "/data/test/shared_test.db"); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_016 + * @tc.desc: normal testcase of SqliteSharedResultSet for setFillWindowForwardOnly + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_016, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); + bool isBk = pSqlSharedRstSet->HasBlock(); + EXPECT_EQ(isBk, true); + + pSqlSharedRstSet->PickFillBlockStartPosition(0, 0); + pSqlSharedRstSet->SetFillBlockForwardOnly(true); + pSqlSharedRstSet->GoToFirstRow(); + + OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); + EXPECT_NE(pBk, nullptr); + std::string path = RdbSqliteSharedResultSetTest::store->GetPath(); + std::string path1 = pBk->Name(); + + EXPECT_EQ(path, "/data/test/shared_test.db"); + EXPECT_EQ(path1, "/data/test/shared_test.db"); + + int rowCnt = 0; + pSqlSharedRstSet->GetRowCount(rowCnt); + int rowCntBk = pBk->GetRowNum(); + + EXPECT_EQ(rowCnt, rowCntBk); + + rstSet->Close(); + bool isClosedFlag = rstSet->IsClosed(); + EXPECT_EQ(isClosedFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_017 + * @tc.desc: normal testcase of SqliteSharedResultSet for setExtensions and getExtensions + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_017, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr rstSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(rstSet, nullptr); + + int rowCnt = 0; + rstSet->GetRowCount(rowCnt); + EXPECT_EQ(rowCnt, 3); + int ret = rstSet->GoToLastRow(); + EXPECT_EQ(ret, E_OK); +} diff --git a/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp index cd9a7b8c4f0cdbc5a165c8794ada7f65dac6ba61..b8a81a5e15da0ec909af4d0d5c0beb6387e9c922 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_config_test.cpp @@ -225,7 +225,7 @@ HWTEST_F(RdbStoreConfigTest, RdbStoreConfig_005, TestSize.Level1) const std::string dbPath = RDB_TEST_PATH + "config_test.db"; RdbStoreConfig config(dbPath, StorageMode::MODE_DISK, false); std::string journalMode = config.GetJournalMode(); - EXPECT_EQ(journalMode, ""); + EXPECT_EQ(journalMode, "WAL"); ConfigTestOpenCallback helper; int errCode = E_OK; std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); @@ -259,7 +259,7 @@ HWTEST_F(RdbStoreConfigTest, RdbStoreConfig_006, TestSize.Level1) std::string currentMode; int ret = store->ExecuteAndGetString(currentMode, "PRAGMA journal_mode"); EXPECT_EQ(ret, E_OK); - EXPECT_EQ(currentMode, "delete"); + EXPECT_EQ(currentMode, "wal"); } /** @@ -386,3 +386,94 @@ HWTEST_F(RdbStoreConfigTest, RdbStoreConfig_011, TestSize.Level1) EXPECT_EQ(ret, E_OK); EXPECT_EQ(currentMode, "off"); } + +/** + * @tc.name: RdbStoreConfig_012 + * @tc.desc: test RdbStoreConfig SetReadPermission/GetReadPermission/SetWritePermission/GetWritePermission + * @tc.type: FUNC + * @tc.require: AR000CU2BO + * @tc.author: chenxi + */ +HWTEST_F(RdbStoreConfigTest, RdbStoreConfig_012, TestSize.Level1) +{ + const std::string dbPath = RDB_TEST_PATH + "config_test.db"; + RdbStoreConfig config(dbPath); + + std::string readPermission = "readPermission"; + config.SetReadPermission(readPermission); + std::string getReadPermission = config.GetReadPermission(); + EXPECT_EQ(getReadPermission, readPermission); + + std::string writePermission = "writePermission"; + config.SetWritePermission(writePermission); + std::string getWritePermission = config.GetWritePermission(); + EXPECT_EQ(getWritePermission, writePermission); + + std::string uri = "uri"; + config.SetUri(uri); + std::string getUri = config.GetUri(); + EXPECT_EQ(getUri, uri); +} + +/** + * @tc.name: RdbStoreConfig_013 + * @tc.desc: test RdbStoreConfig interfaces: SetSecurityLevel/GetSecurityLevel + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(RdbStoreConfigTest, RdbStoreConfig_013, TestSize.Level1) +{ + const std::string dbPath = RDB_TEST_PATH + "config_test.db"; + RdbStoreConfig config(dbPath); + + config.SetSecurityLevel(SecurityLevel::S2); + SecurityLevel retSecurityLevel = config.GetSecurityLevel(); + EXPECT_EQ(SecurityLevel::S2, retSecurityLevel); + + ConfigTestOpenCallback helper; + int errCode = E_ERROR; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(store, nullptr); + + RdbHelper::DeleteRdbStore(dbPath); + + config.SetSecurityLevel(SecurityLevel::LAST); + retSecurityLevel = config.GetSecurityLevel(); + EXPECT_EQ(SecurityLevel::LAST, retSecurityLevel); + store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(store, nullptr); +} + +/** + * @tc.name: RdbStoreConfig_014 + * @tc.desc: test RdbStoreConfig interfaces: SetCreateNecessary/IsCreateNecessary + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(RdbStoreConfigTest, RdbStoreConfig_014, TestSize.Level1) +{ + const std::string dbPath = RDB_TEST_PATH + "config_test.db"; + RdbStoreConfig config(dbPath); + + bool createNecessary = true; + config.SetCreateNecessary(createNecessary); + bool retCreateNecessary = config.IsCreateNecessary(); + EXPECT_EQ(createNecessary, retCreateNecessary); + + ConfigTestOpenCallback helper; + int errCode = E_ERROR; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(store, nullptr); + store = nullptr; + RdbHelper::DeleteRdbStore(dbPath); + + createNecessary = false; + config.SetCreateNecessary(createNecessary); + retCreateNecessary = config.IsCreateNecessary(); + EXPECT_EQ(createNecessary, retCreateNecessary); + + store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_EQ(store, nullptr); +} diff --git a/relational_store/test/native/rdb/unittest/rdb_store_interface_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_interface_test.cpp index 01a7fd220daefc15cee33bb57e3bb93b8f55e3a7..d9e7efcfae2b286ff3d719b0f810d77385e32fee 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_interface_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_interface_test.cpp @@ -249,7 +249,7 @@ HWTEST_F(RdbStoreInterfaceTest, ValuesBucket_002, TestSize.Level1) ret = resultSet->GetColumnIndex("name", columnIndex); EXPECT_EQ(ret, E_OK); ret = resultSet->GetString(columnIndex, strVal); - EXPECT_EQ(ret, E_ERROR); + EXPECT_EQ(ret, E_OK); resultSet->Close(); resultSet = nullptr; diff --git a/test/include/CMakeLists.txt b/test/include/CMakeLists.txt index 102e131319db74a703ef4958461b5cc02c40ec3b..7ef55ee519c42a97e46b0572720342cc62d867fd 100644 --- a/test/include/CMakeLists.txt +++ b/test/include/CMakeLists.txt @@ -1,4 +1,6 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../data_object/interfaces/innerkits) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/adaptor) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../data_object/frameworks/innerkitsimpl/include/common) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/interfaces/innerkits/distributeddata/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/frameworks/common) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/frameworks/innerkitsimpl/kvdb/include) @@ -21,6 +23,7 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/dist include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/service/matrix/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/service/kvdb) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/service/rdb) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/service/crypto/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/framework/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/app/src/) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/libs/distributeddb/include)