diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn b/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn index eaf6c5dd59722f830222eb0340bdfdc4c6542f2f..a79ea560bb2d1572cc9c95339e9db8e36af4bcc7 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn +++ b/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn @@ -43,6 +43,7 @@ common_external_deps = [ "bundle_framework:appexecfwk_core", "c_utils:utils", "device_manager:devicemanagersdk", + "dmsfwk:distributed_sdk", "dsoftbus:softbus_client", "ffmpeg:libohosffmpeg", "hilog:libhilog", @@ -197,7 +198,6 @@ ohos_unittest("DistributedObjectStoreImplTest") { sources = [ "${data_object_base_path}/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp", - "${data_object_base_path}/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp", "${data_object_base_path}/frameworks/innerkitsimpl/test/unittest/src/distributed_object_store_impl_test.cpp", ] @@ -211,6 +211,7 @@ ohos_unittest("DistributedObjectStoreImplTest") { "private = public", "protected = public", ] + deps = [ "${data_object_base_path}/interfaces/innerkits:distributeddataobject_static" ] } ohos_unittest("FlatObjectStoreTest") { diff --git a/datamgr_service/services/distributeddataservice/adapter/BUILD.gn b/datamgr_service/services/distributeddataservice/adapter/BUILD.gn index 80c6b4594486d7131bee6316607960501cf5da8e..8797b303e2a65cc4ebc296e68ea144b3228c3dac 100644 --- a/datamgr_service/services/distributeddataservice/adapter/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/adapter/BUILD.gn @@ -18,8 +18,11 @@ config("distributeddata_adapter_private_config") { visibility = [ ":*" ] include_dirs = [] - cflags = [ "-Wno-multichar" ] - + cflags = [ + "-Werror", + "-Wno-multichar", + "-D_LIBCPP_HAS_COND_CLOCKWAIT", + ] cflags_cc = [ "-fvisibility=hidden" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -51,7 +54,6 @@ ohos_shared_library("distributeddata_adapter") { ubsan = true } sources = [] - cflags = [ "-D_LIBCPP_HAS_COND_CLOCKWAIT" ] configs = [ ":distributeddata_adapter_private_config" ] deps = [ "${data_service_path}/adapter/account:distributeddata_account_static", diff --git a/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp b/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp index 3a25ea0924aa05c453a7e7ee66e8e6ec5f1e28ab..9916508a896e446a4bc67785d478dd38dfcb5e24 100644 --- a/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp +++ b/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp @@ -26,26 +26,26 @@ using namespace OHOS::AAFwk; using namespace OHOS::DistributedData; EventSubscriber::EventSubscriber(const CommonEventSubscribeInfo &info) : CommonEventSubscriber(info) {} +static inline const std::map STATUS = { + { CommonEventSupport::COMMON_EVENT_USER_REMOVED, AccountStatus::DEVICE_ACCOUNT_DELETE }, + { CommonEventSupport::COMMON_EVENT_USER_SWITCHED, AccountStatus::DEVICE_ACCOUNT_SWITCHED }, + { CommonEventSupport::COMMON_EVENT_USER_UNLOCKED, AccountStatus::DEVICE_ACCOUNT_UNLOCKED }, + { CommonEventSupport::COMMON_EVENT_USER_STOPPING, AccountStatus::DEVICE_ACCOUNT_STOPPING }, + { CommonEventSupport::COMMON_EVENT_USER_STOPPED, AccountStatus::DEVICE_ACCOUNT_STOPPED } }; void EventSubscriber::OnReceiveEvent(const CommonEventData &event) { const auto want = event.GetWant(); - AccountEventInfo accountEventInfo {}; + AccountEventInfo accountEventInfo{}; std::string action = want.GetAction(); ZLOGI("Want Action is %{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { - accountEventInfo.status = AccountStatus::DEVICE_ACCOUNT_DELETE; - accountEventInfo.userId = std::to_string(event.GetCode()); - } else if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - accountEventInfo.status = AccountStatus::DEVICE_ACCOUNT_SWITCHED; - accountEventInfo.userId = std::to_string(event.GetCode()); - } else if (action == CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) { - accountEventInfo.status = AccountStatus::DEVICE_ACCOUNT_UNLOCKED; - accountEventInfo.userId = std::to_string(event.GetCode()); - } else { + auto it = STATUS.find(action); + if (it == STATUS.end()) { return; } + accountEventInfo.userId = std::to_string(event.GetCode()); + accountEventInfo.status = it->second; eventCallback_(accountEventInfo); } diff --git a/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_normal_impl.cpp b/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_normal_impl.cpp index 5644959a4ada92ab845b0a83d603d6ae8dc8cdcd..3edb00d67883d3d2c401dbcfe3601f9ed75aaf6e 100644 --- a/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_normal_impl.cpp +++ b/datamgr_service/services/distributeddataservice/adapter/account/src/account_delegate_normal_impl.cpp @@ -127,15 +127,13 @@ void AccountDelegateNormalImpl::UpdateUserStatus(const AccountEventInfo& account { uint32_t status = static_cast(account.status); switch (status) { + case static_cast(AccountStatus::DEVICE_ACCOUNT_STOPPING): case static_cast(AccountStatus::DEVICE_ACCOUNT_DELETE): userStatus_.Erase(atoi(account.userId.c_str())); break; case static_cast(AccountStatus::DEVICE_ACCOUNT_UNLOCKED): userStatus_.InsertOrAssign(atoi(account.userId.c_str()), true); break; - case static_cast(AccountStatus::DEVICE_ACCOUNT_STOPPING): - userStatus_.Erase(atoi(account.userId.c_str())); - break; case static_cast(AccountStatus::DEVICE_ACCOUNT_STOPPED): userStatus_.InsertOrAssign(atoi(account.userId.c_str()), false); break; @@ -209,7 +207,7 @@ void AccountDelegateNormalImpl::BindExecutor(std::shared_ptr execu std::string AccountDelegateNormalImpl::GetUnencryptedAccountId(int32_t userId) const { AccountSA::OhosAccountInfo info; - auto ret = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfoByUserId(userId, info); + auto ret = AccountSA::OhosAccountKits::GetInstance().GetOsAccountDistributedInfo(userId, info); if (ret != ERR_OK) { ZLOGE("GetUnencryptedAccountId failed: %{public}d", ret); return ""; diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/datamgr_service/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index 677701c40ff879baf5538bcb30e09ecd6c63af62..9547e7ff056cac98bd73b15e92215fef8d7e6e79 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -80,9 +80,7 @@ void DataMgrDmStateCall::OnDeviceReady(const DmDeviceInfo &info) class DataMgrDmInitCall final : public DistributedHardware::DmInitCallback { public: explicit DataMgrDmInitCall(DeviceManagerAdapter &dmAdapter, std::shared_ptr executors) - : dmAdapter_(dmAdapter), executors_(executors) - { - } + : dmAdapter_(dmAdapter), executors_(executors) {} void OnRemoteDied() override; private: @@ -164,8 +162,8 @@ struct DeviceExtraInfo final : public Serializable { int32_t OS_TYPE = OH_OS_TYPE; - DeviceExtraInfo(){}; - ~DeviceExtraInfo(){}; + DeviceExtraInfo() {}; + ~DeviceExtraInfo() {}; bool Marshal(json &node) const override { return SetValue(node[GET_NAME(OS_TYPE)], OS_TYPE); @@ -383,7 +381,7 @@ bool DeviceManagerAdapter::GetDeviceInfo(const DmDeviceInfo &dmInfo, DeviceInfo } if (uuid == CLOUD_DEVICE_UUID) { dvInfo = { uuid, udid, networkId, std::string(dmInfo.deviceName), dmInfo.deviceTypeId, OH_OS_TYPE, - static_cast(dmInfo.authForm) }; + static_cast(dmInfo.authForm)}; return true; } DeviceExtraInfo deviceExtraInfo; @@ -392,7 +390,7 @@ bool DeviceManagerAdapter::GetDeviceInfo(const DmDeviceInfo &dmInfo, DeviceInfo return false; } dvInfo = { uuid, udid, networkId, std::string(dmInfo.deviceName), dmInfo.deviceTypeId, deviceExtraInfo.OS_TYPE, - static_cast(dmInfo.authForm) }; + static_cast(dmInfo.authForm)}; return true; } @@ -452,8 +450,9 @@ std::vector DeviceManagerAdapter::GetRemoteDevices() ZLOGE("Unmarshall failed, deviceExtraInfo:%{public}s", dmInfo.extraData.c_str()); continue; } - DeviceInfo dvInfo = { std::move(uuid), std::move(udid), std::move(networkId), std::string(dmInfo.deviceName), - dmInfo.deviceTypeId, deviceExtraInfo.OS_TYPE, static_cast(dmInfo.authForm) }; + DeviceInfo dvInfo = { std::move(uuid), std::move(udid), std::move(networkId), + std::string(dmInfo.deviceName), dmInfo.deviceTypeId, deviceExtraInfo.OS_TYPE, + static_cast(dmInfo.authForm) }; dvInfos.emplace_back(std::move(dvInfo)); } return dvInfos; @@ -470,7 +469,7 @@ std::vector DeviceManagerAdapter::GetOnlineDevices() return devices; } -bool DeviceManagerAdapter::IsDeviceReady(const std::string &id) +bool DeviceManagerAdapter::IsDeviceReady(const std::string& id) { auto it = readyDevices_.Find(id); return (it.first && it.second.first == DeviceState::DEVICE_ONREADY); diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h b/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h index 5e70c3013cc409af2cdbcf805736dbdcb6c8153b..c4fa5324608816a75ebf590085d1d8c579136642 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h @@ -65,7 +65,7 @@ public: void NotifyDataListeners(const uint8_t *data, int size, const std::string &deviceId, const PipeInfo &pipeInfo); - std::string OnClientShutdown(int32_t socket); + std::string OnClientShutdown(int32_t socket, bool isForce = true); void OnBind(int32_t socket, PeerSocketInfo info); @@ -87,12 +87,10 @@ private: using Time = std::chrono::steady_clock::time_point; using Duration = std::chrono::steady_clock::duration; using Task = ExecutorPool::Task; - std::string DelConnect(int32_t socket); + std::string DelConnect(int32_t socket, bool isForce); void StartCloseSessionTask(const std::string &deviceId); Task GetCloseSessionTask(); bool CloseSession(const std::string &networkId); - void Reuse(const PipeInfo &pipeInfo, const DeviceId &deviceId, - uint32_t qosType, std::shared_ptr &conn); void GetExpireTime(std::shared_ptr &conn); std::pair OpenConnect(const std::shared_ptr &conn, const DeviceId &deviceId); static constexpr const char *PKG_NAME = "distributeddata-default"; diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index 73d1bbe1c0b66cbd1655b371b12a043cf835654a..7246a043b49525f9c453a4015e6e53892328efe8 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -50,20 +50,21 @@ public: static void OnClientShutdown(int32_t socket, ShutdownReason reason); static void OnClientBytesReceived(int32_t socket, const void *data, uint32_t dataLen); + static void OnClientSocketChanged(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount); static void OnServerBind(int32_t socket, PeerSocketInfo info); static void OnServerShutdown(int32_t socket, ShutdownReason reason); static void OnServerBytesReceived(int32_t socket, const void *data, uint32_t dataLen); -public: +private: // notify all listeners when received message static void NotifyDataListeners(const uint8_t *data, const int size, const std::string &deviceId, const PipeInfo &pipeInfo); static std::string GetPipeId(const std::string &name); -private: static SoftBusAdapter *softBusAdapter_; }; + SoftBusAdapter *AppDataListenerWrap::softBusAdapter_; std::shared_ptr SoftBusAdapter::instance_; @@ -95,6 +96,7 @@ SoftBusAdapter::SoftBusAdapter() clientListener_.OnShutdown = AppDataListenerWrap::OnClientShutdown; clientListener_.OnBytes = AppDataListenerWrap::OnClientBytesReceived; clientListener_.OnMessage = AppDataListenerWrap::OnClientBytesReceived; + clientListener_.OnQos = AppDataListenerWrap::OnClientSocketChanged; serverListener_.OnBind = AppDataListenerWrap::OnServerBind; serverListener_.OnShutdown = AppDataListenerWrap::OnServerShutdown; @@ -166,18 +168,6 @@ Status SoftBusAdapter::StopWatchDataChange(__attribute__((unused)) const AppData return Status::ERROR; } -void SoftBusAdapter::Reuse(const PipeInfo &pipeInfo, const DeviceId &deviceId, - uint32_t qosType, std::shared_ptr &conn) -{ - std::vector> connects; - auto connect = std::make_shared(pipeInfo, deviceId, qosType); - connect->isReuse = true; - connects.emplace_back(connect); - conn = connect; - connects_.Insert(deviceId.deviceId, connects); - ZLOGI("reuse connect:%{public}s", KvStoreUtils::ToBeAnonymous(deviceId.deviceId).c_str()); -} - void SoftBusAdapter::GetExpireTime(std::shared_ptr &conn) { Time now = std::chrono::steady_clock::now(); @@ -195,28 +185,19 @@ std::pair SoftBusAdapter::SendData(const PipeInfo &pipeInfo, co std::shared_ptr conn; bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId.deviceId); uint32_t qosType = isOHOSType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; - bool isReuse = false; - connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, isOHOSType, &isReuse](const auto &key, + connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, isOHOSType](const auto &key, std::vector> &connects) -> bool { for (auto &connect : connects) { - if (connect->GetQoSType() != qosType) { - continue; - } - if (!isOHOSType && connect->needRemove) { - isReuse = true; - return false; + if (connect->GetQoSType() == qosType) { + conn = connect; + return true; } - conn = connect; - return true; } auto connect = std::make_shared(pipeInfo, deviceId, qosType); connects.emplace_back(connect); conn = connect; return true; }); - if (!isOHOSType && isReuse) { - Reuse(pipeInfo, deviceId, qosType, conn); - } if (conn == nullptr) { return std::make_pair(Status::ERROR, 0); } @@ -371,11 +352,14 @@ uint32_t SoftBusAdapter::GetTimeout(const DeviceId &deviceId) return interval; } -std::string SoftBusAdapter::DelConnect(int32_t socket) +std::string SoftBusAdapter::DelConnect(int32_t socket, bool isForce) { std::string name; std::set closedConnect; - connects_.EraseIf([socket, &name, &closedConnect](const auto &deviceId, auto &connects) -> bool { + connects_.EraseIf([socket, isForce, &name, &closedConnect](const auto &deviceId, auto &connects) -> bool { + if (!isForce && DmAdapter::GetInstance().IsOHOSType(deviceId)) { + return false; + } for (auto iter = connects.begin(); iter != connects.end();) { if (*iter != nullptr && **iter == socket) { name += deviceId; @@ -398,9 +382,9 @@ std::string SoftBusAdapter::DelConnect(int32_t socket) return name; } -std::string SoftBusAdapter::OnClientShutdown(int32_t socket) +std::string SoftBusAdapter::OnClientShutdown(int32_t socket, bool isForce) { - return DelConnect(socket); + return DelConnect(socket, isForce); } bool SoftBusAdapter::IsSameStartedOnPeer(const struct PipeInfo &pipeInfo, @@ -506,6 +490,14 @@ void AppDataListenerWrap::OnClientShutdown(int32_t socket, ShutdownReason reason void AppDataListenerWrap::OnClientBytesReceived(int32_t socket, const void *data, uint32_t dataLen) {} +void AppDataListenerWrap::OnClientSocketChanged(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) +{ + if (eventId == QoSEvent::QOS_SATISFIED && qos != nullptr && qos[0].qos == QOS_TYPE_MIN_BW && qosCount == 1) { + auto name = softBusAdapter_->OnClientShutdown(socket, false); + ZLOGI("[SocketChanged] socket:%{public}d, name:%{public}s", socket, KvStoreUtils::ToBeAnonymous(name).c_str()); + } +} + void AppDataListenerWrap::OnServerBind(int32_t socket, PeerSocketInfo info) { softBusAdapter_->OnBind(socket, info); @@ -573,18 +565,6 @@ void SoftBusAdapter::OnBind(int32_t socket, PeerSocketInfo info) socketInfo.networkId = info.networkId; socketInfo.pkgName = info.pkgName; peerSocketInfos_.Insert(socket, socketInfo); - if (!DmAdapter::GetInstance().IsOHOSType(info.networkId)) { - auto uuid = DmAdapter::GetInstance().ToUUID(info.networkId); - auto connects = connects_.Find(uuid); - if (!connects.first) { - return; - } - for (auto &conn : connects.second) { - if (!conn->isReuse) { - conn->needRemove = true; - } - } - } } void SoftBusAdapter::OnServerShutdown(int32_t socket) diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_client.h index 1547e32d852df91aafc497ed239800e8907bbaeb..6726a29ecdc82a0c5014508c3bc0cb9c3c156545 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -49,8 +49,6 @@ public: uint32_t GetQoSType() const; void UpdateExpireTime(); int32_t GetSoftBusError(); - bool needRemove = false; - bool isReuse = false; private: int32_t Open(int32_t socket, const QosTV qos[], const ISocketListener *listener); diff --git a/datamgr_service/services/distributeddataservice/app/BUILD.gn b/datamgr_service/services/distributeddataservice/app/BUILD.gn index 61a689385968efa39441c94daf08ac873263efd6..42ad60e3f99365b87a33ebbb0d50b83bce07da0f 100644 --- a/datamgr_service/services/distributeddataservice/app/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/BUILD.gn @@ -71,6 +71,7 @@ config("module_private_config") { ] cflags = [ + "-Werror", "-Wno-multichar", "-D_LIBCPP_HAS_COND_CLOCKWAIT", ] diff --git a/datamgr_service/services/distributeddataservice/app/distributed_data.cfg b/datamgr_service/services/distributeddataservice/app/distributed_data.cfg index e8a9f783a837f38f28fc32ae82ac1ba3332c5c25..65e8ac880c053d0127039baf03f077fdf5034fd0 100644 --- a/datamgr_service/services/distributeddataservice/app/distributed_data.cfg +++ b/datamgr_service/services/distributeddataservice/app/distributed_data.cfg @@ -31,6 +31,7 @@ "sandbox" : 0, "permission" : [ "ohos.permission.DISTRIBUTED_DATASYNC", + "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS", "ohos.permission.MANAGE_LOCAL_ACCOUNTS", "ohos.permission.ACCESS_SERVICE_DM", "ohos.permission.PROXY_AUTHORIZATION_URI", diff --git a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp index f543039d3fddb24afdb2d4640e4de465577eb84f..c33d5a66ee5dc808c104630d81c5aae30f02beda 100644 --- a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -544,6 +544,25 @@ void KvStoreDataService::NotifyAccountEvent(const AccountEventInfo &eventInfo) value->OnUserChange(uint32_t(eventInfo.status), eventInfo.userId, eventInfo.harmonyAccountId); return false; }); + switch (eventInfo.status) { + case AccountStatus::DEVICE_ACCOUNT_SWITCHED: + case AccountStatus::DEVICE_ACCOUNT_DELETE: + case AccountStatus::DEVICE_ACCOUNT_STOPPED: { + std::vector users; + AccountDelegate::GetInstance()->QueryUsers(users); + std::set userIds(users.begin(), users.end()); + AutoCache::GetInstance().CloseStore([&userIds](const StoreMetaData &meta) { + return userIds.count(atoi(meta.user.c_str())) == 0; + }); + break; + } + case AccountStatus::DEVICE_ACCOUNT_STOPPING: + AutoCache::GetInstance().CloseStore([&eventInfo](const StoreMetaData &meta) { + return meta.user == eventInfo.userId; + }); + default: + break; + } } void KvStoreDataService::InitSecurityAdapter(std::shared_ptr executors) diff --git a/datamgr_service/services/distributeddataservice/app/test/BUILD.gn b/datamgr_service/services/distributeddataservice/app/test/BUILD.gn index 178d7ecd3cee3ff7073f339cd5cb1e03a49d5fc6..5aa0b09eb4a5c4eba5746f7ba4962602731664f1 100644 --- a/datamgr_service/services/distributeddataservice/app/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/test/BUILD.gn @@ -61,6 +61,11 @@ config("module_private_config") { include_dirs += [ "//base/powermgr/power_manager/interfaces/innerkits/native/include" ] } + cflags = [ + "-Werror", + "-Dprivate=public", + "-Dprotected=public", + ] ldflags = [ "-Wl,--whole-archive" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -68,21 +73,21 @@ config("module_private_config") { ohos_unittest("KvStoreDataServiceTest") { module_out_path = module_output_path sources = [ + "${data_service_path}/app/src/db_info_handle_impl.cpp", + "${data_service_path}/app/src/feature_stub_impl.cpp", + "${data_service_path}/app/src/kvstore_account_observer.cpp", + "${data_service_path}/app/src/kvstore_data_service.cpp", + "${data_service_path}/app/src/kvstore_data_service_stub.cpp", + "${data_service_path}/app/src/kvstore_device_listener.cpp", + "${data_service_path}/app/src/kvstore_meta_manager.cpp", + "${data_service_path}/app/src/security/security.cpp", + "${data_service_path}/app/src/security/sensitive.cpp", + "${data_service_path}/app/src/session_manager/route_head_handler_impl.cpp", + "${data_service_path}/app/src/session_manager/session_manager.cpp", + "${data_service_path}/app/src/session_manager/upgrade_manager.cpp", + "${data_service_path}/app/src/task_manager.cpp", + "${data_service_path}/app/test/unittest/kvstore_data_service_test.cpp", "${data_service_path}/service/common/xcollie.cpp", - "../src/db_info_handle_impl.cpp", - "../src/feature_stub_impl.cpp", - "../src/kvstore_account_observer.cpp", - "../src/kvstore_data_service.cpp", - "../src/kvstore_data_service_stub.cpp", - "../src/kvstore_device_listener.cpp", - "../src/kvstore_meta_manager.cpp", - "../src/security/security.cpp", - "../src/security/sensitive.cpp", - "../src/session_manager/route_head_handler_impl.cpp", - "../src/session_manager/session_manager.cpp", - "../src/session_manager/upgrade_manager.cpp", - "../src/task_manager.cpp", - "unittest/kvstore_data_service_test.cpp", ] configs = [ ":module_private_config" ] @@ -99,6 +104,8 @@ ohos_unittest("KvStoreDataServiceTest") { "hitrace:hitrace_meter", "hitrace:libhitracechain", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", "memmgr:memmgrclient", "safwk:system_ability_fwk", "samgr:samgr_proxy", @@ -111,11 +118,6 @@ ohos_unittest("KvStoreDataServiceTest") { ] } - cflags = [ - "-Dprivate=public", - "-Dprotected=public", - ] - deps = [ "${data_service_path}/adapter:distributeddata_adapter", "${data_service_path}/adapter/broadcaster:distributeddata_broadcaster_static", @@ -125,9 +127,6 @@ ohos_unittest("KvStoreDataServiceTest") { "${data_service_path}/app/src/installer:distributeddata_installer_static", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", - "${kv_store_path}/frameworks/libs/distributeddb:distributeddb", - "${kv_store_path}/interfaces/innerkits/distributeddata:distributeddata_inner", - "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//third_party/googletest:gtest_main", ] part_name = "datamgr_service" diff --git a/datamgr_service/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp b/datamgr_service/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp index 4b3fe063df71bff9c72ef08da9aea1f56726dd90..f9aa98e7c1f949f5069d4bd390aa2dd453e8dfcc 100644 --- a/datamgr_service/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp +++ b/datamgr_service/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp @@ -13,17 +13,28 @@ * limitations under the License. */ +#include "auth_delegate.h" +#include "bootstrap.h" +#include "executor_pool.h" #include +#include "metadata/store_meta_data.h" +#include #include "kvstore_client_death_observer.h" #include "bootstrap.h" #include "gtest/gtest.h" #include "kvstore_data_service.h" +#include "serializable/serializable.h" +#include "system_ability.h" +#include "system_ability_definition.h" +#include "upgrade_manager.h" using namespace testing::ext; +using namespace OHOS; using namespace OHOS::DistributedKv; using namespace OHOS::DistributedData; -using namespace OHOS; +using StoreMetaData = DistributedData::StoreMetaData; +namespace OHOS::Test { class KvStoreDataServiceTest : public testing::Test { public: static void SetUpTestCase(void); @@ -48,6 +59,26 @@ void KvStoreDataServiceTest::SetUp(void) void KvStoreDataServiceTest::TearDown(void) {} +class UpgradeManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void UpgradeManagerTest::SetUpTestCase(void) +{} + +void UpgradeManagerTest::TearDownTestCase(void) +{} + +void UpgradeManagerTest::SetUp(void) +{} + +void UpgradeManagerTest::TearDown(void) +{} + /** * @tc.name: RegisterClientDeathObserver001 * @tc.desc: register client death observer @@ -112,6 +143,7 @@ HWTEST_F(KvStoreDataServiceTest, Dump001, TestSize.Level1) const std::u16string argstest2 = u"OHOS.DistributedKv.IKvStoreDataService2"; args.emplace_back(argstest1); args.emplace_back(argstest2); + kvStoreDataServiceTest.OnDump(); int32_t status = kvStoreDataServiceTest.Dump(1, args); EXPECT_EQ(status, SUCCESS); } @@ -178,3 +210,425 @@ HWTEST_F(KvStoreDataServiceTest, AppExit001, TestSize.Level1) Status status = kvStoreDataServiceTest.AppExit(uid, pid, token, appId); EXPECT_EQ(status, SUCCESS); } + +/** +* @tc.name: OnRemoveSystemAbility001 +* @tc.desc: test OnRemoveSystemAbility function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, OnRemoveSystemAbility001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + int32_t systemAbilityId = MEMORY_MANAGER_SA_ID; + std::string deviceId = "ohos.test.kvstoredataservice"; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnRemoveSystemAbility(systemAbilityId, deviceId)); + + systemAbilityId = COMMON_EVENT_SERVICE_ID; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnRemoveSystemAbility(systemAbilityId, deviceId)); +} + +/** +* @tc.name: OnStoreMetaChanged001 +* @tc.desc: test OnStoreMetaChanged function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, OnStoreMetaChanged001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + std::vector key = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}; + std::vector value = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + CHANGE_FLAG flag = CHANGE_FLAG::UPDATE; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnStoreMetaChanged(key, value, flag)); +} + +/** +* @tc.name: AccountEventChanged001 +* @tc.desc: test AccountEventChanged function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, AccountEventChanged001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + AccountEventInfo eventInfo; + eventInfo.status = AccountStatus::DEVICE_ACCOUNT_DELETE; + eventInfo.userId = "100"; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.AccountEventChanged(eventInfo)); + + eventInfo.userId = ""; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.AccountEventChanged(eventInfo)); + + eventInfo.status = AccountStatus::DEVICE_ACCOUNT_SWITCHED; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.AccountEventChanged(eventInfo)); + + eventInfo.status = AccountStatus::DEVICE_ACCOUNT_UNLOCKED; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.AccountEventChanged(eventInfo)); +} + +/** +* @tc.name: InitSecurityAdapter001 +* @tc.desc: test InitSecurityAdapter function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, InitSecurityAdapter001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + std::shared_ptr executors2 = std::make_shared(1, 0); + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.InitSecurityAdapter(executors2)); +} + +/** +* @tc.name: OnDeviceOnline001 +* @tc.desc: test OnDeviceOnline function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, OnDeviceOnline001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + AppDistributedKv::DeviceInfo info1; + info1.uuid = ""; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnDeviceOnline(info1)); + + AppDistributedKv::DeviceInfo info; + info.uuid = "ohos.test.uuid"; + info.udid = "ohos.test.udid"; + info.networkId = "ohos.test.networkId"; + info.deviceName = "ohos.test.deviceName"; + info.deviceType = 1; + info.osType = 1; + info.authForm = 1; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnDeviceOnline(info)); +} + +/** +* @tc.name: OnDeviceOffline001 +* @tc.desc: test OnDeviceOffline function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, OnDeviceOffline001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + AppDistributedKv::DeviceInfo info1; + info1.uuid = ""; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnDeviceOffline(info1)); + + AppDistributedKv::DeviceInfo info; + info.uuid = "ohos.test.uuid"; + info.udid = "ohos.test.udid"; + info.networkId = "ohos.test.networkId"; + info.deviceName = "ohos.test.deviceName"; + info.deviceType = 1; + info.osType = 1; + info.authForm = 1; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnDeviceOffline(info)); +} + +/** +* @tc.name: OnDeviceOnReady001 +* @tc.desc: test OnDeviceOnReady function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, OnDeviceOnReady001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + AppDistributedKv::DeviceInfo info1; + info1.uuid = ""; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnDeviceOnReady(info1)); + + AppDistributedKv::DeviceInfo info; + info.uuid = "ohos.test.uuid"; + info.udid = "ohos.test.udid"; + info.networkId = "ohos.test.networkId"; + info.deviceName = "ohos.test.deviceName"; + info.deviceType = 1; + info.osType = 1; + info.authForm = 1; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnDeviceOnReady(info)); +} + +/** +* @tc.name: OnSessionReady001 +* @tc.desc: test OnSessionReady function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, OnSessionReady001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + AppDistributedKv::DeviceInfo info1; + info1.uuid = ""; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnSessionReady(info1)); + + AppDistributedKv::DeviceInfo info; + info.uuid = "ohos.test.uuid"; + info.udid = "ohos.test.udid"; + info.networkId = "ohos.test.networkId"; + info.deviceName = "ohos.test.deviceName"; + info.deviceType = 1; + info.osType = 1; + info.authForm = 1; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.OnSessionReady(info)); +} + +/** +* @tc.name: DumpStoreInfo001 +* @tc.desc: test DumpStoreInfo function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, DumpStoreInfo001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + int fd = 0; + std::map> params = {}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.DumpStoreInfo(fd, params)); +} + +/** +* @tc.name: FilterData001 +* @tc.desc: test FilterData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, FilterData001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + std::vector metas = {}; + std::map> filterInfo = {}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.FilterData(metas, filterInfo)); +} + +/** +* @tc.name: FilterData002 +* @tc.desc: test FilterData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, FilterData002, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + StoreMetaData storeMeta; + storeMeta.user = "user"; + std::vector metas = {storeMeta}; + std::map> filterInfo; + filterInfo["USER_INFO"].push_back(""); + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.FilterData(metas, filterInfo)); + EXPECT_TRUE(kvStoreDataServiceTest.IsExist("USER_INFO", filterInfo, storeMeta.user)); +} + +/** +* @tc.name: FilterData003 +* @tc.desc: test FilterData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, FilterData003, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + StoreMetaData storeMeta; + storeMeta.bundleName = "bundleName"; + std::vector metas = {storeMeta}; + std::map> filterInfo; + + filterInfo["BUNDLE_INFO"] = {}; + EXPECT_FALSE(kvStoreDataServiceTest.IsExist("BUNDLE_INFO", filterInfo, storeMeta.bundleName)); + + filterInfo["BUNDLE_INFO"].push_back(""); + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.FilterData(metas, filterInfo)); + EXPECT_TRUE(kvStoreDataServiceTest.IsExist("BUNDLE_INFO", filterInfo, storeMeta.bundleName)); +} + +/** +* @tc.name: FilterData004 +* @tc.desc: test FilterData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, FilterData004, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + StoreMetaData storeMeta; + storeMeta.storeId = "storeId"; + std::vector metas = {storeMeta}; + std::map> filterInfo; + filterInfo["STORE_INFO"].push_back(""); + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.FilterData(metas, filterInfo)); + EXPECT_TRUE(kvStoreDataServiceTest.IsExist("STORE_INFO", filterInfo, storeMeta.storeId)); + + filterInfo["STORE_INFO"].push_back("storeId"); + EXPECT_FALSE(kvStoreDataServiceTest.IsExist("STORE_INFO", filterInfo, storeMeta.storeId)); +} + +/** +* @tc.name: PrintfInfo001 +* @tc.desc: test PrintfInfo function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, PrintfInfo001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + int fd = 0; + StoreMetaData storeMeta1; + std::vector metas = {storeMeta1}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.PrintfInfo(fd, metas)); + + StoreMetaData storeMeta2; + metas = {storeMeta1, storeMeta2}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.PrintfInfo(fd, metas)); +} + +/** +* @tc.name: PrintfInfo002 +* @tc.desc: test PrintfInfo function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, PrintfInfo002, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + int fd = 0; + std::map datas; + KvStoreDataService::UserInfo userInfo; + datas["user1"] = userInfo; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.PrintfInfo(fd, datas)); + + datas["user2"] = userInfo; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.PrintfInfo(fd, datas)); +} + +/** +* @tc.name: PrintfInfo003 +* @tc.desc: test PrintfInfo function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, PrintfInfo003, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + int fd = 0; + std::map datas; + KvStoreDataService::BundleInfo bundleInfo; + datas["bundleName1"] = bundleInfo; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.PrintfInfo(fd, datas)); + + datas["bundleName2"] = bundleInfo; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.PrintfInfo(fd, datas)); +} + +/** +* @tc.name: BuildData001 +* @tc.desc: test BuildData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, BuildData001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + std::map datas; + KvStoreDataService::UserInfo userInfo; + datas["user"] = userInfo; + StoreMetaData storeMeta1; + std::vector metas = {storeMeta1}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.BuildData(datas, metas)); + + StoreMetaData storeMeta2; + storeMeta2.user = "user"; + metas = {storeMeta2}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.BuildData(datas, metas)); +} + +/** +* @tc.name: BuildData002 +* @tc.desc: test BuildData function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, BuildData002, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + std::map datas; + KvStoreDataService::BundleInfo bundleInfo; + datas["bundleName"] = bundleInfo; + StoreMetaData storeMeta1; + std::vector metas = {storeMeta1}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.BuildData(datas, metas)); + + StoreMetaData storeMeta2; + storeMeta2.bundleName = "bundleName"; + metas = {storeMeta2}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.BuildData(datas, metas)); +} + +/** +* @tc.name: DumpUserInfo001 +* @tc.desc: test DumpUserInfo function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, DumpUserInfo001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + int fd = 0; + std::map> params = {}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.DumpUserInfo(fd, params)); +} + +/** +* @tc.name: DumpBundleInfo001 +* @tc.desc: test DumpBundleInfo function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(KvStoreDataServiceTest, DumpBundleInfo001, TestSize.Level0) +{ + KvStoreDataService kvStoreDataServiceTest; + int fd = 0; + std::map> params = {}; + EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.DumpBundleInfo(fd, params)); +} + +/** +* @tc.name: UpgradeManagerTest001 +* @tc.desc: test Init function +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(UpgradeManagerTest, UpgradeManagerTest001, TestSize.Level0) +{ + auto executors = std::make_shared(1, 0); + DistributedData::UpgradeManager instance; + instance.Init(executors); + EXPECT_TRUE(instance.executors_); + + instance.Init(executors); + EXPECT_TRUE(instance.executors_); +} +} // namespace OHOS::Test \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/framework/BUILD.gn b/datamgr_service/services/distributeddataservice/framework/BUILD.gn index 19dc6cfa65639eace05caa11c627c45011639ba8..0456d7f2268788b9af25762b5158b0e00b3ae1c2 100644 --- a/datamgr_service/services/distributeddataservice/framework/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/framework/BUILD.gn @@ -106,6 +106,7 @@ ohos_shared_library("distributeddatasvcfwk") { "utils/ref_count.cpp", ] cflags = [ + "-Werror", "-Wno-multichar", "-D_LIBCPP_HAS_COND_CLOCKWAIT", ] diff --git a/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h b/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h index 0ee41a97222dd952e1d31258874cbfa73fb070c7..9eb51570ff2cfba076a2b12d8c074ff34009d3b1 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h +++ b/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h @@ -40,6 +40,8 @@ public: using Executor = ExecutorPool; using TaskId = ExecutorPool::TaskId; using Creator = std::function; + using Filter = std::function; + API_EXPORT static AutoCache &GetInstance(); API_EXPORT int32_t RegCreator(int32_t type, Creator creator); @@ -52,7 +54,7 @@ public: API_EXPORT void CloseStore(uint32_t tokenId, const std::string &storeId = ""); - API_EXPORT void CloseExcept(const std::set &users); + API_EXPORT void CloseStore(const Filter &filter); API_EXPORT void SetObserver(uint32_t tokenId, const std::string &storeId, const Watchers &watchers); @@ -75,6 +77,7 @@ private: int32_t GetUser() const; int32_t GetArea() const; const std::string& GetDataDir() const; + const StoreMetaData& GetMeta() const; void SetObservers(const Watchers &watchers); int32_t OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) override; int32_t OnChange(const Origin &origin, const Fields &fields, ChangeData &&datas) override; diff --git a/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h b/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h index 1d654f28d8024fe1257d1668d602f1afe06d2538..80d9569b5a0a8d8aa43886770255c13aca5b7a86 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h +++ b/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h @@ -112,10 +112,12 @@ public: bool enableCloud_ = false; }; - enum DistributedDb { + enum ErrOffset { DB_MODE_ID = 1, + CLOUD_MODE_ID = 10, }; static const int32_t DB_ERR_OFFSET = ErrCodeOffset(SUBSYS_DISTRIBUTEDDATAMNG, DB_MODE_ID); + static const int32_t CLOUD_ERR_OFFSET = ErrCodeOffset(SUBSYS_DISTRIBUTEDDATAMNG, CLOUD_MODE_ID); virtual ~GeneralStore() = default; @@ -124,7 +126,7 @@ public: virtual int32_t Bind(Database &database, const std::map &bindInfos, const CloudConfig &config) = 0; - virtual bool IsBound() = 0; + virtual bool IsBound(uint32_t user) = 0; virtual int32_t Execute(const std::string &table, const std::string &sql) = 0; @@ -132,7 +134,7 @@ public: const std::vector &tables, int type, const std::vector &references) = 0; virtual int32_t SetTrackerTable(const std::string &tableName, const std::set &trackerColNames, - const std::string &extendColName, bool isForceUpgrade) = 0; + const std::set &extendColNames, bool isForceUpgrade) = 0; virtual int32_t Insert(const std::string &table, VBuckets &&values) = 0; @@ -148,7 +150,8 @@ public: virtual std::pair> Query(const std::string &table, GenQuery &query) = 0; - virtual int32_t Sync(const Devices &devices, GenQuery &query, DetailAsync async, SyncParam &syncParm) = 0; + virtual std::pair Sync(const Devices &devices, GenQuery &query, + DetailAsync async, const SyncParam &syncParm) = 0; virtual std::pair> PreSharing(GenQuery &query) = 0; diff --git a/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp b/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp index fa94983b91ccbb99362ae1f4c6ef2ed72ddb87aa..0ea9bc7f2e7ce15ecbb618a4dcb7f98bc4bfb72c 100644 --- a/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp +++ b/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp @@ -31,11 +31,11 @@ AutoCache &AutoCache::GetInstance() int32_t AutoCache::RegCreator(int32_t type, Creator creator) { - if (type >= MAX_CREATOR_NUM) { + if (type < 0 || type >= MAX_CREATOR_NUM) { return E_ERROR; } creators_[type] = creator; - return 0; + return E_OK; } void AutoCache::Bind(std::shared_ptr executor) @@ -158,9 +158,8 @@ void AutoCache::CloseStore(uint32_t tokenId, const std::string &storeId) disableStores_.insert(it->second.GetDataDir()); storeIds.insert(it->first); closeStores.emplace(closeStores.end(), it->second); - } else { - ++it; } + ++it; } return !delegates.empty(); }); @@ -178,20 +177,35 @@ void AutoCache::CloseStore(uint32_t tokenId, const std::string &storeId) }); } -void AutoCache::CloseExcept(const std::set &users) +void AutoCache::CloseStore(const AutoCache::Filter &filter) { - bool isScreenLocked = ScreenManager::GetInstance()->IsLocked(); - stores_.EraseIf([&users, isScreenLocked](const auto &tokenId, std::map &delegates) { - if (delegates.empty() || users.count(delegates.begin()->second.GetUser()) != 0) { - return delegates.empty(); - } - - for (auto it = delegates.begin(); it != delegates.end();) { - // if the kv store is BUSY we wait more INTERVAL minutes again - if ((isScreenLocked && it->second.GetArea() >= GeneralStore::EL4) || !it->second.Close()) { + if (filter == nullptr) { + return; + } + std::map> storeIds; + std::list closeStores; + stores_.ForEach( + [this, &filter, &storeIds, &closeStores](const auto &tokenId, std::map &delegates) { + auto it = delegates.begin(); + while (it != delegates.end()) { + if (disableStores_.count(it->second.GetDataDir()) == 0 && filter(it->second.GetMeta())) { + disableStores_.insert(it->second.GetDataDir()); + storeIds[tokenId].insert(it->first); + closeStores.emplace(closeStores.end(), it->second); + } ++it; - } else { + } + return false; + }); + closeStores.clear(); + stores_.EraseIf([this, &storeIds](auto &tokenId, auto &delegates) { + for (auto it = delegates.begin(); it != delegates.end();) { + auto ids = storeIds.find(tokenId); + if (ids != storeIds.end() && ids->second.count(it->first) != 0) { + disableStores_.erase(it->second.GetDataDir()); it = delegates.erase(it); + } else { + ++it; } } return delegates.empty(); @@ -321,6 +335,11 @@ const std::string& AutoCache::Delegate::GetDataDir() const return meta_.dataDir; } +const StoreMetaData &AutoCache::Delegate::GetMeta() const +{ + return meta_; +} + int32_t AutoCache::Delegate::OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) { std::vector tables; diff --git a/datamgr_service/services/distributeddataservice/framework/test/BUILD.gn b/datamgr_service/services/distributeddataservice/framework/test/BUILD.gn index 2476ad7d067766da1f672cdc2d011bdc445f867f..a1351798e30900898839e2df0f2f0fe38fa56cb1 100644 --- a/datamgr_service/services/distributeddataservice/framework/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/framework/test/BUILD.gn @@ -47,6 +47,7 @@ config("module_private_config") { "${data_service_path}/service/waterversion", "//third_party/json/single_include", ] + cflags = [ "-Werror" ] ldflags = [ "-Wl,--whole-archive" ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } diff --git a/datamgr_service/services/distributeddataservice/rust/connect_adapter/BUILD.gn b/datamgr_service/services/distributeddataservice/rust/connect_adapter/BUILD.gn index a5759ed585ba5a847f84558f59c830c8400eb731..49162568bd6ea279da85d11bdb65a87a02544d91 100644 --- a/datamgr_service/services/distributeddataservice/rust/connect_adapter/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/rust/connect_adapter/BUILD.gn @@ -34,6 +34,7 @@ ohos_shared_library("conn_adapter") { "src/connect_wrapper.cpp", ] configs = [ ":export_connect" ] + cflags = [ "-Werror" ] cflags_cc = [ "-fvisibility=hidden" ] external_deps = [ diff --git a/datamgr_service/services/distributeddataservice/rust/extension/BUILD.gn b/datamgr_service/services/distributeddataservice/rust/extension/BUILD.gn index cffbfca971c9d6f8ab4a3021e261c34cb8c9294b..ab8f148b9a2eb5c39fecc47a9005d1a6126d102c 100644 --- a/datamgr_service/services/distributeddataservice/rust/extension/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/rust/extension/BUILD.gn @@ -42,7 +42,10 @@ ohos_shared_library("opencloudextension") { cfi_cross_dso = true debug = false } - cflags = [ "-Wno-multichar" ] + cflags = [ + "-Werror", + "-Wno-multichar", + ] cflags_cc = [ "-fvisibility=hidden" ] diff --git a/datamgr_service/services/distributeddataservice/rust/extension/asset_loader_impl.cpp b/datamgr_service/services/distributeddataservice/rust/extension/asset_loader_impl.cpp index 035aee18b9892272e722dde1720a79e3b392917f..0d50e9b401723abe8596e15f81c28061f2fe3b95 100644 --- a/datamgr_service/services/distributeddataservice/rust/extension/asset_loader_impl.cpp +++ b/datamgr_service/services/distributeddataservice/rust/extension/asset_loader_impl.cpp @@ -79,7 +79,7 @@ int32_t AssetLoaderImpl::RemoveLocalAssets( return DBErr::E_OK; } auto dbAsset = std::get_if(&value); - if (dbAssets != nullptr) { + if (dbAsset != nullptr) { RemoveLocalAsset(*dbAsset); return DBErr::E_OK; } diff --git a/datamgr_service/services/distributeddataservice/service/BUILD.gn b/datamgr_service/services/distributeddataservice/service/BUILD.gn index 4c04cb7e45a9510673290bdf528594c46c6a705b..6f64cdeb3b9a2cbd9efb65f7c1a41f93da789997 100644 --- a/datamgr_service/services/distributeddataservice/service/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/BUILD.gn @@ -132,6 +132,7 @@ ohos_shared_library("distributeddatasvc") { "waterversion/water_version_manager.cpp", ] cflags = [ + "-Werror", "-Wno-multichar", "-Wno-c99-designator", "-D_LIBCPP_HAS_COND_CLOCKWAIT", diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index cbd0125b3d61a39c20d930253e6c50b6f7806ce3..badff50f50d1f946dafe7b927476938e206a20c4 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -672,6 +672,8 @@ int32_t CloudServiceImpl::OnUserChange(uint32_t code, const std::string &user, c Execute(GenTask(0, userId, { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB })); break; case static_cast(AccountStatus::DEVICE_ACCOUNT_DELETE): + case static_cast(AccountStatus::DEVICE_ACCOUNT_STOPPING): + case static_cast(AccountStatus::DEVICE_ACCOUNT_STOPPED): Execute(GenTask(0, userId, { WORK_STOP_CLOUD_SYNC, WORK_RELEASE })); break; case static_cast(AccountStatus::DEVICE_ACCOUNT_UNLOCKED): diff --git a/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp b/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp index 19fa812216e59d45a84ee5e4202f91184bf2e7b9..b666a88fc1ee472eed4d2f291df5922aa6c16d75 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -44,6 +44,7 @@ using Account = OHOS::DistributedKv::AccountDelegate; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Defer = EventCenter::Defer; std::atomic SyncManager::genId_ = 0; +constexpr int32_t SYSTEM_USER_ID = 0; SyncManager::SyncInfo::SyncInfo( int32_t user, const std::string &bundleName, const Store &store, const Tables &tables, int32_t triggerMode) : user_(user), bundleName_(bundleName), triggerMode_(triggerMode) @@ -364,7 +365,8 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount schemas = GetSchemaMeta(cloud, info.bundleName_); if (schemas.empty()) { auto it = traceIds.find(info.bundleName_); - retryer(RETRY_INTERVAL, E_RETRY_TIMEOUT, E_CLOUD_DISABLED, it == traceIds.end() ? "" : it->second); + retryer(RETRY_INTERVAL, E_RETRY_TIMEOUT, GenStore::CLOUD_ERR_OFFSET + E_CLOUD_DISABLED, + it == traceIds.end() ? "" : it->second); BatchUpdateFinishState(cloudSyncInfos, E_CLOUD_DISABLED); BatchReport(info.user_, traceIds, SyncStage::END, E_CLOUD_DISABLED); return; @@ -407,7 +409,7 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) "GetSyncHandler", BizState::BEGIN); Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::START, E_OK }); SyncParam syncParam = { evt.GetMode(), evt.GetWait(), evt.IsCompensation(), MODE_DEFAULT, prepareTraceId }; - auto status = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()), + auto [status, dbCode] = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()), evt.AutoRetry() ? RetryCallback(storeInfo, retryer, evt.GetTriggerMode(), prepareTraceId, user) : GetCallback(evt.GetAsyncDetail(), storeInfo, evt.GetTriggerMode(), prepareTraceId, user), syncParam); @@ -420,10 +422,10 @@ std::function SyncManager::GetSyncHandler(Retryer retryer) if (status == GeneralError::E_NOT_SUPPORT) { return; } - int32_t errCode = status + GenStore::DB_ERR_OFFSET; + auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode; RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, - evt.GetTriggerMode(), false, errCode }, "GetSyncHandler", BizState::END); - Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, errCode }); + evt.GetTriggerMode(), false, code }, "GetSyncHandler", BizState::END); + Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, code }); } }; } @@ -568,17 +570,20 @@ AutoCache::Store SyncManager::GetStore(const StoreMetaData &meta, int32_t user, ZLOGE("store null, storeId:%{public}s", meta.GetStoreAlias().c_str()); return nullptr; } - if (!store->IsBound()) { - std::vector users{}; - CloudInfo info; - if (user == 0) { - AccountDelegate::GetInstance()->QueryForegroundUsers(users); - } else { - users.push_back(user); - } - if (!users.empty()) { - info.user = users[0]; - } + CloudInfo info; + info.user = user; + std::vector users{}; + if (info.user == SYSTEM_USER_ID) { + AccountDelegate::GetInstance()->QueryForegroundUsers(users); + info.user = users.empty() ? SYSTEM_USER_ID : users[0]; + } else { + users.push_back(user); + } + if (info.user == SYSTEM_USER_ID) { + ZLOGE("invalid cloud users, bundleName:%{public}s", meta.bundleName.c_str()); + return nullptr; + } + if (!store->IsBound(info.user)) { SchemaMeta schemaMeta; std::string schemaKey = info.GetSchemaKey(meta.bundleName, meta.instanceId); if (!MetaDataManager::GetInstance().LoadMeta(schemaKey, schemaMeta, true)) { diff --git a/datamgr_service/services/distributeddataservice/service/data_share/BUILD.gn b/datamgr_service/services/distributeddataservice/service/data_share/BUILD.gn index f2992608080489e995759c42151fa88eae32933d..e2e7181642aaca7fd90025750b9b42d5cda59296 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/data_share/BUILD.gn @@ -88,6 +88,7 @@ ohos_shared_library("data_share_service") { "sys_event_subscriber.cpp", ] cflags = [ + "-Werror", "-Wno-multichar", "-D_LIBCPP_HAS_COND_CLOCKWAIT", ] diff --git a/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.cpp b/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.cpp index f9ba94f047fb3fd9eef242af3d1c578f67f7d681..abc2c1925ea6f766d6044a10c4c9995c92c166fa 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.cpp @@ -44,7 +44,7 @@ std::shared_ptr DBDelegate::Create(DistributedData::StoreMetaData &m ZLOGE("creator failed, storeName: %{public}s", metaData.GetStoreAlias().c_str()); return false; } - auto entity = std::make_shared(store); + auto entity = std::make_shared(store, metaData); stores.emplace(metaData.storeId, entity); StartTimer(); return !stores.empty(); @@ -57,13 +57,33 @@ void DBDelegate::SetExecutorPool(std::shared_ptr executor) executor_ = std::move(executor); } +void DBDelegate::Close(const DBDelegate::Filter &filter) +{ + if (filter == nullptr) { + return; + } + std::list> closeStores; + stores_.EraseIf([&closeStores, &filter](auto &, std::map> &stores) { + for (auto it = stores.begin(); it != stores.end();) { + if (it->second == nullptr || filter(it->second->user)) { + closeStores.push_back(it->second); + it = stores.erase(it); + } else { + ++it; + } + } + return stores.empty(); + }); +} + void DBDelegate::GarbageCollect() { - stores_.EraseIf([](auto &, std::map> &stores) { + std::list> closeStores; + stores_.EraseIf([&closeStores](auto &, std::map> &stores) { auto current = std::chrono::steady_clock::now(); for (auto it = stores.begin(); it != stores.end();) { - // if the store is BUSY we wait more INTERVAL minutes again if (it->second->time_ < current) { + closeStores.push_back(it->second); it = stores.erase(it); } else { ++it; @@ -94,10 +114,11 @@ void DBDelegate::StartTimer() ZLOGD("start timer, taskId: %{public}" PRIu64, taskId_); } -DBDelegate::Entity::Entity(std::shared_ptr store) +DBDelegate::Entity::Entity(std::shared_ptr store, const DistributedData::StoreMetaData &meta) { store_ = std::move(store); time_ = std::chrono::steady_clock::now() + std::chrono::seconds(INTERVAL); + user = meta.user; } void DBDelegate::EraseStoreCache(const int32_t tokenId) diff --git a/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.h b/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.h index 05ed3b843bb7c8c6bae80c83df2861204868ee00..06da8d8d1239b2b9b4e4e38418fd9f843b7a831d 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.h +++ b/datamgr_service/services/distributeddataservice/service/data_share/common/db_delegate.h @@ -33,8 +33,10 @@ namespace OHOS::DataShare { class DBDelegate { public: using Time = std::chrono::steady_clock::time_point; + using Filter = std::function; static std::shared_ptr Create(DistributedData::StoreMetaData &metaData, const std::string &extUri = "", const std::string &backup = ""); + static void Close(const Filter &filter); virtual std::pair> Query(const std::string &tableName, const DataSharePredicates &predicates, const std::vector &columns, const int32_t callingPid) = 0; @@ -55,8 +57,9 @@ private: static void GarbageCollect(); static void StartTimer(); struct Entity { - explicit Entity(std::shared_ptr store); + explicit Entity(std::shared_ptr store, const DistributedData::StoreMetaData &meta); std::shared_ptr store_; + std::string user; Time time_; }; static constexpr int NO_CHANGE_VERSION = -1; diff --git a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index 1b31c377a26c34f5d2e0e97a0aea0ecccfa009b6..3c0d6854bf0b80f5f02f26635ab38edb09e61a90 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -1013,4 +1013,30 @@ void DataShareServiceImpl::InitSubEvent() sysEventSubscriber->OnBMSReady(); } } + +int32_t DataShareServiceImpl::OnUserChange(uint32_t code, const std::string &user, const std::string &account) +{ + ZLOGI("code:%{public}d, user:%{public}s, account:%{public}s", code, user.c_str(), + Anonymous::Change(account).c_str()); + switch (code) { + case static_cast(DistributedKv::AccountStatus::DEVICE_ACCOUNT_DELETE): + case static_cast(DistributedKv::AccountStatus::DEVICE_ACCOUNT_STOPPED): { + std::vector users; + DistributedKv::AccountDelegate::GetInstance()->QueryUsers(users); + std::set userIds(users.begin(), users.end()); + DBDelegate::Close([&userIds](const std::string &userId) { + return userIds.count(atoi(userId.c_str())) == 0; + }); + break; + } + case static_cast(DistributedKv::AccountStatus::DEVICE_ACCOUNT_STOPPING): + DBDelegate::Close([&user](const std::string &userId) { + return user == userId; + }); + break; + default: + break; + } + return E_OK; +} } // namespace OHOS::DataShare diff --git a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h index 634322ccc33dfffdce4aec9b3f9960d1892f85a1..2fcc6420133f2740eaa0292310fddd2be391ae90 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h @@ -76,6 +76,7 @@ public: int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName) override; int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) override; + int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account) override; void NotifyObserver(const std::string &uri) override; void DumpDataShareServiceInfo(int fd, std::map> ¶ms); int32_t OnInitialize() override; diff --git a/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index f40aeab434a602916a3971cdab7b0440b544eed5..1066024e7738cefc9e354ee3ed449d3a6600f10b 100644 --- a/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -210,9 +210,9 @@ KVDBGeneralStore::~KVDBGeneralStore() manager_.CloseKvStore(delegate_); delegate_ = nullptr; } - for (auto &bindInfo_ : bindInfos_) { - if (bindInfo_.db_ != nullptr) { - bindInfo_.db_->Close(); + for (auto &bindInfo : bindInfos_) { + if (bindInfo.db_ != nullptr) { + bindInfo.db_->Close(); } } bindInfos_.clear(); @@ -231,22 +231,25 @@ int32_t KVDBGeneralStore::Bind( ZLOGW("No cloudDB!"); return GeneralError::E_OK; } - std::map schemas; auto dbSchema = GetDBSchema(database); + std::set users; for (auto &[userId, bindInfo] : bindInfos) { if (bindInfo.db_ == nullptr) { return GeneralError::E_INVALID_ARGS; } - - if (isBound_.exchange(true)) { - return GeneralError::E_OK; - } - + users.insert(userId); dbClouds_.insert({ std::to_string(userId), std::make_shared(bindInfo.db_, nullptr) }); bindInfos_.insert(std::move(bindInfo)); schemas.insert({ std::to_string(userId), dbSchema }); } + { + std::unique_lock lock(bindMutex_); + if (users_ == users) { + return GeneralError::E_OK; + } + users_ = users; + } DistributedDB::CloudSyncConfig dbConfig; dbConfig.maxUploadCount = config.maxNumber; dbConfig.maxUploadSize = config.maxSize; @@ -261,9 +264,10 @@ int32_t KVDBGeneralStore::Bind( return GeneralError::E_OK; } -bool KVDBGeneralStore::IsBound() +bool KVDBGeneralStore::IsBound(uint32_t user) { - return isBound_; + std::shared_lock lock(bindMutex_); + return users_.find(user) != users_.end(); } int32_t KVDBGeneralStore::Close(bool isForce) @@ -375,26 +379,27 @@ DBStatus KVDBGeneralStore::CloudSync(const Devices &devices, DistributedDB::Sync return delegate_->Sync(syncOption, GetDBProcessCB(async)); } -int32_t KVDBGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAsync async, SyncParam &syncParam) +std::pair KVDBGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAsync async, + const SyncParam &syncParam) { auto syncMode = GeneralStore::GetSyncMode(syncParam.mode); std::shared_lock lock(rwMutex_); if (delegate_ == nullptr) { ZLOGE("store already closed! devices count:%{public}zu, the 1st:%{public}s, mode:%{public}d", devices.size(), devices.empty() ? "null" : Anonymous::Change(*devices.begin()).c_str(), syncParam.mode); - return GeneralError::E_ALREADY_CLOSED; + return { GeneralError::E_ALREADY_CLOSED, DBStatus::OK }; } DBStatus dbStatus; auto dbMode = DistributedDB::SyncMode(syncMode); if (syncMode > NEARBY_END && syncMode < CLOUD_END) { if (!enableCloud_) { - return GeneralError::E_NOT_SUPPORT; + return { GeneralError::E_NOT_SUPPORT, DBStatus::OK }; } dbStatus = CloudSync(devices, dbMode, async, syncParam.wait, syncParam.prepareTraceId); } else { if (devices.empty()) { ZLOGE("Devices is empty! mode:%{public}d", syncParam.mode); - return GeneralError::E_INVALID_ARGS; + return { GeneralError::E_INVALID_ARGS, DBStatus::OK }; } KVDBQuery *kvQuery = nullptr; auto ret = query.QueryInterface(kvQuery); @@ -402,7 +407,7 @@ int32_t KVDBGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAs if (ret == GeneralError::E_OK && kvQuery != nullptr && kvQuery->IsValidQuery()) { dbQuery = kvQuery->GetDBQuery(); } else { - return GeneralError::E_INVALID_ARGS; + return { GeneralError::E_INVALID_ARGS, DBStatus::OK }; } if (syncMode == NEARBY_SUBSCRIBE_REMOTE) { dbStatus = delegate_->SubscribeRemoteQuery(devices, GetDBSyncCompleteCB(std::move(async)), dbQuery, false); @@ -420,7 +425,7 @@ int32_t KVDBGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAs dbStatus = DistributedDB::INVALID_ARGS; } } - return ConvertStatus(dbStatus); + return { ConvertStatus(dbStatus), dbStatus }; } void KVDBGeneralStore::SetEqualIdentifier(const std::string &appId, const std::string &storeId, const std::string &account) @@ -566,7 +571,7 @@ int32_t KVDBGeneralStore::SetDistributedTables( } int32_t KVDBGeneralStore::SetTrackerTable(const std::string &tableName, const std::set &trackerColNames, - const std::string &extendColName, bool isForceUpgrade) + const std::set &extendColNames, bool isForceUpgrade) { return GeneralError::E_OK; } @@ -735,7 +740,7 @@ void KVDBGeneralStore::SetDBReceiveDataInterceptor(int32_t storeType) return errCode; } if (sourceID.empty()) { - ZLOGE("targetID empty"); + ZLOGE("sourceID empty"); return static_cast(DBStatus::DB_ERROR); } auto entries = data.GetEntries(); diff --git a/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.h b/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.h index 5a84a0f280c4e75823ef8a53b261f57852502422..fe37ac820d70ea22bb0ac2b12c78a9ae12baae18 100644 --- a/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.h +++ b/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_general_store.h @@ -44,13 +44,13 @@ public: explicit KVDBGeneralStore(const StoreMetaData &meta); ~KVDBGeneralStore(); int32_t Bind(Database &database, const std::map &bindInfos, const CloudConfig &config) override; - bool IsBound() override; + bool IsBound(uint32_t user) override; bool IsValid(); int32_t Execute(const std::string &table, const std::string &sql) override; int32_t SetDistributedTables( const std::vector &tables, int32_t type, const std::vector &references) override; int32_t SetTrackerTable(const std::string &tableName, const std::set &trackerColNames, - const std::string &extendColName, bool isForceUpgrade = false) override; + const std::set &extendColNames, bool isForceUpgrade = false) override; int32_t Insert(const std::string &table, VBuckets &&values) override; int32_t Update(const std::string &table, const std::string &setSql, Values &&values, const std::string &whereSql, Values &&conditions) override; @@ -59,7 +59,8 @@ public: std::pair> Query( const std::string &table, const std::string &sql, Values &&args) override; std::pair> Query(const std::string &table, GenQuery &query) override; - int32_t Sync(const Devices &devices, GenQuery &query, DetailAsync async, SyncParam &syncParm) override; + std::pair Sync(const Devices &devices, GenQuery &query, DetailAsync async, + const SyncParam &syncParm) override; std::pair> PreSharing(GenQuery &query) override; int32_t Clean(const std::vector &devices, int32_t mode, const std::string &tableName) override; int32_t Watch(int32_t origin, Watcher &watcher) override; @@ -125,7 +126,8 @@ private: KvDelegate *delegate_ = nullptr; std::map> dbClouds_{}; std::set bindInfos_; - std::atomic isBound_ = false; + std::shared_mutex bindMutex_; + std::set users_{}; std::mutex mutex_; int32_t ref_ = 1; mutable std::shared_timed_mutex rwMutex_; diff --git a/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 2efbeeaf65b7d96c1812fcef2789fd91caf38a6c..5593bc0b4d0c144a89c23810c53fda89f018e8ee 100644 --- a/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -778,7 +778,7 @@ int32_t KVDBServiceImpl::ResolveAutoLaunch(const std::string &identifier, DBLaun { ZLOGI("user:%{public}s appId:%{public}s storeId:%{public}s identifier:%{public}s", param.userId.c_str(), param.appId.c_str(), Anonymous::Change(param.storeId).c_str(), Anonymous::Change(identifier).c_str()); - + std::vector metaData; auto prefix = StoreMetaData::GetPrefix({ DMAdapter::GetInstance().GetLocalDevice().uuid }); if (!MetaDataManager::GetInstance().LoadMeta(prefix, metaData)) { @@ -812,13 +812,6 @@ int32_t KVDBServiceImpl::ResolveAutoLaunch(const std::string &identifier, DBLaun int32_t KVDBServiceImpl::OnUserChange(uint32_t code, const std::string &user, const std::string &account) { - (void)code; - (void)user; - (void)account; - std::vector users; - AccountDelegate::GetInstance()->QueryUsers(users); - std::set userIds(users.begin(), users.end()); - AutoCache::GetInstance().CloseExcept(userIds); return SUCCESS; } @@ -1128,7 +1121,7 @@ Status KVDBServiceImpl::DoSyncBegin(const std::vector &devices, con complete(deviceStatus); }, syncParam); - auto status = Status(ret); + auto status = Status(ret.first); if (status != Status::SUCCESS) { RADAR_REPORT(STANDARD_DEVICE_SYNC, START_SYNC, RADAR_FAILED, ERROR_CODE, status, BIZ_STATE, END, SYNC_STORE_ID, Anonymous::Change(meta.storeId), SYNC_APP_ID, meta.bundleName, CONCURRENT_ID, diff --git a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp index 1a3182fcc1d9f9496b05f47436c54913c8cb2976..5c32afaaa7794c3d99de0f3d2f1b71709edf420e 100644 --- a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp @@ -301,7 +301,7 @@ int32_t ObjectServiceImpl::ResolveAutoLaunch(const std::string &identifier, Dist param.appId.c_str(), DistributedData::Anonymous::Change(param.storeId).c_str(), DistributedData::Anonymous::Change(identifier).c_str()); std::vector metaData; - auto prefix = StoreMetaData::GetPrefix({ DmAdapter::GetInstance().GetLocalDevice().uuid, param.userId }); + auto prefix = StoreMetaData::GetPrefix({ DmAdapter::GetInstance().GetLocalDevice().uuid }); if (!DistributedData::MetaDataManager::GetInstance().LoadMeta(prefix, metaData)) { ZLOGE("no store in user:%{public}s", param.userId.c_str()); return OBJECT_STORE_NOT_FOUND; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_asset_loader.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_asset_loader.cpp index 5bb2e7cb25b573c33401cf15d373684667349598..f65d51a9afc1722b13485e87afdc5ef699820852 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_asset_loader.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_asset_loader.cpp @@ -158,7 +158,7 @@ void RdbAssetLoader::PostEvent(DistributedData::AssetEvent eventId, DistributedD deleteAssets.insert(downLoadAsset.uri); continue; } - if (snapshots_->bindAssets == nullptr) { + if (snapshots_ == nullptr || snapshots_->bindAssets == nullptr) { continue; } auto it = snapshots_->bindAssets->find(downLoadAsset.uri); diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp index 954e6eadf3a0db841dc214ffcf43f4e936b655a7..a102573e878ea5999bbaaaa2a2bec75d67633ad8 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -216,7 +216,7 @@ int32_t RdbGeneralStore::Bind(Database &database, const std::map RdbGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAsync async, + const SyncParam &syncParam) { DistributedDB::Query dbQuery; RdbQuery *rdbQuery = nullptr; @@ -525,7 +526,7 @@ int32_t RdbGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAsy ZLOGE("store already closed! devices count:%{public}zu, the 1st:%{public}s, mode:%{public}d, " "wait:%{public}d", devices.size(), devices.empty() ? "null" : Anonymous::Change(*devices.begin()).c_str(), syncParam.mode, syncParam.wait); - return GeneralError::E_ALREADY_CLOSED; + return { GeneralError::E_ALREADY_CLOSED, DBStatus::OK }; } auto highMode = GetHighMode(static_cast(syncParam.mode)); SyncId syncId = ++syncTaskId_; @@ -543,7 +544,7 @@ int32_t RdbGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAsy highMode == AUTO_SYNC_MODE, LOCK_ACTION, syncParam.prepareTraceId }, tasks_ != nullptr ? GetCB(syncId) : callback, syncId); if (dbStatus == DBStatus::OK || tasks_ == nullptr) { - return ConvertStatus(dbStatus); + return { ConvertStatus(dbStatus), dbStatus }; } tasks_->ComputeIfPresent(syncId, [executor = executor_](SyncId syncId, const FinishTask &task) { if (executor != nullptr) { @@ -552,7 +553,7 @@ int32_t RdbGeneralStore::Sync(const Devices &devices, GenQuery &query, DetailAsy return false; }); } - return ConvertStatus(dbStatus); + return { ConvertStatus(dbStatus), dbStatus }; } std::pair> RdbGeneralStore::PreSharing(GenQuery &query) @@ -731,7 +732,7 @@ RdbGeneralStore::DBProcessCB RdbGeneralStore::GetDBProcessCB(DetailAsync async, auto &detail = details[id]; detail.progress = process.process; detail.code = ConvertStatus(process.errCode); - detail.dbCode = DB_ERR_OFFSET + process.errCode; + detail.dbCode = process.errCode; uint32_t totalCount = 0; for (auto [key, value] : process.tableProcess) { auto &table = detail.details[key]; @@ -830,7 +831,7 @@ int32_t RdbGeneralStore::SetDistributedTables(const std::vector &ta } int32_t RdbGeneralStore::SetTrackerTable(const std::string &tableName, const std::set &trackerColNames, - const std::string &extendColName, bool isForceUpgrade) + const std::set &extendColNames, bool isForceUpgrade) { std::shared_lock lock(rwMutex_); if (delegate_ == nullptr) { @@ -838,7 +839,7 @@ int32_t RdbGeneralStore::SetTrackerTable(const std::string &tableName, const std Anonymous::Change(storeInfo_.storeName).c_str(), Anonymous::Change(tableName).c_str()); return GeneralError::E_ALREADY_CLOSED; } - auto status = delegate_->SetTrackerTable({ tableName, extendColName, trackerColNames, isForceUpgrade }); + auto status = delegate_->SetTrackerTable({ tableName, extendColNames, trackerColNames, isForceUpgrade }); if (status == DBStatus::WITH_INVENTORY_DATA) { ZLOGI("Set tracker table with inventory data, database:%{public}s, tables name:%{public}s", Anonymous::Change(storeInfo_.storeName).c_str(), Anonymous::Change(tableName).c_str()); diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h index dcb38ab14cb5be758c514d5bcaf393c8ffd202be..51cfc5f0c65269131397cacca88063c6cc525891 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -56,13 +56,13 @@ public: void SetExecutor(std::shared_ptr executor) override; int32_t Bind(Database &database, const std::map &bindInfos, const CloudConfig &config) override; - bool IsBound() override; + bool IsBound(uint32_t user) override; bool IsValid(); int32_t Execute(const std::string &table, const std::string &sql) override; int32_t SetDistributedTables(const std::vector &tables, int32_t type, const std::vector &references) override; int32_t SetTrackerTable(const std::string& tableName, const std::set& trackerColNames, - const std::string& extendColName, bool isForceUpgrade = false) override; + const std::set &extendColNames, bool isForceUpgrade = false) override; int32_t Insert(const std::string &table, VBuckets &&values) override; int32_t Update(const std::string &table, const std::string &setSql, Values &&values, const std::string &whereSql, Values &&conditions) override; @@ -71,8 +71,8 @@ public: std::pair> Query(const std::string &table, const std::string &sql, Values &&args) override; std::pair> Query(const std::string &table, GenQuery &query) override; - int32_t Sync( - const Devices &devices, GenQuery &query, DetailAsync async, DistributedData::SyncParam &syncParam) override; + std::pair Sync(const Devices &devices, GenQuery &query, DetailAsync async, + const DistributedData::SyncParam &syncParam) override; std::pair> PreSharing(GenQuery &query) override; int32_t Clean(const std::vector &devices, int32_t mode, const std::string &tableName) override; int32_t Watch(int32_t origin, Watcher &watcher) override; @@ -153,7 +153,7 @@ private: std::shared_ptr GetRdbCloud() const; bool IsFinished(uint64_t syncId) const; void RemoveTasks(); - + ObserverProxy observer_; RdbManager manager_; RdbDelegate *delegate_ = nullptr; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 17d05d287ed0eebdef9d2b9b7c56b2628bc46dea..36016b652017a33b5caaaf41eca430c3efc16e47 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -96,52 +96,9 @@ RdbServiceImpl::RdbServiceImpl() { ZLOGI("construct"); DistributedDB::RelationalStoreManager::SetAutoLaunchRequestCallback( - [this](const std::string& identifier, DistributedDB::AutoLaunchParam ¶m) { + [this](const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) { return ResolveAutoLaunch(identifier, param); }); - auto process = [this](const Event &event) { - auto &evt = static_cast(event); - auto &storeInfo = evt.GetStoreInfo(); - StoreMetaData meta(storeInfo); - meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) { - ZLOGE("meta empty, bundleName:%{public}s, storeId:%{public}s", meta.bundleName.c_str(), - meta.GetStoreAlias().c_str()); - return; - } - if (meta.storeType < StoreMetaData::STORE_RELATIONAL_BEGIN || - meta.storeType > StoreMetaData::STORE_RELATIONAL_END) { - return; - } - auto watchers = GetWatchers(meta.tokenId, meta.storeId); - auto store = AutoCache::GetInstance().GetStore(meta, watchers); - if (store == nullptr) { - ZLOGE("store null, storeId:%{public}s", meta.GetStoreAlias().c_str()); - return; - } - store->RegisterDetailProgressObserver(GetCallbacks(meta.tokenId, storeInfo.storeName)); - }; - EventCenter::GetInstance().Subscribe(CloudEvent::CLOUD_SYNC, process); - EventCenter::GetInstance().Subscribe(CloudEvent::CLEAN_DATA, process); - - EventCenter::GetInstance().Subscribe(CloudEvent::MAKE_QUERY, [](const Event& event) { - auto& evt = static_cast(event); - auto callback = evt.GetCallback(); - if (!callback) { - return; - } - auto predicate = evt.GetPredicates(); - auto rdbQuery = std::make_shared(); - rdbQuery->MakeQuery(*predicate); - rdbQuery->SetColumns(evt.GetColumns()); - callback(rdbQuery); - }); - auto compensateSyncProcess = [this] (const Event &event) { - auto &evt = static_cast(event); - DoCompensateSync(evt); - }; - EventCenter::GetInstance().Subscribe(BindEvent::COMPENSATE_SYNC, compensateSyncProcess); - EventCenter::GetInstance().Subscribe(BindEvent::RECOVER_SYNC, compensateSyncProcess); } int32_t RdbServiceImpl::ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) @@ -463,7 +420,7 @@ int RdbServiceImpl::DoSync(const RdbSyncerParam ¶m, const RdbService::Option [this, tokenId, pid, seqNum = option.seqNum](const GenDetails &result) mutable { OnAsyncComplete(tokenId, pid, seqNum, HandleGenDetails(result)); }, - syncParam); + syncParam).first; } bool RdbServiceImpl::IsNeedMetaSync(const StoreMetaData &meta, const std::vector &uuids) @@ -557,7 +514,7 @@ void RdbServiceImpl::DoCloudSync(const RdbSyncerParam ¶m, const RdbService:: }; auto mixMode = static_cast(GeneralStore::MixMode(option.mode, option.isAutoSync ? GeneralStore::AUTO_SYNC_MODE : GeneralStore::MANUAL_SYNC_MODE)); - SyncParam syncParam = { mixMode, (option.isAsync ? 0 : WAIT_TIME), option.isCompensation }; + SyncParam syncParam = { mixMode, (option.isAsync ? 0 : static_cast(WAIT_TIME)), option.isCompensation }; auto info = ChangeEvent::EventInfo(syncParam, option.isAutoSync, query, option.isAutoSync ? nullptr : option.isAsync ? asyncCallback @@ -737,10 +694,9 @@ int32_t RdbServiceImpl::BeforeOpen(RdbSyncerParam ¶m) { XCollie xcollie(__FUNCTION__, HiviewDFX::XCOLLIE_FLAG_LOG | HiviewDFX::XCOLLIE_FLAG_RECOVERY); auto meta = GetStoreMetaData(param); - auto isCreated = - MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true); + auto isCreated = MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true); if (!isCreated) { - return RDB_OK; + return RDB_NO_META; } SetReturnParam(meta, param); return RDB_OK; @@ -1053,12 +1009,18 @@ int32_t RdbServiceImpl::OnInitialize() { RegisterRdbServiceInfo(); RegisterHandler(); + RegisterEvent(); return RDB_OK; } RdbServiceImpl::~RdbServiceImpl() { DumpManager::GetInstance().RemoveHandler("FEATURE_INFO", uintptr_t(this)); + EventCenter::GetInstance().Unsubscribe(CloudEvent::CLOUD_SYNC); + EventCenter::GetInstance().Unsubscribe(CloudEvent::CLEAN_DATA); + EventCenter::GetInstance().Unsubscribe(CloudEvent::MAKE_QUERY); + EventCenter::GetInstance().Unsubscribe(BindEvent::COMPENSATE_SYNC); + EventCenter::GetInstance().Unsubscribe(BindEvent::RECOVER_SYNC); } int32_t RdbServiceImpl::NotifyDataChange(const RdbSyncerParam ¶m, const RdbChangedData &rdbChangedData, @@ -1161,7 +1123,7 @@ int32_t RdbServiceImpl::PostSearchEvent(int32_t evtId, const RdbSyncerParam& par return RDB_OK; } -int32_t RdbServiceImpl::Disable(const RdbSyncerParam& param) +int32_t RdbServiceImpl::Disable(const RdbSyncerParam ¶m) { auto tokenId = IPCSkeleton::GetCallingTokenID(); auto storeId = RemoveSuffix(param.storeName_); @@ -1169,7 +1131,7 @@ int32_t RdbServiceImpl::Disable(const RdbSyncerParam& param) return RDB_OK; } -int32_t RdbServiceImpl::Enable(const RdbSyncerParam& param) +int32_t RdbServiceImpl::Enable(const RdbSyncerParam ¶m) { auto tokenId = IPCSkeleton::GetCallingTokenID(); auto storeId = RemoveSuffix(param.storeName_); @@ -1359,4 +1321,51 @@ int32_t RdbServiceImpl::VerifyPromiseInfo(const RdbSyncerParam ¶m) } return RDB_OK; } + +void RdbServiceImpl::RegisterEvent() +{ + auto process = [this](const Event &event) { + auto &evt = static_cast(event); + auto &storeInfo = evt.GetStoreInfo(); + StoreMetaData meta(storeInfo); + meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) { + ZLOGE("meta empty, bundleName:%{public}s, storeId:%{public}s", meta.bundleName.c_str(), + meta.GetStoreAlias().c_str()); + return; + } + if (meta.storeType < StoreMetaData::STORE_RELATIONAL_BEGIN || + meta.storeType > StoreMetaData::STORE_RELATIONAL_END) { + return; + } + auto watchers = GetWatchers(meta.tokenId, meta.storeId); + auto store = AutoCache::GetInstance().GetStore(meta, watchers); + if (store == nullptr) { + ZLOGE("store null, storeId:%{public}s", meta.GetStoreAlias().c_str()); + return; + } + store->RegisterDetailProgressObserver(GetCallbacks(meta.tokenId, storeInfo.storeName)); + }; + EventCenter::GetInstance().Subscribe(CloudEvent::CLOUD_SYNC, process); + EventCenter::GetInstance().Subscribe(CloudEvent::CLEAN_DATA, process); + + EventCenter::GetInstance().Subscribe(CloudEvent::MAKE_QUERY, [](const Event &event) { + auto &evt = static_cast(event); + auto callback = evt.GetCallback(); + if (!callback) { + return; + } + auto predicate = evt.GetPredicates(); + auto rdbQuery = std::make_shared(); + rdbQuery->MakeQuery(*predicate); + rdbQuery->SetColumns(evt.GetColumns()); + callback(rdbQuery); + }); + auto compensateSyncProcess = [this](const Event &event) { + auto &evt = static_cast(event); + DoCompensateSync(evt); + }; + EventCenter::GetInstance().Subscribe(BindEvent::COMPENSATE_SYNC, compensateSyncProcess); + EventCenter::GetInstance().Subscribe(BindEvent::RECOVER_SYNC, compensateSyncProcess); +} } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h index b49d448efd11186f487e6d558acf776a03b7d4ff..34c551550afb3747fe898889910eda4881a2d63b 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -153,6 +153,8 @@ private: void RegisterHandler(); + void RegisterEvent(); + void DumpRdbServiceInfo(int fd, std::map> ¶ms); void DoCloudSync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, diff --git a/datamgr_service/services/distributeddataservice/service/test/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/BUILD.gn index 0cf3ca1a0f71b35625b004552ced4c1953e0cca0..5ed1d319f673f96a276b782b49ce6a0decdb54a6 100644 --- a/datamgr_service/services/distributeddataservice/service/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/BUILD.gn @@ -51,7 +51,7 @@ config("module_private_config") { "${relational_store_path}/interfaces/inner_api/cloud_data/include", "${relational_store_path}/interfaces/inner_api/common_type/include", ] - + cflags = [ "-Werror" ] defines = [ "TEST_ON_DEVICE", "OPENSSL_SUPPRESS_DEPRECATED", @@ -90,6 +90,7 @@ ohos_unittest("CloudDataTest") { "${data_service_path}/service/crypto/src/crypto_manager.cpp", "${data_service_path}/service/matrix/src/device_matrix.cpp", "${data_service_path}/service/matrix/src/matrix_event.cpp", + "${data_service_path}/service/permission/src/permit_delegate.cpp", "${data_service_path}/service/rdb/cache_cursor.cpp", "${data_service_path}/service/rdb/rdb_asset_loader.cpp", "${data_service_path}/service/rdb/rdb_cloud.cpp", @@ -172,6 +173,7 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/service/crypto/src/crypto_manager.cpp", "${data_service_path}/service/matrix/src/device_matrix.cpp", "${data_service_path}/service/matrix/src/matrix_event.cpp", + "${data_service_path}/service/permission/src/permit_delegate.cpp", "${data_service_path}/service/rdb/cache_cursor.cpp", "${data_service_path}/service/rdb/rdb_asset_loader.cpp", "${data_service_path}/service/rdb/rdb_cloud.cpp", @@ -443,6 +445,76 @@ ohos_unittest("KVDBGeneralStoreTest") { ] } +ohos_unittest("KVDBGeneralStoreAbnormalTest") { + module_out_path = module_output_path + sources = [ + "../common/value_proxy.cpp", + "../kvdb/kvdb_general_store.cpp", + "../rdb/rdb_cloud.cpp", + "../rdb/rdb_query.cpp", + "../waterversion/water_version_manager.cpp", + "kvdb_general_store_abnormal_test.cpp", + "mock/db_change_data_mock.cpp", + "mock/db_store_mock.cpp", + "mock/device_manager_adapter_mock.cpp", + "mock/general_watcher_mock.cpp", + "mock/kv_store_nb_delegate_mock.cpp", + ] + + include_dirs = [ + "${data_service_path}/service/common", + "${data_service_path}/service/rdb", + "${data_service_path}/service/waterversion", + "${data_service_path}/adapter/include", + "${data_service_path}/app/src", + "${data_service_path}/framework/include", + "${data_service_path}/service/bootstrap/include/", + "${data_service_path}/service/backup/include/", + "${data_service_path}/service/cloud/", + "${data_service_path}/service/config/include/", + "${data_service_path}/service/crypto/include", + "${data_service_path}/service/directory/include/", + "${data_service_path}/service/data_share/common", + "${data_service_path}/service/data_share/data", + "${data_service_path}/service/data_share/strategies", + "${data_service_path}/service/data_share/subscriber_managers", + "${data_service_path}/service/data_share", + "${data_service_path}/service/matrix/include/", + "${data_service_path}/service/kvdb", + "${data_service_path}/service/object/", + "${data_service_path}/service/permission/include", + "${data_service_path}/service/test/mock", + ] + + configs = [] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "c_utils:utils", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "relational_store:native_rdb", + ] + + deps = [ + "${data_service_path}/adapter:distributeddata_adapter", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + ] +} + ohos_unittest("RdbResultSetImplTest") { module_out_path = module_output_path sources = [ @@ -527,6 +599,7 @@ ohos_unittest("RdbServiceTest") { "-Dprotected=public", "-Wno-multichar", "-Wno-c99-designator", + "-fno-access-control", # Ignore Private Member Access Control ] external_deps = [ @@ -968,6 +1041,7 @@ ohos_unittest("DataShareServiceImplTest") { "${data_service_path}/service/data_share/sys_event_subscriber.cpp", "${data_service_path}/service/kvdb/user_delegate.cpp", "${data_service_path}/service/permission/src/permit_delegate.cpp", + "data_share_obs_proxy_test.cpp", "data_share_profile_config_test.cpp", "data_share_service_impl_test.cpp", "data_share_service_stub_test.cpp", @@ -988,6 +1062,7 @@ ohos_unittest("DataShareServiceImplTest") { ] external_deps = [ + "ability_base:base", "ability_base:want", "ability_base:zuri", "ability_runtime:dataobs_manager", @@ -1115,6 +1190,45 @@ ohos_unittest("DumpHelperTest") { ] } +ohos_unittest("UdmfServiceImplTest") { + module_out_path = module_output_path + sources = [ + "${data_service_path}/framework/feature/feature_system.cpp", + "udmf_service_impl_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/service/udmf/store", + "${data_service_path}/service/udmf", + "${data_service_path}/framework/include", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + deps = [ + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/udmf:udmf_server", + ] + + external_deps = [ + "ability_runtime:uri_permission_mgr", + "access_token:libaccesstoken_sdk", + "app_file_service:remote_file_share_native", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gtest_main", + "hilog:libhilog", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "relational_store:native_rdb", + "udmf:udmf_client", + ] +} + ############################################################################### group("unittest") { testonly = true @@ -1134,6 +1248,7 @@ group("unittest") { ":DeviceMatrixTest", ":DirectoryManagerTest", ":DumpHelperTest", + ":KVDBGeneralStoreAbnormalTest", ":KVDBGeneralStoreTest", ":KvdbServiceImplTest", ":MetaDataTest", @@ -1145,6 +1260,7 @@ group("unittest") { ":RdbResultSetImplTest", ":RdbServiceTest", ":UdmfRunTimeStoreTest", + ":UdmfServiceImplTest", ":ValueProxyServiceTest", ":WaterVersionManagerTest", ] diff --git a/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp b/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp index e35e1efce3db3c5cd273959e66f73be2b9bf04cc..29932a6d3d4bd873567fc3c1dad3081f1b895121 100644 --- a/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -2034,5 +2034,42 @@ HWTEST_F(CloudDataTest, IsAllSwitchOff, TestSize.Level0) auto ret = cloudInfo.IsAllSwitchOff(); EXPECT_FALSE(ret); } + +/** +* @tc.name: GetMinExpireTime +* @tc.desc: Test GetMinExpireTime. +* @tc.type: FUNC +* @tc.require: + */ +HWTEST_F(CloudDataTest, GetMinExpireTime, TestSize.Level0) +{ + uint64_t expire = 0; + Subscription sub; + sub.expiresTime.insert_or_assign(TEST_CLOUD_BUNDLE, expire); + sub.GetMinExpireTime(); + expire = 24 * 60 * 60 * 1000; + sub.expiresTime.insert_or_assign(TEST_CLOUD_BUNDLE, expire); + expire = 24 * 60 * 60; + sub.expiresTime.insert_or_assign("test_cloud_bundleName1", expire); + EXPECT_EQ(sub.GetMinExpireTime(), expire); +} + + /** +* @tc.name: GetTableNames +* @tc.desc: Test GetTableNames. +* @tc.type: FUNC +* @tc.require: + */ +HWTEST_F(CloudDataTest, GetTableNames, TestSize.Level0) +{ + SchemaMeta::Database database; + SchemaMeta::Table table; + table.name = "test_cloud_table_name"; + table.alias = "test_cloud_table_alias"; + table.sharedTableName = "test_share_table_name"; + database.tables.emplace_back(table); + auto tableNames = database.GetTableNames(); + EXPECT_EQ(tableNames.size(), 2); +} } // namespace DistributedDataTest } // namespace OHOS::Test \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/test/directory_manager_test.cpp b/datamgr_service/services/distributeddataservice/service/test/directory_manager_test.cpp index ce979c4fb33722da5127c852bf565fbff8f4edfa..c763765ab1544cf3ab8e5df7d8b395f666eb94b1 100644 --- a/datamgr_service/services/distributeddataservice/service/test/directory_manager_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/directory_manager_test.cpp @@ -98,9 +98,7 @@ HWTEST_F(DirectoryManagerTest, GetBundleStorePath, TestSize.Level0) metaData.area = 1; metaData.tokenId = AccessTokenKit::GetHapTokenID(100, "ohos.test.demo", 0); metaData.storeType = KvStoreType::SINGLE_VERSION; - HapTokenInfo tokenInfo; - AccessTokenKit::GetHapTokenInfo(metaData.tokenId, tokenInfo); - metaData.appId = tokenInfo.appID; + metaData.appId = "ohos.test.demo_09AEF01D"; auto path = DirectoryManager::GetInstance().GetStorePath(metaData); EXPECT_EQ(path, metaData.dataDir); } @@ -165,9 +163,7 @@ HWTEST_F(DirectoryManagerTest, GetRDBBackupPath, TestSize.Level0) metaData.area = 1; metaData.storeType = 10; metaData.tokenId = AccessTokenKit::GetHapTokenID(10, "ohos.test.demo", 0); - HapTokenInfo tokenInfo; - AccessTokenKit::GetHapTokenInfo(metaData.tokenId, tokenInfo); - metaData.appId = tokenInfo.appID; + metaData.appId = "ohos.test.demo_09AEF01D"; metaData.storeId = "testStpre"; auto path = DirectoryManager::GetInstance().GetStoreBackupPath(metaData); EXPECT_EQ(path, metaData.dataDir + "/rdb/backup/testStpre"); @@ -189,9 +185,7 @@ HWTEST_F(DirectoryManagerTest, GetKVDBBackupPath, TestSize.Level0) metaData.area = 1; metaData.storeType = 0; metaData.tokenId = AccessTokenKit::GetHapTokenID(10, "ohos.test.demo", 0); - HapTokenInfo tokenInfo; - AccessTokenKit::GetHapTokenInfo(metaData.tokenId, tokenInfo); - metaData.appId = tokenInfo.appID; + metaData.appId = "ohos.test.demo_09AEF01D"; metaData.storeId = "testStpre"; auto path = DirectoryManager::GetInstance().GetStoreBackupPath(metaData); EXPECT_EQ(path, metaData.dataDir + "/backup/testStpre"); diff --git a/datamgr_service/services/distributeddataservice/service/test/kvdb_general_store_abnormal_test.cpp b/datamgr_service/services/distributeddataservice/service/test/kvdb_general_store_abnormal_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6d46bbb9727ae8fa7f139d0c195cf2636c3b6c1 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/test/kvdb_general_store_abnormal_test.cpp @@ -0,0 +1,269 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#define LOG_TAG "KVDBGeneralStoreAbnormalTest" + +#include "kvdb_general_store.h" + +#include +#include +#include +#include + +#include "bootstrap.h" +#include "cloud/asset_loader.h" +#include "cloud/cloud_db.h" +#include "cloud/schema_meta.h" +#include "crypto_manager.h" +#include "device_manager_adapter_mock.h" +#include "kv_store_nb_delegate_mock.h" +#include "kvdb_query.h" +#include "log_print.h" +#include "metadata/meta_data_manager.h" +#include "metadata/secret_key_meta_data.h" +#include "metadata/store_meta_data.h" +#include "metadata/store_meta_data_local.h" +#include "mock/db_store_mock.h" +#include "mock/general_watcher_mock.h" + +using namespace testing::ext; +using namespace DistributedDB; +using namespace OHOS::DistributedData; +using DBStoreMock = OHOS::DistributedData::DBStoreMock; +using StoreMetaData = OHOS::DistributedData::StoreMetaData; +using SecurityLevel = OHOS::DistributedKv::SecurityLevel; +using KVDBGeneralStore = OHOS::DistributedKv::KVDBGeneralStore; +using DMAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using DBProcessCB = std::function &processes)>; +namespace OHOS::Test { +namespace DistributedDataTest { +class KVDBGeneralStoreAbnormalTest : public testing::Test { +public: + static inline std::shared_ptr deviceManagerAdapterMock = nullptr; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + +protected: + static constexpr const char *bundleName = "test_distributeddata"; + static constexpr const char *storeName = "test_service_meta"; + + void InitMetaData(); + static std::shared_ptr dbStoreMock_; + StoreMetaData metaData_; +}; + +std::shared_ptr KVDBGeneralStoreAbnormalTest::dbStoreMock_ = std::make_shared(); + +void KVDBGeneralStoreAbnormalTest::InitMetaData() +{ + metaData_.bundleName = bundleName; + metaData_.appId = bundleName; + metaData_.user = "0"; + metaData_.area = OHOS::DistributedKv::EL1; + metaData_.instanceId = 0; + metaData_.isAutoSync = true; + metaData_.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; + metaData_.storeId = storeName; + metaData_.dataDir = "/data/service/el1/public/database/" + std::string(bundleName) + "/kvdb"; + metaData_.securityLevel = SecurityLevel::S2; +} + +void KVDBGeneralStoreAbnormalTest::SetUpTestCase(void) +{ + deviceManagerAdapterMock = std::make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock; +} + +void KVDBGeneralStoreAbnormalTest::TearDownTestCase() +{ + deviceManagerAdapterMock = nullptr; +} + +void KVDBGeneralStoreAbnormalTest::SetUp() +{ + Bootstrap::GetInstance().LoadDirectory(); + InitMetaData(); +} + +void KVDBGeneralStoreAbnormalTest::TearDown() {} + +/** +* @tc.name: GetDBOption +* @tc.desc: GetDBOption test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreAbnormalTest, GetDBOptionTest001, TestSize.Level0) +{ + metaData_.isEncrypt = true; + metaData_.appId = Bootstrap::GetInstance().GetProcessLabel(); + auto dbPassword = KVDBGeneralStore::GetDBPassword(metaData_); + auto dbOption = KVDBGeneralStore::GetDBOption(metaData_, dbPassword); + EXPECT_EQ(dbOption.compressionRate, 10); + EXPECT_EQ(dbOption.conflictResolvePolicy, DistributedDB::LAST_WIN); +} + +/** +* @tc.name: SetEqualIdentifier +* @tc.desc: sameAccountDevs & defaultAccountDevs != empty +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreAbnormalTest, SetEqualIdentifier, TestSize.Level0) +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + std::vector uuids{"uuidtest01"}; + KvStoreNbDelegateMock mockDelegate; + mockDelegate.taskCountMock_ = 1; + store->delegate_ = &mockDelegate; + EXPECT_NE(store->delegate_, nullptr); + EXPECT_CALL(*deviceManagerAdapterMock, ToUUID(testing::_)).WillOnce(testing::Return(uuids)); + auto uuids1 = DMAdapter::ToUUID(DMAdapter::GetInstance().GetRemoteDevices()); + EXPECT_CALL(*deviceManagerAdapterMock, ToUUID(testing::_)).WillOnce(testing::Return(uuids)); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest01")) + .WillOnce(testing::Return(false)).WillOnce(testing::Return(false)); + store->SetEqualIdentifier(metaData_.appId, metaData_.storeId); + EXPECT_EQ(uuids1, uuids); + store->delegate_ = nullptr; + delete store; +} + +/** +* @tc.name: GetIdentifierParams +* @tc.desc: GetIdentifierParams abnormal branch. +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreAbnormalTest, GetIdentifierParams, TestSize.Level0) +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + std::vector sameAccountDevs{}; + std::vector uuids{"uuidtest01"}; + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest01")) + .WillOnce(testing::Return(true)).WillOnce(testing::Return(true)); + store->GetIdentifierParams(sameAccountDevs, uuids, 0); // test + for (const auto &devId : uuids) { + EXPECT_EQ(DMAdapter::GetInstance().IsOHOSType(devId), true); + EXPECT_EQ(DMAdapter::GetInstance().GetAuthType(devId), 0); // NO_ACCOUNT + } + EXPECT_EQ(sameAccountDevs.empty(), true); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest01")) + .WillOnce(testing::Return(false)).WillOnce(testing::Return(false)); + store->GetIdentifierParams(sameAccountDevs, uuids, 1); // test + for (const auto &devId : uuids) { + EXPECT_EQ(DMAdapter::GetInstance().IsOHOSType(devId), false); + EXPECT_EQ(DMAdapter::GetInstance().GetAuthType(devId), 0); // NO_ACCOUNT + } + EXPECT_EQ(sameAccountDevs.empty(), true); + store->delegate_ = nullptr; + delete store; +} + +/** +* @tc.name: ConvertStatus +* @tc.desc: ConvertStatus test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreAbnormalTest, ConvertStatus, TestSize.Level0) +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + auto status = store->ConvertStatus(DistributedDB::DBStatus::BUTT_STATUS); // test + EXPECT_EQ(status, DistributedData::GeneralError::E_ERROR); + store->delegate_ = nullptr; + delete store; +} + +/** +* @tc.name: GetDBProcessCB +* @tc.desc: GetDBProcessCB test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreAbnormalTest, GetDBProcessCB, TestSize.Level0) +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + GeneralStore::DetailAsync async; + EXPECT_EQ(async, nullptr); + auto process = store->GetDBProcessCB(async); + EXPECT_NE(process, nullptr); + auto asyncs = [](const GenDetails &result) {}; + EXPECT_NE(asyncs, nullptr); + process = store->GetDBProcessCB(asyncs); + EXPECT_NE(process, nullptr); + store->delegate_ = nullptr; + delete store; +} + +/** +* @tc.name: SetDBPushDataInterceptor +* @tc.desc: SetDBPushDataInterceptor test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreAbnormalTest, SetDBPushDataInterceptor, TestSize.Level0) //SINGLE_VERSION +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + KvStoreNbDelegateMock mockDelegate; + store->delegate_ = &mockDelegate; + EXPECT_NE(store->delegate_, nullptr); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest01")).WillOnce(testing::Return(false)); + store->SetDBPushDataInterceptor(metaData_.storeType); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest01")).WillOnce(testing::Return(true)); + store->SetDBPushDataInterceptor(metaData_.storeType); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest01")).WillOnce(testing::Return(true)); + store->SetDBPushDataInterceptor(DistributedKv::KvStoreType::DEVICE_COLLABORATION); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest01")).WillOnce(testing::Return(false)); + store->SetDBPushDataInterceptor(DistributedKv::KvStoreType::DEVICE_COLLABORATION); + EXPECT_NE(metaData_.storeType, DistributedKv::KvStoreType::DEVICE_COLLABORATION); + store->delegate_ = nullptr; + delete store; +} + +/** +* @tc.name: SetDBReceiveDataInterceptor +* @tc.desc: SetDBReceiveDataInterceptor test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreAbnormalTest, SetDBReceiveDataInterceptor, TestSize.Level0) //SINGLE_VERSION +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + KvStoreNbDelegateMock mockDelegate; + store->delegate_ = &mockDelegate; + EXPECT_NE(store->delegate_, nullptr); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest_1")).WillOnce(testing::Return(false)); + store->SetDBReceiveDataInterceptor(metaData_.storeType); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest_1")).WillOnce(testing::Return(true)); + store->SetDBReceiveDataInterceptor(metaData_.storeType); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest_1")).WillOnce(testing::Return(true)); + store->SetDBReceiveDataInterceptor(DistributedKv::KvStoreType::DEVICE_COLLABORATION); + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType("uuidtest_1")).WillOnce(testing::Return(false)); + store->SetDBReceiveDataInterceptor(DistributedKv::KvStoreType::DEVICE_COLLABORATION); + EXPECT_NE(metaData_.storeType, DistributedKv::KvStoreType::DEVICE_COLLABORATION); + store->delegate_ = nullptr; + delete store; +} +} // namespace DistributedDataTest +} // namespace OHOS::Test \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/test/kvdb_general_store_test.cpp b/datamgr_service/services/distributeddataservice/service/test/kvdb_general_store_test.cpp index b8c4568324e1cfd9980bf2a1234a8e489964e828..cd8dd577393d12365d96d0b7922e0fb7bab352a3 100644 --- a/datamgr_service/services/distributeddataservice/service/test/kvdb_general_store_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/kvdb_general_store_test.cpp @@ -25,6 +25,7 @@ #include "cloud/cloud_db.h" #include "cloud/schema_meta.h" #include "crypto_manager.h" +#include "device_manager_adapter.h" #include "kv_store_nb_delegate_mock.h" #include "kvdb_query.h" #include "log_print.h" @@ -42,6 +43,7 @@ using DBStoreMock = OHOS::DistributedData::DBStoreMock; using StoreMetaData = OHOS::DistributedData::StoreMetaData; using SecurityLevel = OHOS::DistributedKv::SecurityLevel; using KVDBGeneralStore = OHOS::DistributedKv::KVDBGeneralStore; +using DMAdapter = OHOS::DistributedData::DeviceManagerAdapter; namespace OHOS::Test { namespace DistributedDataTest { class KVDBGeneralStoreTest : public testing::Test { @@ -325,9 +327,9 @@ HWTEST_F(KVDBGeneralStoreTest, SyncTest, TestSize.Level0) SyncParam syncParam{}; syncParam.mode = mixMode; auto ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); - EXPECT_NE(ret, GeneralError::E_OK); - ret = store->Close(); - EXPECT_EQ(ret, GeneralError::E_OK); + EXPECT_NE(ret.first, GeneralError::E_OK); + auto status = store->Close(); + EXPECT_EQ(status, GeneralError::E_OK); } /** @@ -359,21 +361,61 @@ HWTEST_F(KVDBGeneralStoreTest, BindTest, TestSize.Level0) std::shared_ptr loaders = std::make_shared(); GeneralStore::BindInfo bindInfo2(dbs, loaders); bindInfos[key] = bindInfo2; - EXPECT_EQ(store->IsBound(), false); + EXPECT_EQ(store->IsBound(key), false); ret = store->Bind(database, bindInfos, config); EXPECT_EQ(ret, GeneralError::E_ALREADY_CLOSED); - store->isBound_ = false; + store->users_.clear(); KvStoreNbDelegateMock mockDelegate; store->delegate_ = &mockDelegate; EXPECT_NE(store->delegate_, nullptr); - EXPECT_EQ(store->IsBound(), false); + EXPECT_EQ(store->IsBound(key), false); + ret = store->Bind(database, bindInfos, config); + EXPECT_EQ(ret, GeneralError::E_OK); + + EXPECT_EQ(store->IsBound(key), true); ret = store->Bind(database, bindInfos, config); EXPECT_EQ(ret, GeneralError::E_OK); +} + +/** +* @tc.name: BindWithDifferentUsersTest +* @tc.desc: Bind test the functionality of different users. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Hollokin +*/ +HWTEST_F(KVDBGeneralStoreTest, BindWithDifferentUsersTest, TestSize.Level0) +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + KvStoreNbDelegateMock mockDelegate; + store->delegate_ = &mockDelegate; + EXPECT_NE(store->delegate_, nullptr); + ASSERT_NE(store, nullptr); + DistributedData::Database database; + std::map bindInfos; + GeneralStore::CloudConfig config; + + std::shared_ptr dbs = std::make_shared(); + std::shared_ptr loaders = std::make_shared(); + GeneralStore::BindInfo bindInfo(dbs, loaders); + uint32_t key0 = 100; + uint32_t key1 = 101; + bindInfos[key0] = bindInfo; + bindInfos[key1] = bindInfo; + EXPECT_EQ(store->IsBound(key0), false); + EXPECT_EQ(store->IsBound(key1), false); + auto ret = store->Bind(database, bindInfos, config); + EXPECT_EQ(ret, GeneralError::E_OK); + EXPECT_EQ(store->IsBound(key0), true); + EXPECT_EQ(store->IsBound(key1), true); - EXPECT_EQ(store->IsBound(), true); + uint32_t key2 = 102; + bindInfos[key2] = bindInfo; + EXPECT_EQ(store->IsBound(key2), false); ret = store->Bind(database, bindInfos, config); EXPECT_EQ(ret, GeneralError::E_OK); + EXPECT_EQ(store->IsBound(key2), true); } /** @@ -426,6 +468,26 @@ HWTEST_F(KVDBGeneralStoreTest, CloudSync, TestSize.Level0) EXPECT_EQ(ret, DBStatus::OK); } +/** +* @tc.name: GetIdentifierParams +* @tc.desc: GetIdentifierParams test. +* @tc.type: FUNC +* @tc.require: +* @tc.author: wangbin +*/ +HWTEST_F(KVDBGeneralStoreTest, GetIdentifierParams, TestSize.Level0) +{ + auto store = new (std::nothrow) KVDBGeneralStore(metaData_); + std::vector sameAccountDevs{}; + std::vector uuids{"uuidtest01", "uuidtest02", "uuidtest03"}; + store->GetIdentifierParams(sameAccountDevs, uuids, 0); // NO_ACCOUNT + for (const auto &devId : uuids) { + EXPECT_EQ(DMAdapter::GetInstance().IsOHOSType(devId), false); + EXPECT_EQ(DMAdapter::GetInstance().GetAuthType(devId), 0); // NO_ACCOUNT + } + EXPECT_EQ(sameAccountDevs.empty(), false); +} + /** * @tc.name: Sync * @tc.desc: Sync test the functionality of different branches. @@ -449,43 +511,43 @@ HWTEST_F(KVDBGeneralStoreTest, Sync, TestSize.Level0) KvStoreNbDelegateMock mockDelegate; store->delegate_ = &mockDelegate; auto ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); - EXPECT_EQ(ret, GeneralError::E_NOT_SUPPORT); + EXPECT_EQ(ret.first, GeneralError::E_NOT_SUPPORT); GeneralStore::StoreConfig storeConfig; storeConfig.enableCloud_ = true; store->SetConfig(storeConfig); ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); - EXPECT_EQ(ret, GeneralError::E_OK); + EXPECT_EQ(ret.first, GeneralError::E_OK); syncMode = GeneralStore::SyncMode::NEARBY_END; mixMode = GeneralStore::MixMode(syncMode, highMode); syncParam.mode = mixMode; ret = store->Sync({}, query, [](const GenDetails &result) {}, syncParam); - EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS); + EXPECT_EQ(ret.first, GeneralError::E_INVALID_ARGS); std::vector devices = { "device1", "device2" }; syncMode = GeneralStore::SyncMode::NEARBY_SUBSCRIBE_REMOTE; mixMode = GeneralStore::MixMode(syncMode, highMode); syncParam.mode = mixMode; ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam); - EXPECT_EQ(ret, GeneralError::E_OK); + EXPECT_EQ(ret.first, GeneralError::E_OK); syncMode = GeneralStore::SyncMode::NEARBY_UNSUBSCRIBE_REMOTE; mixMode = GeneralStore::MixMode(syncMode, highMode); syncParam.mode = mixMode; ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam); - EXPECT_EQ(ret, GeneralError::E_OK); + EXPECT_EQ(ret.first, GeneralError::E_OK); syncMode = GeneralStore::SyncMode::NEARBY_PULL_PUSH; mixMode = GeneralStore::MixMode(syncMode, highMode); syncParam.mode = mixMode; ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam); - EXPECT_EQ(ret, GeneralError::E_OK); + EXPECT_EQ(ret.first, GeneralError::E_OK); syncMode = GeneralStore::SyncMode::MODE_BUTT; mixMode = GeneralStore::MixMode(syncMode, highMode); syncParam.mode = mixMode; ret = store->Sync(devices, query, [](const GenDetails &result) {}, syncParam); - EXPECT_EQ(ret, GeneralError::E_INVALID_ARGS); + EXPECT_EQ(ret.first, GeneralError::E_INVALID_ARGS); } /** diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp index 7b6b52b78160c6f1a6819fe00674476c54e66cdb..c89d6d954c41cbc64629183b999cf83308c7ffec 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp @@ -167,8 +167,7 @@ DBStatus DBStoreMock::Export(const std::string &filePath, const CipherPassword & return NOT_SUPPORT; } -DBStatus DBStoreMock::Import(const std::string &filePath, const CipherPassword &passwd, - bool isNeedIntegrityCheck) +DBStatus DBStoreMock::Import(const std::string &filePath, const CipherPassword &passwd, bool isNeedIntegrityCheck) { return NOT_SUPPORT; } diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h index 454e5d5ff9866c97ef9e5364d8996a5a65ff6b8c..5c7e0ff325d364389a1ae0027cbeecac8f064775 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h +++ b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h @@ -78,8 +78,7 @@ public: DBStatus SetConflictNotifier(int conflictType, const KvStoreNbConflictNotifier ¬ifier) override; DBStatus Rekey(const CipherPassword &password) override; DBStatus Export(const std::string &filePath, const CipherPassword &passwd, bool force) override; - DBStatus Import(const std::string &filePath, const CipherPassword &passwd, - bool isNeedIntegrityCheck = false) override; + DBStatus Import(const std::string &filePath, const CipherPassword &passwd, bool isNeedIntegrityCheck) override; DBStatus StartTransaction() override; DBStatus Commit() override; DBStatus Rollback() override; diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp b/datamgr_service/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..015bec1fe28658c22081425e53581a8a4447d9f2 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_adapter_mock.h" + +namespace OHOS::DistributedData { +OHOS::DistributedData::DeviceManagerAdapter &OHOS::DistributedData::DeviceManagerAdapter::GetInstance() +{ + static DeviceManagerAdapter dmAdapter; + return dmAdapter; +} + +OHOS::DistributedData::DeviceManagerAdapter::DeviceManagerAdapter() + : cloudDmInfo({ "cloudDeviceId", "cloudDeviceName", 0, "cloudNetworkId", 0 }) +{} + +std::vector OHOS::DistributedData::DeviceManagerAdapter::ToUUID(std::vector devices) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + std::vector vec; + return vec; + } + return BDeviceManagerAdapter::deviceManagerAdapter->ToUUID(devices); +} + +bool OHOS::DistributedData::DeviceManagerAdapter::IsOHOSType(const std::string &id) +{ + if (BDeviceManagerAdapter::deviceManagerAdapter == nullptr) { + return false; + } + return BDeviceManagerAdapter::deviceManagerAdapter->IsOHOSType(id); +} +} \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h b/datamgr_service/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..e302e40032c17dd6978b477f0c48077a4bc12722 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_DISTRIBUTEDDATA_SERVICE_TEST_BDEVICE_MANAGER_ADAPTER_MOCK_H +#define OHOS_DISTRIBUTEDDATA_SERVICE_TEST_BDEVICE_MANAGER_ADAPTER_MOCK_H + +#include +#include "device_manager_adapter.h" +#include "commu_types.h" + +namespace OHOS { +namespace DistributedData { +using namespace OHOS::AppDistributedKv; +class BDeviceManagerAdapter { +public: + virtual bool IsOHOSType(const std::string &) = 0; + virtual std::vector ToUUID(std::vector) = 0; + static inline std::shared_ptr deviceManagerAdapter = nullptr; + BDeviceManagerAdapter() = default; + virtual ~BDeviceManagerAdapter() = default; +}; + +class DeviceManagerAdapterMock : public BDeviceManagerAdapter { +public: + MOCK_METHOD(bool, IsOHOSType, (const std::string &)); + MOCK_METHOD(std::vector, ToUUID, (std::vector)); +}; + +} // namespace DistributedData +} // namespace OHOS +#endif //OHOS_DISTRIBUTEDDATA_SERVICE_TEST_BDEVICE_MANAGER_ADAPTER_MOCK_H diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.cpp b/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.cpp index 90e945f57448f76057398cf5715bc6d772630ee7..03ca21d297a752356a097152a827e10c09185ab0 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.cpp @@ -31,7 +31,7 @@ int32_t GeneralStoreMock::Bind(Database &database, const std::map &trackerColNames, const std::string &extendColName, bool isForceUpgrade) + const std::set &trackerColNames, const std::set &extendColNames, bool isForceUpgrade) { return 0; } @@ -79,9 +79,10 @@ std::pair> GeneralStoreMock::Query(const std::s return {GeneralError::E_NOT_SUPPORT, nullptr}; } -int32_t GeneralStoreMock::Sync(const Devices &devices, GenQuery &query, DetailAsync async, SyncParam &syncParm) +std::pair GeneralStoreMock::Sync(const Devices &devices, GenQuery &query, + DetailAsync async, const SyncParam &syncParm) { - return 0; + return { GeneralError::E_OK, 0 }; } std::pair> GeneralStoreMock::PreSharing(GenQuery &query) @@ -175,6 +176,7 @@ void GeneralStoreMock::SetExecutor(std::shared_ptr executor) { return; } + int32_t GeneralStoreMock::OnChange(const GeneralWatcher::Origin &origin, const GeneralWatcher::PRIFields &primaries, GeneralWatcher::ChangeInfo &&changeInfo) { diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.h b/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.h index 401417b8bdd8bb61a936f3335012576bfb87f11b..3b343c14ff34d9f87e14f8f36f863d0d196f028d 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.h +++ b/datamgr_service/services/distributeddataservice/service/test/mock/general_store_mock.h @@ -36,12 +36,12 @@ public: bool IsValid(); int32_t Bind(Database &database, const std::map &bindInfos, const CloudConfig &config) override; - bool IsBound() override; + bool IsBound(uint32_t user) override; int32_t Execute(const std::string &table, const std::string &sql) override; int32_t SetDistributedTables( const std::vector &tables, int32_t type, const std::vector &references) override; int32_t SetTrackerTable(const std::string &tableName, const std::set &trackerColNames, - const std::string &extendColName, bool isForceUpgrade = false) override; + const std::set &extendColNames, bool isForceUpgrade = false) override; int32_t Insert(const std::string &table, VBuckets &&values) override; int32_t Update(const std::string &table, const std::string &setSql, Values &&values, const std::string &whereSql, Values &&conditions) override; @@ -50,7 +50,8 @@ public: std::pair> Query(const std::string &table, const std::string &sql, Values &&args) override; std::pair> Query(const std::string &table, GenQuery &query) override; - int32_t Sync(const Devices &devices, GenQuery &query, DetailAsync async, SyncParam &syncParm) override; + std::pair Sync(const Devices &devices, GenQuery &query, DetailAsync async, + const SyncParam &syncParm) override; std::pair> PreSharing(GenQuery &query) override; int32_t Clean(const std::vector &devices, int32_t mode, const std::string &tableName) override; int32_t Watch(int32_t origin, Watcher &watcher) override; diff --git a/datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp b/datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp index 0405b829469e604611e5848df3acb6d1d67d7fea..c865cf9e54adbe4f01edeb90da059a45d977e48f 100644 --- a/datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/object_asset_machine_test.cpp @@ -204,11 +204,11 @@ HWTEST_F(ObjectAssetMachineTest, StatusUpload002, TestSize.Level0) .assetName = "asset_" + timestamp + ".jpg", }; StoreInfo storeInfo { - .tokenId = time, + .tokenId = static_cast(time), .bundleName = "bundleName_" + timestamp, .storeName = "store_" + timestamp, - .instanceId = time, - .user = time, + .instanceId = static_cast(time), + .user = static_cast(time), }; ChangedAssetInfo changedAssetInfo(asset, bindInfo, storeInfo); std::pair changedAsset{ "device_" + timestamp, asset }; diff --git a/datamgr_service/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/datamgr_service/services/distributeddataservice/service/test/rdb_general_store_test.cpp index 6697dae26ee74c0766a53abce35375daba9938c1..488ec36fdc1305cc395e4e2c886fa7faf20e0c61 100644 --- a/datamgr_service/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -393,7 +393,7 @@ HWTEST_F(RdbGeneralStoreTest, Close, TestSize.Level1) { auto store = new (std::nothrow) RdbGeneralStore(metaData_); ASSERT_NE(store, nullptr); - auto result = store->IsBound(); + auto result = store->IsBound(std::stoi(metaData_.user)); EXPECT_EQ(result, false); EXPECT_EQ(store->delegate_, nullptr); auto ret = store->Close(); @@ -726,12 +726,12 @@ HWTEST_F(RdbGeneralStoreTest, Sync, TestSize.Level1) GeneralStore::DetailAsync async; SyncParam syncParam; auto result = store->Sync(devices, query, async, syncParam); - EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); + EXPECT_EQ(result.first, GeneralError::E_ALREADY_CLOSED); MockRelationalStoreDelegate mockDelegate; store->delegate_ = &mockDelegate; result = store->Sync(devices, query, async, syncParam); - EXPECT_EQ(result, GeneralError::E_OK); + EXPECT_EQ(result.first, GeneralError::E_OK); } /** @@ -936,17 +936,17 @@ HWTEST_F(RdbGeneralStoreTest, SetTrackerTable, TestSize.Level1) ASSERT_NE(store, nullptr); std::string tableName = "tableName"; std::set trackerColNames = { "col1", "col2" }; - std::string extendColName = "extendColName"; - auto result = store->SetTrackerTable(tableName, trackerColNames, extendColName); + std::set extendColNames = { "extendColName1", "extendColName2" }; + auto result = store->SetTrackerTable(tableName, trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_ALREADY_CLOSED); MockRelationalStoreDelegate mockDelegate; store->delegate_ = &mockDelegate; - result = store->SetTrackerTable(tableName, trackerColNames, extendColName); + result = store->SetTrackerTable(tableName, trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_OK); - result = store->SetTrackerTable("WITH_INVENTORY_DATA", trackerColNames, extendColName); + result = store->SetTrackerTable("WITH_INVENTORY_DATA", trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_WITH_INVENTORY_DATA); - result = store->SetTrackerTable("test", trackerColNames, extendColName); + result = store->SetTrackerTable("test", trackerColNames, extendColNames); EXPECT_EQ(result, GeneralError::E_ERROR); } @@ -1019,5 +1019,165 @@ HWTEST_F(RdbGeneralStoreTest, QuerySql, TestSize.Level1) EXPECT_EQ(err1, GeneralError::E_ERROR); EXPECT_TRUE(result2.empty()); } + +/** +* @tc.name: BuildSqlWhenCloumnEmpty +* @tc.desc: test buildsql method when cloumn empty +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenCloumnEmpty, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + std::string table = "mock_table"; + std::string statement = "mock_statement"; + std::vector columns; + std::string expectSql = "select cloud_gid from naturalbase_rdb_aux_mock_table_log, (select rowid from " + "mock_tablemock_statement) where data_key = rowid"; + std::string resultSql = store->BuildSql(table, statement, columns); + EXPECT_EQ(resultSql, expectSql); +} + +/** +* @tc.name: BuildSqlWhenParamValid +* @tc.desc: test buildsql method when param valid +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, BuildSqlWhenParamValid, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + std::string table = "mock_table"; + std::string statement = "mock_statement"; + std::vector columns; + columns.push_back("mock_column_1"); + columns.push_back("mock_column_2"); + std::string expectSql = "select cloud_gid, mock_column_1, mock_column_2 from naturalbase_rdb_aux_mock_table_log, " + "(select rowid, mock_column_1, mock_column_2 from mock_tablemock_statement) where " + "data_key = rowid"; + std::string resultSql = store->BuildSql(table, statement, columns); + EXPECT_EQ(resultSql, expectSql); +} + +/** +* @tc.name: GetWaterVersionTest +* @tc.desc: GetWaterVersion test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, GetWaterVersionTest, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + std::string deviceId = ""; + std::vector expected = {}; + std::vector actual = store->GetWaterVersion(deviceId); + EXPECT_EQ(expected, actual); + deviceId = "mock_deviceId"; + actual = store->GetWaterVersion(deviceId); + EXPECT_EQ(expected, actual); +} + +/** +* @tc.name: LockAndUnLockCloudDBTest +* @tc.desc: lock and unlock cloudDB test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, LockAndUnLockCloudDBTest, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + auto result = store->LockCloudDB(); + EXPECT_EQ(result.first, 1); + EXPECT_EQ(result.second, 0); + auto unlockResult = store->UnLockCloudDB(); + EXPECT_EQ(unlockResult, 1); +} + +/** +* @tc.name: InFinishedTest +* @tc.desc: isFinished test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, InFinishedTest, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + DistributedRdb::RdbGeneralStore::SyncId syncId = 1; + bool isFinished = store->IsFinished(syncId); + EXPECT_TRUE(isFinished); +} + +/** +* @tc.name: GetRdbCloudTest +* @tc.desc: getRdbCloud test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, GetRdbCloudTest, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + auto rdbCloud = store->GetRdbCloud(); + EXPECT_EQ(rdbCloud, nullptr); +} + +/** +* @tc.name: RegisterDetailProgressObserverTest +* @tc.desc: RegisterDetailProgressObserver test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, RegisterDetailProgressObserverTest, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + DistributedData::GeneralStore::DetailAsync async; + auto result = store->RegisterDetailProgressObserver(async); + EXPECT_EQ(result, GeneralError::E_OK); +} + +/** +* @tc.name: GetFinishTaskTest +* @tc.desc: GetFinishTask test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, GetFinishTaskTest, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + DistributedRdb::RdbGeneralStore::SyncId syncId = 1; + auto result = store->GetFinishTask(syncId); + ASSERT_NE(result, nullptr); +} + +/** +* @tc.name: GetCBTest +* @tc.desc: GetCB test +* @tc.type: FUNC +* @tc.require: +* @tc.author: SQL +*/ +HWTEST_F(RdbGeneralStoreTest, GetCBTest, TestSize.Level1) +{ + auto store = new (std::nothrow) RdbGeneralStore(metaData_); + ASSERT_NE(store, nullptr); + DistributedRdb::RdbGeneralStore::SyncId syncId = 1; + auto result = store->GetCB(syncId); + ASSERT_NE(result, nullptr); +} } // namespace DistributedRDBTest } // namespace OHOS::Test \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/test/udmf_service_impl_test.cpp b/datamgr_service/services/distributeddataservice/service/test/udmf_service_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b06a2616ff5fac1bb68c0ada607ae2c1c7f95b8 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/test/udmf_service_impl_test.cpp @@ -0,0 +1,200 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#define LOG_TAG "UdmfServiceImplTest" +#include "udmf_service_impl.h" +#include "gtest/gtest.h" +#include "error_code.h" +#include "text.h" + +using namespace OHOS::DistributedData; +namespace OHOS::UDMF { +using namespace testing::ext; +class UdmfServiceImplTest : public testing::Test { +public: + static void SetUpTestCase(void) {} + static void TearDownTestCase(void) {} + void SetUp() {} + void TearDown() {} +}; + +/** +* @tc.name: SaveData001 +* @tc.desc: Abnormal test of SaveData, unifiedData is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, SaveData001, TestSize.Level1) +{ + CustomOption option; + UnifiedData data; + std::string key = ""; + option.intention = UD_INTENTION_BASE; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.SaveData(option, data, key); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: RetrieveData001 +* @tc.desc: Abnormal test of RetrieveData, query.key is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, RetrieveData001, TestSize.Level1) +{ + QueryOption query; + UnifiedData data; + query.intention = UD_INTENTION_BASE; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.RetrieveData(query, data); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: IsPermissionInCache002 +* @tc.desc: Abnormal test of IsPermissionInCache, privilegeCache_ has no query.key +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, IsPermissionInCache002, TestSize.Level1) +{ + QueryOption query; + UdmfServiceImpl udmfServiceImpl; + bool ret = udmfServiceImpl.IsPermissionInCache(query); + EXPECT_EQ(ret, false); +} + +/** +* @tc.name: UpdateData001 +* @tc.desc: Abnormal test of UpdateData, query.key is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, UpdateData001, TestSize.Level1) +{ + QueryOption query; + UnifiedData data; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.UpdateData(query, data); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: GetSummary001 +* @tc.desc: Abnormal test of UpdateData, query.key is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, GetSummary001, TestSize.Level1) +{ + QueryOption query; + Summary summary; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.GetSummary(query, summary); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: Sync001 +* @tc.desc: Abnormal test of Sync, query.key is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, Sync001, TestSize.Level1) +{ + QueryOption query; + std::vector devices = {"device1"}; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.Sync(query, devices); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: IsRemoteData001 +* @tc.desc: Abnormal test of IsRemoteData, query.key is invalid +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, IsRemoteData001, TestSize.Level1) +{ + QueryOption query; + bool result = false; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.IsRemoteData(query, result); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: SetAppShareOption001 +* @tc.desc: Abnormal test of SetAppShareOption, intention is empty +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, SetAppShareOption001, TestSize.Level1) +{ + std::string intention = ""; + int32_t shareOption = 1; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.SetAppShareOption(intention, shareOption); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + + +/** +* @tc.name: SetAppShareOption002 +* @tc.desc: Abnormal test of SetAppShareOption, shareOption > SHARE_OPTIONS_BUTT +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, SetAppShareOption002, TestSize.Level1) +{ + std::string intention = "intention"; + int32_t shareOption = 4; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.SetAppShareOption(intention, shareOption); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: SetAppShareOption003 +* @tc.desc: Abnormal test of SetAppShareOption, shareOption = SHARE_OPTIONS_BUTT +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, SetAppShareOption003, TestSize.Level1) +{ + std::string intention = "intention"; + int32_t shareOption = 3; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.SetAppShareOption(intention, shareOption); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} + +/** +* @tc.name: SetAppShareOption004 +* @tc.desc: Abnormal test of SetAppShareOption, shareOption < IN_APP +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, SetAppShareOption004, TestSize.Level1) +{ + std::string intention = "intention"; + int32_t shareOption = -1; + UdmfServiceImpl udmfServiceImpl; + int32_t ret = udmfServiceImpl.SetAppShareOption(intention, shareOption); + EXPECT_EQ(ret, E_INVALID_PARAMETERS); +} +}; // namespace UDMF \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/test/unittest/cloud/device_manger_adapter_mock.cpp b/datamgr_service/services/distributeddataservice/service/test/unittest/cloud/device_manger_adapter_mock.cpp index ec2f814e5a96ce641041ec1ee7951d5a4842c112..4f2c5ac381d31c7fb46a9f06759b0f822da522ae 100644 --- a/datamgr_service/services/distributeddataservice/service/test/unittest/cloud/device_manger_adapter_mock.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/unittest/cloud/device_manger_adapter_mock.cpp @@ -17,59 +17,59 @@ namespace OHOS { namespace DistributedData { -DeviceManagerAdapter &DeviceManagerAdapter::GetInstance() -{ - static DeviceManagerAdapter dmAdapter; - return dmAdapter; -} -void DeviceManagerAdapter::Init(std::shared_ptr executors) {} -//Status DeviceManagerAdapter::StartWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) +//DeviceManagerAdapter &DeviceManagerAdapter::GetInstance() //{ +// static DeviceManagerAdapter dmAdapter; +// return dmAdapter; +//} +//void DeviceManagerAdapter::Init(std::shared_ptr executors) {} +////Status DeviceManagerAdapter::StartWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) +////{ +//// +////} +////Status DeviceManagerAdapter::StopWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) +////{ +////} +////DeviceInfo DeviceManagerAdapter::GetLocalDevice() {} +////std::vector DeviceManagerAdapter::GetRemoteDevices() {} +////DeviceInfo DeviceManagerAdapter::GetDeviceInfo(const std::string &id) {} +//std::string DeviceManagerAdapter::GetUuidByNetworkId(const std::string &networkId) +//{ +// return networkId; +//} +//std::string DeviceManagerAdapter::GetUdidByNetworkId(const std::string &networkId) +//{ +// return networkId; +//} +//std::string DeviceManagerAdapter::CalcClientUuid(const std::string &appId, const std::string &uuid) +//{ +// return appId + uuid; +//} +//std::string DeviceManagerAdapter::ToUUID(const std::string &id) +//{ +// return id; +//} +//std::string DeviceManagerAdapter::ToUDID(const std::string &id) +//{ +// return id; +//} +////static std::vector DeviceManagerAdapter::ToUUID(const std::vector &devices) {} +////static std::vector DeviceManagerAdapter::ToUUID(std::vector devices) {} +//std::string DeviceManagerAdapter::ToNetworkID(const std::string &id) +//{ +// return id; +//} +//void DeviceManagerAdapter::NotifyReadyEvent(const std::string &uuid) {} // +//bool DeviceManagerAdapter::IsNetworkAvailable() +//{ +// return true; //} -//Status DeviceManagerAdapter::StopWatchDeviceChange(const AppDeviceChangeListener *observer, const PipeInfo &pipeInfo) +// +//DeviceManagerAdapter::DeviceManagerAdapter() +// : cloudDmInfo({ "cloudDeviceId", "cloudDeviceName", 0, "cloudNetworkId", 0 }) //{ //} -//DeviceInfo DeviceManagerAdapter::GetLocalDevice() {} -//std::vector DeviceManagerAdapter::GetRemoteDevices() {} -//DeviceInfo DeviceManagerAdapter::GetDeviceInfo(const std::string &id) {} -std::string DeviceManagerAdapter::GetUuidByNetworkId(const std::string &networkId) -{ - return networkId; -} -std::string DeviceManagerAdapter::GetUdidByNetworkId(const std::string &networkId) -{ - return networkId; -} -std::string DeviceManagerAdapter::CalcClientUuid(const std::string &appId, const std::string &uuid) -{ - return appId + uuid; -} -std::string DeviceManagerAdapter::ToUUID(const std::string &id) -{ - return id; -} -std::string DeviceManagerAdapter::ToUDID(const std::string &id) -{ - return id; -} -//static std::vector DeviceManagerAdapter::ToUUID(const std::vector &devices) {} -//static std::vector DeviceManagerAdapter::ToUUID(std::vector devices) {} -std::string DeviceManagerAdapter::ToNetworkID(const std::string &id) -{ - return id; -} -void DeviceManagerAdapter::NotifyReadyEvent(const std::string &uuid) {} - -bool DeviceManagerAdapter::IsNetworkAvailable() -{ - return true; -} - -DeviceManagerAdapter::DeviceManagerAdapter() - : cloudDmInfo({ "cloudDeviceId", "cloudDeviceName", 0, "cloudNetworkId", 0 }) -{ -} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/udmf/BUILD.gn b/datamgr_service/services/distributeddataservice/service/udmf/BUILD.gn index 9824c5be0998860f2810b558181c7671c091fa0a..c791f4bfb94332e044959a754932cafe4705373b 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/udmf/BUILD.gn @@ -64,7 +64,10 @@ ohos_shared_library("udmf_server") { configs = [ ":module_public_config" ] - cflags = [ "-D_LIBCPP_HAS_COND_CLOCKWAIT" ] + cflags = [ + "-D_LIBCPP_HAS_COND_CLOCKWAIT", + "-Werror", + ] deps = [ "${data_service_path}/adapter:distributeddata_adapter", diff --git a/datamgr_service/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/datamgr_service/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index 5fa055cf5c1a729ecc736480472f03efb4911c02..0c4062437d3cb2ed075d00516f994f62bf9d93d1 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -193,8 +193,6 @@ int32_t PreProcessUtils::SetRemoteUri(uint32_t tokenId, UnifiedData &data) } int ret = GetDfsUrisFromLocal(uris, userId, data); if (ret != E_OK) { - RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SET_DATA, SetDataStage::GERERATE_DFS_URI, StageRes::FAILED, E_FS_ERROR); ZLOGE("Get remoteUri failed, ret = %{public}d, userId: %{public}d, uri size:%{public}zu.", ret, userId, uris.size()); } diff --git a/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 3d1cc59f47a13833b84cc3f8745d10719d5b8fa3..11ea83507e36c8089263d098447ae8da45ee9b8c 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -282,18 +282,16 @@ Status RuntimeStore::Sync(const std::vector &devices) } if (dbStatus != DBStatus::OK) { RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, dbStatus); + BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, dbStatus, BizState::DFX_END); } else { RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::SUCCESS, BizState::DFX_NORMAL_END); + BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::SUCCESS, BizState::DFX_END); } ZLOGI("sync complete, %{public}s, status:%{public}d.", Anonymous::Change(storeId_).c_str(), dbStatus); }; DBStatus status = kvStore_->Sync(syncDevices, SyncMode::SYNC_MODE_PULL_ONLY, onComplete); if (status != DBStatus::OK) { - RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, status); ZLOGE("Sync kvStore failed, status: %{public}d.", status); return E_DB_ERROR; } @@ -323,8 +321,6 @@ Status RuntimeStore::Sync(const std::vector &devices, ProcessCallba option.isWait = false; DBStatus status = kvStore_->Sync(option, progressCallback); if (status != DBStatus::OK) { - RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, status); ZLOGE("Sync kvStore failed, status: %{public}d.", status); return E_DB_ERROR; } @@ -347,11 +343,11 @@ void RuntimeStore::NotifySyncProcss(const DevSyncProcessMap &processMap, Process if (syncProcess.errCode == DBStatus::OK) { processInfo.syncStatus = ASYNC_SUCCESS; RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::SUCCESS, BizState::DFX_NORMAL_END); + BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::SUCCESS, BizState::DFX_END); } else { processInfo.syncStatus = ASYNC_FAILURE; RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, syncProcess.errCode); + BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, syncProcess.errCode, BizState::DFX_END); } } callback(processInfo); diff --git a/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index edbdc54e3882b038a24cdde4c85a4e1ce5c8106f..0b237bf2c64debaab8373133ce8c5d418f9a9772 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -228,6 +228,8 @@ int32_t UdmfServiceImpl::RetrieveData(const QueryOption &query, UnifiedData &uni if (key.intention == UD_INTENTION_MAP.at(UD_INTENTION_DRAG)) { int32_t ret = ProcessUri(query, unifiedData); if (ret != E_OK) { + RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), + BizScene::GET_DATA, GetDataStage::GRANT_URI_PERMISSION, StageRes::FAILED, ret); ZLOGE("ProcessUri failed. ret=%{public}d", ret); return E_NO_PERMISSION; } @@ -273,7 +275,8 @@ bool UdmfServiceImpl::IsReadAndKeep(const std::vector &privileges, co int32_t UdmfServiceImpl::ProcessUri(const QueryOption &query, UnifiedData &unifiedData) { std::string localDeviceId = PreProcessUtils::GetLocalDeviceId(); - int32_t verifyRes = ProcessCrossDeviceData(unifiedData); + std::vector allUri; + int32_t verifyRes = ProcessCrossDeviceData(unifiedData, allUri); if (verifyRes != E_OK) { ZLOGE("verify unifieddata fail, key=%{public}s, stauts=%{public}d", query.key.c_str(), verifyRes); return verifyRes; @@ -288,31 +291,10 @@ int32_t UdmfServiceImpl::ProcessUri(const QueryOption &query, UnifiedData &unifi ZLOGW("No need to grant uri permissions, queryKey=%{public}s.", query.key.c_str()); return E_OK; } - std::vector allUri; - auto records = unifiedData.GetRecords(); - for (auto record : records) { - if (record != nullptr && PreProcessUtils::IsFileType(record->GetType())) { - auto file = static_cast(record.get()); - if (file->GetUri().empty()) { - ZLOGW("Get uri is empty, key=%{public}s.", query.key.c_str()); - continue; - } - Uri uri(file->GetUri()); - std::string scheme = uri.GetScheme(); - std::transform(scheme.begin(), scheme.end(), scheme.begin(), ::tolower); - if (uri.GetAuthority().empty() || scheme != FILE_SCHEME) { - ZLOGW("Get authority is empty or uri scheme not equals to file, key=%{public}s.", query.key.c_str()); - continue; - } - allUri.push_back(uri); - } - } asyncProcessInfo_.permStatus = ASYNC_RUNNING; asyncProcessInfo_.permTotal = allUri.size(); if (UriPermissionManager::GetInstance().GrantUriPermission(allUri, query.tokenId, query.key, asyncProcessInfo_.permFnished) != E_OK) { - RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::GET_DATA, GetDataStage::GRANT_URI_PERMISSION, StageRes::FAILED, E_NO_PERMISSION); ZLOGE("GrantUriPermission fail, bundleName=%{public}s, key=%{public}s.", bundleName.c_str(), query.key.c_str()); return E_NO_PERMISSION; @@ -320,7 +302,7 @@ int32_t UdmfServiceImpl::ProcessUri(const QueryOption &query, UnifiedData &unifi return E_OK; } -int32_t UdmfServiceImpl::ProcessCrossDeviceData(UnifiedData &unifiedData) +int32_t UdmfServiceImpl::ProcessCrossDeviceData(UnifiedData &unifiedData, std::vector &uris) { if (unifiedData.GetRuntime() == nullptr) { ZLOGE("Get runtime empty!"); @@ -328,20 +310,37 @@ int32_t UdmfServiceImpl::ProcessCrossDeviceData(UnifiedData &unifiedData) } std::string localDeviceId = PreProcessUtils::GetLocalDeviceId(); std::string sourceDeviceId = unifiedData.GetRuntime()->deviceId; - if (localDeviceId == sourceDeviceId) { - return E_OK; - } auto records = unifiedData.GetRecords(); for (auto record : records) { - if (record != nullptr && PreProcessUtils::IsFileType(record->GetType())) { - auto file = static_cast(record.get()); - std::string remoteUri = file->GetRemoteUri(); - if (remoteUri.empty()) { + if (record == nullptr || !PreProcessUtils::IsFileType(record->GetType())) { + continue; + } + auto file = static_cast(record.get()); + if (file->GetUri().empty()) { + ZLOGW("Get uri is empty."); + continue; + } + Uri uri(file->GetUri()); + std::string scheme = uri.GetScheme(); + std::transform(scheme.begin(), scheme.end(), scheme.begin(), ::tolower); + std::string remoteUri = file->GetRemoteUri(); + if (localDeviceId != sourceDeviceId) { + if (remoteUri.empty() && scheme == FILE_SCHEME) { ZLOGE("when cross devices, remote uri is required!"); return E_ERROR; } - file->SetUri(remoteUri); // cross dev, need dis path. + if (!remoteUri.empty()) { + file->SetUri(remoteUri); // cross dev, need dis path. + } + } + Uri newUri(file->GetUri()); + scheme = newUri.GetScheme(); + std::transform(scheme.begin(), scheme.end(), scheme.begin(), ::tolower); + if (newUri.GetAuthority().empty() || scheme != FILE_SCHEME) { + ZLOGW("Get authority is empty or uri scheme not equals to file."); + continue; } + uris.push_back(newUri); } return E_OK; } @@ -537,12 +536,16 @@ int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vectorSync(devices, callback) != E_OK) { syncingData_ = false; ZLOGE("Store sync failed, intention: %{public}s.", key.intention.c_str()); RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, E_DB_ERROR, BizState::DFX_ABNORMAL_END); + BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, E_DB_ERROR, BizState::DFX_END); return E_DB_ERROR; } - RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), - BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::SUCCESS, BizState::DFX_NORMAL_END); return E_OK; } diff --git a/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.h b/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.h index f121fc99778349831afb89ef02c2fdd5b829b034..3d096d7f105ec9ae4753eee8fa54453ad4f8799d 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -61,7 +61,7 @@ private: int32_t ProcessUri(const QueryOption &query, UnifiedData &unifiedData); bool IsPermissionInCache(const QueryOption &query); bool IsReadAndKeep(const std::vector &privileges, const QueryOption &query); - int32_t ProcessCrossDeviceData(UnifiedData &unifiedData); + int32_t ProcessCrossDeviceData(UnifiedData &unifiedData, std::vector &uris); class Factory { public: diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/src/store_util.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/src/store_util.cpp index 9f49528669465b2467b61e327afe9bdeaf08b100..014a2ab030e81a75aeaeab39983820cb4732709c 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/src/store_util.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/src/store_util.cpp @@ -292,6 +292,10 @@ bool StoreUtil::RemoveRWXForOthers(const std::string &path) if (S_ISDIR(buf.st_mode)) { DIR *dirp = opendir(path.c_str()); + if (dirp == nullptr) { + ZLOGE("opendir error:%{public}d, path:%{public}s", errno, path.c_str()); + return false; + } struct dirent *dp = nullptr; while ((dp = readdir(dirp)) != nullptr) { if ((std::string(dp->d_name) == ".") || (std::string(dp->d_name) == "..")) { diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn b/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn index 1634d3e3ffae04e589ed2155a8763b6d2787dbc6..ecad8dc10648256584ab73899ce7ef0e9209bc0a 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn @@ -22,19 +22,15 @@ config("module_private_config") { include_dirs = [ "${kv_store_base_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "../../../../interfaces/innerkits/distributeddatamgr/include/", - "//commonlibrary/c_utils/base/include", "//foundation/distributeddatamgr/kv_store/frameworks/common", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/include", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/kvdb/src", + "${kv_store_base_path}/frameworks/innerkitsimpl/kvdb/test/mock", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/distributedtest/single_kvstore_client", "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/app/include", - "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include", - "//base/hiviewdfx/hitrace/interfaces/native/innerkits/include", - "//test/testfwk/developer_test/aw/distributed", ] lib_dirs = [ "//foundation/appexecfwk/libs" ] } @@ -91,12 +87,12 @@ ohos_source_set("kvdb_src_file") { "../../../../databaseutils:database_utils", "../../../../interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", - "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp:devicemanagersdk", ] external_deps = [ "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", "c_utils:utils", + "device_manager:devicemanagersdk", "file_api:securitylabel", "hilog:libhilog", "hisysevent:libhisysevent", @@ -130,6 +126,7 @@ ohos_unittest("SingleStoreImplTest") { external_deps = [ "c_utils:utils", + "device_manager:devicemanagersdk", "hilog:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", @@ -373,6 +370,162 @@ ohos_unittest("SingleStorePerfPhoneTest") { ] } +ohos_unittest("StoreFactoryMockTest") { + module_out_path = module_output_path + sources = [ + "../../distributeddatafwk/src/blob.cpp", + "../../distributeddatafwk/src/ikvstore_observer.cpp", + "../../distributeddatafwk/src/kvdb_notifier_client.cpp", + "../../distributeddatafwk/src/kvdb_notifier_stub.cpp", + "../../distributeddatafwk/src/kvstore_observer_client.cpp", + "../../distributeddatafwk/src/kvstore_service_death_notifier.cpp", + "../../distributeddatafwk/src/sync_observer.cpp", + "../../kvdb/src/kv_hiview_reporter_mock.cpp", + "../src/backup_manager.cpp", + "../src/convertor.cpp", + "../src/dev_manager.cpp", + "../src/device_convertor.cpp", + "../src/kv_types_util.cpp", + "../src/kvdb_service_client.cpp", + "../src/observer_bridge.cpp", + "../src/single_store_impl.cpp", + "../src/store_factory.cpp", + "../src/store_manager.cpp", + "../src/store_result_set.cpp", + "../src/system_api.cpp", + "../src/task_executor.cpp", + "../src/task_executor_adapter.cpp", + "./mock/src/security_manager_mock.cpp", + "./mock/src/store_util_mock.cpp", + "store_factory_mock_test.cpp", + ] + + if (qemu_disable) { + sources += [ "../src/auto_sync_timer.cpp" ] + } else { + sources += [ "../src/auto_sync_timer_mock.cpp" ] + } + configs = [ ":module_private_config" ] + deps = [ + "${kv_store_base_path}/frameworks/libs/distributeddb/:distributeddb", + "${kv_store_base_path}/interfaces/innerkits/distributeddata:distributeddata_inner", + "${kv_store_base_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "device_manager:devicemanagersdk", + "file_api:securitylabel", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "huks:libhukssdk", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (dms_service_enable && qemu_disable) { + external_deps += [ "dmsfwk:distributed_sdk" ] + } + + cflags = [ "-Dprivate=public" ] + + public_external_deps = [ + "googletest:gmock_main", + "googletest:gtest_main", + ] + + use_exceptions = true +} + +ohos_unittest("SingleStoreImplMockTest") { + module_out_path = module_output_path + sources = [ + "../../distributeddatafwk/src/blob.cpp", + "../../distributeddatafwk/src/change_notification.cpp", + "../../distributeddatafwk/src/data_query.cpp", + "../../distributeddatafwk/src/distributed_kv_data_manager.cpp", + "../../distributeddatafwk/src/ikvstore_client_death_observer.cpp", + "../../distributeddatafwk/src/ikvstore_observer.cpp", + "../../distributeddatafwk/src/kv_utils.cpp", + "../../distributeddatafwk/src/kvdb_notifier_stub.cpp", + "../../distributeddatafwk/src/kvstore_client_death_observer.cpp", + "../../distributeddatafwk/src/kvstore_datashare_bridge.cpp", + "../../distributeddatafwk/src/kvstore_observer_client.cpp", + "../../distributeddatafwk/src/kvstore_service_death_notifier.cpp", + "../../distributeddatafwk/src/sync_observer.cpp", + "../../kvdb/src/kv_hiview_reporter_mock.cpp", + "../src/backup_manager.cpp", + "../src/convertor.cpp", + "../src/device_convertor.cpp", + "../src/kv_types_util.cpp", + "../src/security_manager.cpp", + "../src/single_store_impl.cpp", + "../src/store_factory.cpp", + "../src/store_manager.cpp", + "../src/store_result_set.cpp", + "../src/store_util.cpp", + "../src/system_api.cpp", + "../src/task_executor_adapter.cpp", + "./mock/src/dev_manager_mock.cpp", + "./mock/src/kvdb_notifier_client_mock.cpp", + "./mock/src/kvdb_service_client_mock.cpp", + "./mock/src/observer_bridge_mock.cpp", + "./mock/src/task_executor_mock.cpp", + "single_store_impl_mock_test.cpp", + ] + + if (qemu_disable) { + sources += [ "../src/auto_sync_timer.cpp" ] + } else { + sources += [ "../src/auto_sync_timer_mock.cpp" ] + } + + configs = [ ":module_private_config" ] + deps = [ + "${kv_store_base_path}/frameworks/libs/distributeddb/:distributeddb", + "${kv_store_base_path}/interfaces/innerkits/distributeddata:distributeddata_client_sync", + "${kv_store_base_path}/interfaces/innerkits/distributeddata:distributeddata_inner", + "${kv_store_base_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", + "../../../../databaseutils:database_utils", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "c_utils:utils", + "device_manager:devicemanagersdk", + "file_api:securitylabel", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "huks:libhukssdk", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (dms_service_enable && qemu_disable) { + external_deps += [ "dmsfwk:distributed_sdk" ] + } + + public_external_deps = [ + "data_share:datashare_common", + "data_share:datashare_provider", + "googletest:gmock_main", + "googletest:gtest_main", + ] + + defines = [ + "private=public", + "protected=public", + ] + + use_exceptions = true +} + ############################################################################### group("unittest") { testonly = true @@ -383,7 +536,9 @@ group("unittest") { ":DevManagerMockTest", ":DevManagerTest", ":SingleStoreImplGetTopTest", + ":SingleStoreImplMockTest", ":SingleStoreImplTest", + ":StoreFactoryMockTest", ":StoreFactoryTest", ":StoreUtilTest", ] diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp index c900b60577846e8cc5bc29381b9619cd658743c5..1934f5780f2c777106ded8f877346a05b1bd78e0 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp @@ -36,8 +36,8 @@ public: Status DeleteBackUpFiles(std::shared_ptr kvStore, std::string baseDir, StoreId storeId); void MkdirPath(std::string baseDir, AppId appId, StoreId storeId); - std::shared_ptr CreateKVStore(std::string storeIdTest, std::string appIdTest, std::string baseDir, - KvStoreType type, bool encrypt); + std::shared_ptr CreateKVStore( + std::string storeIdTest, std::string appIdTest, std::string baseDir, KvStoreType type, bool encrypt); std::shared_ptr kvStore_; }; @@ -82,8 +82,8 @@ void BackupManagerTest::TearDown(void) ASSERT_EQ(status, SUCCESS); } -std::shared_ptr BackupManagerTest::CreateKVStore(std::string storeIdTest, std::string appIdTest, - std::string baseDir, KvStoreType type, bool encrypt) +std::shared_ptr BackupManagerTest::CreateKVStore( + std::string storeIdTest, std::string appIdTest, std::string baseDir, KvStoreType type, bool encrypt) { Options options; options.kvStoreType = type; @@ -127,12 +127,12 @@ void BackupManagerTest::MkdirPath(std::string baseDir, AppId appId, StoreId stor } /** -* @tc.name: BackUp -* @tc.desc: the kvstore back up -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: BackUp + * @tc.desc: the kvstore back up + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, BackUp, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); @@ -141,12 +141,12 @@ HWTEST_F(BackupManagerTest, BackUp, TestSize.Level0) ASSERT_EQ(status, SUCCESS); } /** -* @tc.name: BackUpInvalidArguments -* @tc.desc: the kvstore back up and the arguments is invalid -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: BackUpInvalidArguments + * @tc.desc: the kvstore back up and the arguments is invalid + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, BackUpInvalidArguments, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); @@ -160,12 +160,12 @@ HWTEST_F(BackupManagerTest, BackUpInvalidArguments, TestSize.Level0) ASSERT_EQ(status, INVALID_ARGUMENT); } /** -* @tc.name: BackUpSameFile -* @tc.desc: the kvstore back up the same file -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: BackUpSameFile + * @tc.desc: the kvstore back up the same file + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, BackUpSameFile, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); @@ -176,12 +176,12 @@ HWTEST_F(BackupManagerTest, BackUpSameFile, TestSize.Level0) ASSERT_EQ(status, SUCCESS); } /** -* @tc.name: ReStore -* @tc.desc: the kvstore ReStore -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: ReStore + * @tc.desc: the kvstore ReStore + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, ReStore, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); @@ -208,12 +208,12 @@ HWTEST_F(BackupManagerTest, ReStore, TestSize.Level0) ASSERT_EQ(status, INVALID_ARGUMENT); } /** -* @tc.name: DeleteBackup -* @tc.desc: the kvstore DeleteBackup -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: DeleteBackup + * @tc.desc: the kvstore DeleteBackup + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, DeleteBackup, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); @@ -233,12 +233,12 @@ HWTEST_F(BackupManagerTest, DeleteBackup, TestSize.Level0) ASSERT_EQ(status, INVALID_ARGUMENT); } /** -* @tc.name: RollbackKey -* @tc.desc: rollback the key -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: RollbackKey + * @tc.desc: rollback the key + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, RollbackKey, TestSize.Level0) { AppId appId = { "BackupManagerTestRollBackKey" }; @@ -279,12 +279,12 @@ HWTEST_F(BackupManagerTest, RollbackKey, TestSize.Level0) } /** -* @tc.name: RollbackData -* @tc.desc: rollback the data -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: RollbackData + * @tc.desc: rollback the data + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, RollbackData, TestSize.Level0) { AppId appId = { "BackupManagerTestRollBackData" }; @@ -319,12 +319,12 @@ HWTEST_F(BackupManagerTest, RollbackData, TestSize.Level0) } /** -* @tc.name: Rollback -* @tc.desc: rollback the key -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: Rollback + * @tc.desc: rollback the key + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, Rollback, TestSize.Level0) { AppId appId = { "BackupManagerTestRollBack" }; @@ -374,12 +374,12 @@ HWTEST_F(BackupManagerTest, Rollback, TestSize.Level0) } /** -* @tc.name: CleanTmp -* @tc.desc: Clean up temporary data -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: CleanTmp + * @tc.desc: Clean up temporary data + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, CleanTmp, TestSize.Level0) { AppId appId = { "BackupManagerTestCleanTmp" }; @@ -429,12 +429,12 @@ HWTEST_F(BackupManagerTest, CleanTmp, TestSize.Level0) } /** -* @tc.name: BackUpEncrypt -* @tc.desc: Back up an encrypt database and restore -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: BackUpEncrypt + * @tc.desc: Back up an encrypt database and restore + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(BackupManagerTest, BackUpEntry, TestSize.Level0) { AppId appId = { "BackupManagerTest" }; diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_mock_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_mock_test.cpp index c44a7cc0b35acca0183dcec28d65d54ee53ccba4..b84cdc1beca83bc7aeeda0b4f191e376e76de853 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_mock_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_mock_test.cpp @@ -14,11 +14,11 @@ */ #define LOG_TAG "DevManagerMockTest" -#include #include "dev_manager.h" #include "device_manager_mock.h" -#include "types.h" #include "log_print.h" +#include "types.h" +#include namespace OHOS::Test { using namespace testing; using namespace testing::ext; @@ -35,25 +35,21 @@ public: void TearDown(); }; -void DevManagerMockTest::SetUpTestCase(void) -{} +void DevManagerMockTest::SetUpTestCase(void) { } -void DevManagerMockTest::TearDownTestCase(void) -{} +void DevManagerMockTest::TearDownTestCase(void) { } -void DevManagerMockTest::SetUp(void) -{} +void DevManagerMockTest::SetUp(void) { } -void DevManagerMockTest::TearDown(void) -{} +void DevManagerMockTest::TearDown(void) { } /** -* @tc.name: GetUnEncryptedUuid -* @tc.desc: test GetUnEncryptedUuid get local device info fail -* @tc.type: FUNC -* @tc.require: -* @tc.author: SQL -*/ + * @tc.name: GetUnEncryptedUuid + * @tc.desc: test GetUnEncryptedUuid get local device info fail + * @tc.type: FUNC + * @tc.require: + * @tc.author: SQL + */ HWTEST_F(DevManagerMockTest, GetUnEncryptedUuid001, TestSize.Level1) { ZLOGI("GetUnEncryptedUuid001 begin."); @@ -62,12 +58,12 @@ HWTEST_F(DevManagerMockTest, GetUnEncryptedUuid001, TestSize.Level1) } /** -* @tc.name: GetUnEncryptedUuid -* @tc.desc: test GetUnEncryptedUuid networkid empty -* @tc.type: FUNC -* @tc.require: -* @tc.author: SQL -*/ + * @tc.name: GetUnEncryptedUuid + * @tc.desc: test GetUnEncryptedUuid networkid empty + * @tc.type: FUNC + * @tc.require: + * @tc.author: SQL + */ HWTEST_F(DevManagerMockTest, GetUnEncryptedUuid002, TestSize.Level1) { ZLOGI("GetUnEncryptedUuid002 begin."); @@ -76,12 +72,12 @@ HWTEST_F(DevManagerMockTest, GetUnEncryptedUuid002, TestSize.Level1) } /** -* @tc.name: GetLocalDevice -* @tc.desc: test GetLocalDevice get local device info fail -* @tc.type: FUNC -* @tc.require: -* @tc.author: SQL -*/ + * @tc.name: GetLocalDevice + * @tc.desc: test GetLocalDevice get local device info fail + * @tc.type: FUNC + * @tc.require: + * @tc.author: SQL + */ HWTEST_F(DevManagerMockTest, GetLocalDevice, TestSize.Level1) { ZLOGI("GetLocalDevice begin."); @@ -90,12 +86,12 @@ HWTEST_F(DevManagerMockTest, GetLocalDevice, TestSize.Level1) } /** -* @tc.name: GetRemoteDevices001 -* @tc.desc: test GetRemoteDevices get trusted device fail -* @tc.type: FUNC -* @tc.require: -* @tc.author: SQL -*/ + * @tc.name: GetRemoteDevices001 + * @tc.desc: test GetRemoteDevices get trusted device fail + * @tc.type: FUNC + * @tc.require: + * @tc.author: SQL + */ HWTEST_F(DevManagerMockTest, GetRemoteDevices001, TestSize.Level1) { ZLOGI("GetRemoteDevices001 begin."); @@ -104,12 +100,12 @@ HWTEST_F(DevManagerMockTest, GetRemoteDevices001, TestSize.Level1) } /** -* @tc.name: GetRemoteDevices002 -* @tc.desc: test GetRemoteDevices get trusted device no remote device -* @tc.type: FUNC -* @tc.require: -* @tc.author: SQL -*/ + * @tc.name: GetRemoteDevices002 + * @tc.desc: test GetRemoteDevices get trusted device no remote device + * @tc.type: FUNC + * @tc.require: + * @tc.author: SQL + */ HWTEST_F(DevManagerMockTest, GetRemoteDevices002, TestSize.Level1) { ZLOGI("GetRemoteDevices002 begin."); diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp index 01bf94431e59a9a61bfdedcfbe4fc7b34d2520b7..4214a064095af5f7e921aa8b7ef2aedb3980f526 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/dev_manager_test.cpp @@ -17,8 +17,8 @@ #include #include "dev_manager.h" -#include "types.h" #include "log_print.h" +#include "types.h" namespace OHOS::Test { using namespace testing::ext; using namespace OHOS::DistributedKv; @@ -32,25 +32,21 @@ public: void TearDown(); }; -void DevManagerTest::SetUpTestCase(void) -{} +void DevManagerTest::SetUpTestCase(void) { } -void DevManagerTest::TearDownTestCase(void) -{} +void DevManagerTest::TearDownTestCase(void) { } -void DevManagerTest::SetUp(void) -{} +void DevManagerTest::SetUp(void) { } -void DevManagerTest::TearDown(void) -{} +void DevManagerTest::TearDown(void) { } /** -* @tc.name: GetLocalDevice -* @tc.desc: Get local device's infomation -* @tc.type: FUNC -* @tc.require: -* @tc.author: taoyuxin -*/ + * @tc.name: GetLocalDevice + * @tc.desc: Get local device's infomation + * @tc.type: FUNC + * @tc.require: + * @tc.author: taoyuxin + */ HWTEST_F(DevManagerTest, GetLocalDevice, TestSize.Level1) { ZLOGI("GetLocalDevice begin."); @@ -60,12 +56,12 @@ HWTEST_F(DevManagerTest, GetLocalDevice, TestSize.Level1) } /** -* @tc.name: ToUUID -* @tc.desc: Get uuid from networkId -* @tc.type: FUNC -* @tc.require: -* @tc.author: taoyuxin -*/ + * @tc.name: ToUUID + * @tc.desc: Get uuid from networkId + * @tc.type: FUNC + * @tc.require: + * @tc.author: taoyuxin + */ HWTEST_F(DevManagerTest, ToUUID, TestSize.Level1) { ZLOGI("ToUUID begin."); @@ -78,12 +74,12 @@ HWTEST_F(DevManagerTest, ToUUID, TestSize.Level1) } /** -* @tc.name: ToNetworkId -* @tc.desc: Get networkId from uuid -* @tc.type: FUNC -* @tc.require: -* @tc.author: zuojiangjiang -*/ + * @tc.name: ToNetworkId + * @tc.desc: Get networkId from uuid + * @tc.type: FUNC + * @tc.require: + * @tc.author: zuojiangjiang + */ HWTEST_F(DevManagerTest, ToNetworkId, TestSize.Level1) { auto &devMgr = DevManager::GetInstance(); @@ -95,12 +91,12 @@ HWTEST_F(DevManagerTest, ToNetworkId, TestSize.Level1) } /** -* @tc.name: GetRemoteDevices -* @tc.desc: Get remote devices -* @tc.type: FUNC -* @tc.require: -* @tc.author: taoyuxin -*/ + * @tc.name: GetRemoteDevices + * @tc.desc: Get remote devices + * @tc.type: FUNC + * @tc.require: + * @tc.author: taoyuxin + */ HWTEST_F(DevManagerTest, GetRemoteDevices, TestSize.Level1) { ZLOGI("GetRemoteDevices begin."); diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.cpp index 6249fa24ab17792ad238786655b4130dca742d92..c6acc7e83cd9cd3863a90e4de4f7a0de8e437397 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.cpp @@ -24,8 +24,7 @@ DeviceManager &DeviceManager::GetInstance() return instance; } -int32_t DeviceManager::InitDeviceManager(const std::string &pkgName, - std::shared_ptr dmInitCallback) +int32_t DeviceManager::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) { return ERR_DM_INPUT_PARA_INVALID; } @@ -35,8 +34,8 @@ int32_t DeviceManager::UnInitDeviceManager(const std::string &pkgName) return ERR_DM_INPUT_PARA_INVALID; } -int32_t DeviceManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, - std::vector &deviceList) +int32_t DeviceManager::GetTrustedDeviceList( + const std::string &pkgName, const std::string &extra, std::vector &deviceList) { if (testDemo == 0) { testDemo = 1; @@ -47,14 +46,13 @@ int32_t DeviceManager::GetTrustedDeviceList(const std::string &pkgName, const st } } -int32_t DeviceManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, - bool isRefresh, std::vector &deviceList) +int32_t DeviceManager::GetTrustedDeviceList( + const std::string &pkgName, const std::string &extra, bool isRefresh, std::vector &deviceList) { return ERR_DM_INPUT_PARA_INVALID; } -int32_t DeviceManager::GetAvailableDeviceList(const std::string &pkgName, - std::vector &deviceList) +int32_t DeviceManager::GetAvailableDeviceList(const std::string &pkgName, std::vector &deviceList) { return ERR_DM_INPUT_PARA_INVALID; } @@ -70,26 +68,25 @@ int32_t DeviceManager::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceIn } } -int32_t DeviceManager::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, - std::shared_ptr callback) +int32_t DeviceManager::RegisterDevStateCallback( + const std::string &pkgName, const std::string &extra, std::shared_ptr callback) { return ERR_DM_INPUT_PARA_INVALID; } -int32_t DeviceManager::RegisterDevStatusCallback(const std::string &pkgName, const std::string &extra, - std::shared_ptr callback) +int32_t DeviceManager::RegisterDevStatusCallback( + const std::string &pkgName, const std::string &extra, std::shared_ptr callback) { return ERR_DM_INPUT_PARA_INVALID; } -int32_t DeviceManager::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, - std::string &uuid) +int32_t DeviceManager::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) { return ERR_DM_INPUT_PARA_INVALID; } -int32_t DeviceManager::GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId, - std::string &uuid) +int32_t DeviceManager::GetEncryptedUuidByNetworkId( + const std::string &pkgName, const std::string &networkId, std::string &uuid) { return ERR_DM_INPUT_PARA_INVALID; } diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.h index 52ac6aa05ac1d4fb6194a91ace62a642aef0a172..65f1a5d47b6eafa5935b0c358694026f4928ec58 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.h +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/device_manager_mock.h @@ -16,14 +16,14 @@ #ifndef OHOS_DEVICE_MANAGER_H #define OHOS_DEVICE_MANAGER_H -#include -#include -#include -#include #include "device_manager_callback.h" #include "dm_device_info.h" #include "dm_publish_info.h" #include "dm_subscribe_info.h" +#include +#include +#include +#include namespace OHOS { @@ -36,27 +36,27 @@ public: virtual int32_t UnInitDeviceManager(const std::string &pkgName); - virtual int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, - std::vector &deviceList); + virtual int32_t GetTrustedDeviceList( + const std::string &pkgName, const std::string &extra, std::vector &deviceList); - virtual int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, - bool isRefresh, std::vector &deviceList); + virtual int32_t GetTrustedDeviceList( + const std::string &pkgName, const std::string &extra, bool isRefresh, std::vector &deviceList); - virtual int32_t GetAvailableDeviceList(const std::string &pkgName, - std::vector &deviceList); + virtual int32_t GetAvailableDeviceList(const std::string &pkgName, std::vector &deviceList); virtual int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &deviceInfo); - virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, - std::shared_ptr callback); + virtual int32_t RegisterDevStateCallback( + const std::string &pkgName, const std::string &extra, std::shared_ptr callback); - virtual int32_t RegisterDevStatusCallback(const std::string &pkgName, const std::string &extra, - std::shared_ptr callback); + virtual int32_t RegisterDevStatusCallback( + const std::string &pkgName, const std::string &extra, std::shared_ptr callback); virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid); - virtual int32_t GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId, - std::string &uuid); + virtual int32_t GetEncryptedUuidByNetworkId( + const std::string &pkgName, const std::string &networkId, std::string &uuid); + private: int32_t testDemo = 0; DeviceManager() = default; diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/dev_manager_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/dev_manager_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..2c0231a2fa843c619c4dd0630e9d441c7e0c9a13 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/dev_manager_mock.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_DEV_MANAGER_MOCK_H +#define OHOS_DISTRIBUTED_DATA_DEV_MANAGER_MOCK_H + +#include "dev_manager.h" +#include + +namespace OHOS::DistributedKv { +class BDevManager { +public: + virtual std::string ToUUID(const std::string &) = 0; + virtual const DevManager::DetailInfo &GetLocalDevice() = 0; + virtual std::string ToNetworkId(const std::string &) = 0; + virtual std::string GetUnEncryptedUuid() = 0; + BDevManager() = default; + virtual ~BDevManager() = default; + +public: + static inline std::shared_ptr devManager = nullptr; +}; + +class DevManagerMock : public BDevManager { +public: + MOCK_METHOD(std::string, ToUUID, (const std::string &)); + MOCK_METHOD(const DevManager::DetailInfo &, GetLocalDevice, ()); + MOCK_METHOD(std::string, ToNetworkId, (const std::string &)); + MOCK_METHOD(std::string, GetUnEncryptedUuid, ()); +}; +} // namespace OHOS::DistributedKv +#endif // OHOS_DISTRIBUTED_DATA_DEV_MANAGER_MOCK_H \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/kvdb_notifier_client_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/kvdb_notifier_client_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..816650b0118d59b9c2abf0c19e643dd4b5901c66 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/kvdb_notifier_client_mock.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_KVDB_NOTIFIER_CLIENT_MOCK_H +#define OHOS_DISTRIBUTED_DATA_KVDB_NOTIFIER_CLIENT_MOCK_H + +#include "kvdb_notifier_client.h" +#include + +namespace OHOS::DistributedKv { +class BKVDBNotifierClient { +public: + virtual bool IsChanged(const std::string &, DataType) = 0; + virtual void AddSyncCallback(const std::shared_ptr, uint64_t) = 0; + virtual void DeleteSyncCallback(uint64_t) = 0; + virtual void AddCloudSyncCallback(uint64_t, const AsyncDetail &) = 0; + virtual void DeleteCloudSyncCallback(uint64_t) = 0; + virtual void AddSwitchCallback(const std::string &, std::shared_ptr) = 0; + virtual void DeleteSwitchCallback(const std::string &, std::shared_ptr) = 0; + virtual void SyncCompleted(uint64_t, ProgressDetail &&) = 0; + virtual void SyncCompleted(const std::map &, uint64_t) = 0; + virtual void OnRemoteChange(const std::map &, int32_t) = 0; + virtual void OnSwitchChange(const SwitchNotification &) = 0; + BKVDBNotifierClient() = default; + virtual ~BKVDBNotifierClient() = default; + +public: + static inline std::shared_ptr kVDBNotifierClient = nullptr; +}; + +class KVDBNotifierClientMock : public BKVDBNotifierClient { +public: + MOCK_METHOD(bool, IsChanged, (const std::string &, DataType dataType)); + MOCK_METHOD(void, AddSyncCallback, (const std::shared_ptr, uint64_t)); + MOCK_METHOD(void, DeleteSyncCallback, (uint64_t)); + MOCK_METHOD(void, AddCloudSyncCallback, (uint64_t, const AsyncDetail &)); + MOCK_METHOD(void, DeleteCloudSyncCallback, (uint64_t)); + MOCK_METHOD(void, AddSwitchCallback, (const std::string &, std::shared_ptr)); + MOCK_METHOD(void, DeleteSwitchCallback, (const std::string &, std::shared_ptr)); + MOCK_METHOD(void, SyncCompleted, (uint64_t, ProgressDetail &&)); + MOCK_METHOD(void, SyncCompleted, ((const std::map &), uint64_t)); + MOCK_METHOD(void, OnRemoteChange, ((const std::map &), int32_t)); + MOCK_METHOD(void, OnSwitchChange, (const SwitchNotification &)); +}; +} // namespace OHOS::DistributedKv +#endif // OHOS_DISTRIBUTED_DATA_KVDB_NOTIFIER_CLIENT_MOCK_H \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/kvdb_service_client_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/kvdb_service_client_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..a44fac1ae4b986bf08dc5caaef15d0b55c6a022d --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/kvdb_service_client_mock.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_KVDB_SERVICE_CLIENT_MOCK_H +#define OHOS_DISTRIBUTED_DATA_KVDB_SERVICE_CLIENT_MOCK_H + +#include "kvdb_service_client.h" +#include + +namespace OHOS::DistributedKv { +class BKVDBServiceClient { +public: + virtual std::shared_ptr GetInstance() = 0; + virtual sptr GetServiceAgent(const AppId &) = 0; + BKVDBServiceClient() = default; + virtual ~BKVDBServiceClient() = default; + +public: + static inline std::shared_ptr kVDBServiceClient = nullptr; +}; + +class KVDBServiceClientMock : public BKVDBServiceClient { +public: + MOCK_METHOD(std::shared_ptr, GetInstance, ()); + MOCK_METHOD(sptr, GetServiceAgent, (const AppId &)); + static inline Status status = ERROR; +}; +} // namespace OHOS::DistributedKv +#endif // OHOS_DISTRIBUTED_DATA_KVDB_SERVICE_CLIENT_MOCK_H \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/observer_bridge_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/observer_bridge_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..3bc66cff2aaafefbb851c847cc2aec411d8c089d --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/observer_bridge_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_OBSERVER_BRIDGE_MOCK_H +#define OHOS_DISTRIBUTED_DATA_OBSERVER_BRIDGE_MOCK_H + +#include "observer_bridge.h" +#include + +namespace OHOS::DistributedKv { +class BObserverBridge { +public: + virtual void OnServiceDeath() = 0; + virtual Status RegisterRemoteObserver(uint32_t) = 0; + BObserverBridge() = default; + virtual ~BObserverBridge() = default; + +public: + static inline std::shared_ptr observerBridge = nullptr; +}; + +class ObserverBridgeMock : public BObserverBridge { +public: + MOCK_METHOD(void, OnServiceDeath, ()); + MOCK_METHOD(Status, RegisterRemoteObserver, (uint32_t)); +}; +} // namespace OHOS::DistributedKv +#endif // OHOS_DISTRIBUTED_DATA_OBSERVER_BRIDGE_MOCK_H \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/security_manager_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/security_manager_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..d8b258b893d77e7e11c9f12e6c0641c903fa24b1 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/security_manager_mock.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_SECURITY_MANAGER_MOCK_H +#define OHOS_DISTRIBUTED_DATA_SECURITY_MANAGER_MOCK_H + +#include "security_manager.h" +#include + +namespace OHOS::DistributedKv { +class BSecurityManager { +public: + virtual bool SaveDBPassword(const std::string &, const std::string &, const DistributedDB::CipherPassword &) = 0; + virtual SecurityManager::DBPassword GetDBPassword(const std::string &, const std::string &, bool) = 0; + BSecurityManager() = default; + virtual ~BSecurityManager() = default; + +public: + static inline std::shared_ptr securityManager = nullptr; +}; + +class SecurityManagerMock : public BSecurityManager { +public: + MOCK_METHOD( + bool, SaveDBPassword, (const std::string &, const std::string &, const DistributedDB::CipherPassword &)); + MOCK_METHOD(SecurityManager::DBPassword, GetDBPassword, (const std::string &, const std::string &, bool)); +}; +} // namespace OHOS::DistributedKv +#endif // OHOS_DISTRIBUTED_DATA_STORE_UTIL_MOCK_H \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/store_util_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/store_util_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..73473344b947ca4d9ddcb2a92782c46ff0dd9e64 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/store_util_mock.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_STORE_UTIL_MOCK_H +#define OHOS_DISTRIBUTED_DATA_STORE_UTIL_MOCK_H + +#include + +#include "store_types.h" +#include "store_util.h" + +namespace OHOS::DistributedKv { +class BStoreUtil { +public: + virtual bool IsFileExist(const std::string &) = 0; + virtual bool Remove(const std::string &) = 0; + virtual Status ConvertStatus(StoreUtil::DBStatus) = 0; + virtual bool InitPath(const std::string) = 0; + virtual StoreUtil::DBSecurity GetDBSecurity(int32_t) = 0; + virtual StoreUtil::DBIndexType GetDBIndexType(IndexType) = 0; + virtual std::vector GetSubPath(const std::string &) = 0; + virtual std::vector GetFiles(const std::string &) = 0; + virtual bool Rename(const std::string &, const std::string &) = 0; + virtual uint32_t Anonymous(const void *) = 0; + virtual bool RemoveRWXForOthers(const std::string &) = 0; + virtual std::string Anonymous(const std::string &) = 0; + virtual bool CreateFile(const std::string &) = 0; + BStoreUtil() = default; + virtual ~BStoreUtil() = default; + +public: + static inline std::shared_ptr storeUtil = nullptr; +}; + +class StoreUtilMock : public BStoreUtil { +public: + MOCK_METHOD(bool, IsFileExist, (const std::string &)); + MOCK_METHOD(bool, Remove, (const std::string &)); + MOCK_METHOD(Status, ConvertStatus, (StoreUtil::DBStatus)); + MOCK_METHOD(StoreUtil::DBSecurity, GetDBSecurity, (int32_t)); + MOCK_METHOD(bool, InitPath, (const std::string)); + MOCK_METHOD(StoreUtil::DBIndexType, GetDBIndexType, (IndexType)); + MOCK_METHOD(std::vector, GetSubPath, (const std::string &)); + MOCK_METHOD(std::vector, GetFiles, (const std::string &)); + MOCK_METHOD(bool, Rename, (const std::string &, const std::string &)); + MOCK_METHOD(uint32_t, Anonymous, (const void *)); + MOCK_METHOD(std::string, Anonymous, (const std::string &)); + MOCK_METHOD(bool, RemoveRWXForOthers, (const std::string &)); + MOCK_METHOD(bool, CreateFile, (const std::string &)); +}; +} // namespace OHOS::DistributedKv +#endif // OHOS_DISTRIBUTED_DATA_STORE_UTIL_MOCK_H \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/task_executor_mock.h b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/task_executor_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..05a97ff9a9f0adc3f5bb3f298972e127216ec069 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/include/task_executor_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DISTRIBUTED_DATA_TASK_EXECUTOR_MOCK_H +#define DISTRIBUTED_DATA_TASK_EXECUTOR_MOCK_H +#include "task_executor.h" +#include + +namespace OHOS { +using TaskId = ExecutorPool::TaskId; +using Task = std::function; +using Duration = std::chrono::steady_clock::duration; + +class BTaskExecutor { +public: + BTaskExecutor() = default; + virtual ~BTaskExecutor() = default; + virtual TaskId Schedule(Duration, const Task &, Duration, uint64_t) = 0; + +public: + static inline std::shared_ptr taskExecutor = nullptr; +}; + +class TaskExecutorMock : public BTaskExecutor { +public: + MOCK_METHOD(TaskId, Schedule, (Duration, const Task &, Duration, uint64_t)); +}; +} // namespace OHOS +#endif // DISTRIBUTED_DATA_TASK_EXECUTOR_MOCK_H \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/dev_manager_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/dev_manager_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..108b7fac65b32af2eb8b56f6626abd2152c7b726 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/dev_manager_mock.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/dev_manager_mock.h" + +namespace OHOS::DistributedKv { + +constexpr const char *PKG_NAME_EX = "_distributed_data"; + +DevManager::DevManager(const std::string &pkgName) : PKG_NAME(pkgName + PKG_NAME_EX) { } + +DevManager &DevManager::GetInstance() +{ + static DevManager instance(std::to_string(getpid())); + return instance; +} + +const DevManager::DetailInfo &DevManager::GetLocalDevice() +{ + if (BDevManager::devManager == nullptr) { + return invalidDetail_; + } + return BDevManager::devManager->GetLocalDevice(); +} + +std::string DevManager::ToUUID(const std::string &networkId) +{ + if (BDevManager::devManager == nullptr) { + return ""; + } + return BDevManager::devManager->ToUUID(networkId); +} + +std::string DevManager::ToNetworkId(const std::string &uuid) +{ + if (BDevManager::devManager == nullptr) { + return ""; + } + return BDevManager::devManager->ToNetworkId(uuid); +} + +std::string DevManager::GetUnEncryptedUuid() +{ + if (BDevManager::devManager == nullptr) { + return ""; + } + return BDevManager::devManager->GetUnEncryptedUuid(); +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/kvdb_notifier_client_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/kvdb_notifier_client_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e747cbc74c0ff5165cb71ddc48123209db31711 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/kvdb_notifier_client_mock.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/kvdb_notifier_client_mock.h" + +namespace OHOS::DistributedKv { + +KVDBNotifierClient::~KVDBNotifierClient() { } + +bool KVDBNotifierClient::IsChanged(const std::string &deviceId, DataType dataType) +{ + if (BKVDBNotifierClient::kVDBNotifierClient == nullptr) { + return false; + } + return BKVDBNotifierClient::kVDBNotifierClient->IsChanged(deviceId, dataType); +} + +void KVDBNotifierClient::AddSyncCallback(const std::shared_ptr callback, uint64_t sequenceId) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->AddSyncCallback(callback, sequenceId); + } +} + +void KVDBNotifierClient::DeleteSyncCallback(uint64_t sequenceId) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->DeleteSyncCallback(sequenceId); + } +} + +void KVDBNotifierClient::AddCloudSyncCallback(uint64_t sequenceId, const AsyncDetail &async) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->AddCloudSyncCallback(sequenceId, async); + } +} + +void KVDBNotifierClient::DeleteCloudSyncCallback(uint64_t sequenceId) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->DeleteCloudSyncCallback(sequenceId); + } +} + +void KVDBNotifierClient::AddSwitchCallback(const std::string &appId, std::shared_ptr observer) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->AddSwitchCallback(appId, observer); + } +} + +void KVDBNotifierClient::DeleteSwitchCallback(const std::string &appId, std::shared_ptr observer) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->DeleteSwitchCallback(appId, observer); + } +} + +void KVDBNotifierClient::SyncCompleted(uint64_t seqNum, ProgressDetail &&detail) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->SyncCompleted(seqNum, std::move(detail)); + } +} + +void KVDBNotifierClient::SyncCompleted(const std::map &results, uint64_t sequenceId) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->SyncCompleted(results, sequenceId); + } +} + +void KVDBNotifierClient::OnRemoteChange(const std::map &mask, int32_t dataType) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->OnRemoteChange(mask, dataType); + } +} + +void KVDBNotifierClient::OnSwitchChange(const SwitchNotification ¬ification) +{ + if (BKVDBNotifierClient::kVDBNotifierClient != nullptr) { + return BKVDBNotifierClient::kVDBNotifierClient->OnSwitchChange(notification); + } +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/kvdb_service_client_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/kvdb_service_client_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b83820cf27de11b9e61e0389f21c16d50592cea --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/kvdb_service_client_mock.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/kvdb_service_client_mock.h" + +namespace OHOS::DistributedKv { + +KVDBServiceClient::KVDBServiceClient(const sptr &handle) : IRemoteProxy(handle) { } + +std::shared_ptr KVDBServiceClient::GetInstance() +{ + if (BKVDBServiceClient::kVDBServiceClient == nullptr) { + return nullptr; + } + return BKVDBServiceClient::kVDBServiceClient->GetInstance(); +} + +sptr KVDBServiceClient::GetServiceAgent(const AppId &appId) +{ + if (BKVDBServiceClient::kVDBServiceClient == nullptr) { + return nullptr; + } + return BKVDBServiceClient::kVDBServiceClient->GetServiceAgent(appId); +} + +void KVDBServiceClient::ServiceDeath::OnRemoteDied() +{ +} + +Status KVDBServiceClient::GetStoreIds(const AppId &appId, std::vector &storeIds) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::BeforeCreate(const AppId &appId, const StoreId &storeId, const Options &options) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::AfterCreate( + const AppId &appId, const StoreId &storeId, const Options &options, const std::vector &password) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::Delete(const AppId &appId, const StoreId &storeId) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::Close(const AppId &appId, const StoreId &storeId) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::Sync(const AppId &appId, const StoreId &storeId, SyncInfo &syncInfo) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::CloudSync(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::NotifyDataChange(const AppId &appId, const StoreId &storeId, uint64_t delay) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::RegServiceNotifier(const AppId &appId, sptr notifier) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::UnregServiceNotifier(const AppId &appId) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::SetSyncParam(const AppId &appId, const StoreId &storeId, const KvSyncParam &syncParam) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::GetSyncParam(const AppId &appId, const StoreId &storeId, KvSyncParam &syncParam) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::EnableCapability(const AppId &appId, const StoreId &storeId) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::DisableCapability(const AppId &appId, const StoreId &storeId) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::SetCapability(const AppId &appId, const StoreId &storeId, + const std::vector &local, const std::vector &remote) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::AddSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::RmvSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::Subscribe(const AppId &appId, const StoreId &storeId, sptr observer) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::Unsubscribe(const AppId &appId, const StoreId &storeId, sptr observer) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::GetBackupPassword( + const AppId &appId, const StoreId &storeId, std::vector &password, int32_t passwordType) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::PutSwitch(const AppId &appId, const SwitchData &data) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::GetSwitch(const AppId &appId, const std::string &networkId, SwitchData &data) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::SubscribeSwitchData(const AppId &appId) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::UnsubscribeSwitchData(const AppId &appId) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::SetConfig(const AppId &appId, const StoreId &storeId, const StoreConfig &storeConfig) +{ + return KVDBServiceClientMock::status; +} + +Status KVDBServiceClient::RemoveDeviceData(const AppId &appId, const StoreId &storeId, const std::string &device) +{ + return KVDBServiceClientMock::status; +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/observer_bridge_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/observer_bridge_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5d1e85e47aad825515c6bfa54e9403c03ad6459 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/observer_bridge_mock.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/observer_bridge_mock.h" + +namespace OHOS::DistributedKv { +ObserverBridge::ObserverBridge(AppId appId, StoreId store, std::shared_ptr observer, const Convertor &cvt) + : appId_(std::move(appId)), storeId_(std::move(store)), observer_(std::move(observer)), convert_(cvt) +{ +} + +ObserverBridge::~ObserverBridge() { } + +void ObserverBridge::OnServiceDeath() +{ + if (BObserverBridge::observerBridge != nullptr) { + return BObserverBridge::observerBridge->OnServiceDeath(); + } +} + +Status ObserverBridge::RegisterRemoteObserver(uint32_t realType) +{ + if (BObserverBridge::observerBridge != nullptr) { + return BObserverBridge::observerBridge->RegisterRemoteObserver(realType); + } + return ERROR; +} + +Status ObserverBridge::UnregisterRemoteObserver(uint32_t realType) +{ + return SUCCESS; +} + +void ObserverBridge::OnChange(const DBChangedData &data) { } + +ObserverBridge::ObserverClient::ObserverClient(std::shared_ptr observer, const Convertor &cvt) + : KvStoreObserverClient(observer), convert_(cvt), realType_(0) +{ +} + +void ObserverBridge::ObserverClient::OnChange(const ChangeNotification &data) { } + +void ObserverBridge::ObserverClient::OnChange(const DataOrigin &origin, Keys &&keys) { } + +template +std::vector ObserverBridge::ConvertDB(const T &dbEntries, std::string &deviceId, const Convertor &convert) +{ + std::vector entries(dbEntries.size()); + return entries; +} + +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/security_manager_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/security_manager_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e9be9cacaf981324e0de173d4b24efe3682f4be --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/security_manager_mock.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/security_manager_mock.h" + +namespace OHOS::DistributedKv { +SecurityManager::SecurityManager() { } + +SecurityManager::~SecurityManager() { } + +bool SecurityManager::SaveDBPassword( + const std::string &name, const std::string &path, const DistributedDB::CipherPassword &key) +{ + if (BSecurityManager::securityManager == nullptr) { + return false; + } + return BSecurityManager::securityManager->SaveDBPassword(name, path, key); +} + +SecurityManager &SecurityManager::GetInstance() +{ + static SecurityManager instance; + return instance; +} + +SecurityManager::DBPassword SecurityManager::GetDBPassword( + const std::string &name, const std::string &path, bool needCreate) +{ + if (BSecurityManager::securityManager == nullptr) { + SecurityManager::DBPassword dbPassword; + return dbPassword; + } + return BSecurityManager::securityManager->GetDBPassword(name, path, needCreate); +} + +void SecurityManager::DelDBPassword(const std::string &name, const std::string &path) +{ +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/store_util_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/store_util_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b457f6bfd24cbe9e787c2762ad6d8f151fd3ab0 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/store_util_mock.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/store_util_mock.h" +#include "types.h" + +namespace OHOS::DistributedKv { + +bool StoreUtil::IsFileExist(const std::string &name) +{ + if (BStoreUtil::storeUtil == nullptr) { + return false; + } + return BStoreUtil::storeUtil->IsFileExist(name); +} + +bool StoreUtil::Remove(const std::string &path) +{ + if (BStoreUtil::storeUtil == nullptr) { + return false; + } + return BStoreUtil::storeUtil->Remove(path); +} + +Status StoreUtil::ConvertStatus(StoreUtil::DBStatus status) +{ + if (BStoreUtil::storeUtil == nullptr) { + return Status::ERROR; + } + return BStoreUtil::storeUtil->ConvertStatus(status); +} + +StoreUtil::DBSecurity StoreUtil::GetDBSecurity(int32_t secLevel) +{ + if (BStoreUtil::storeUtil == nullptr) { + return { DistributedDB::NOT_SET, DistributedDB::ECE }; + } + return BStoreUtil::storeUtil->GetDBSecurity(secLevel); +} + +bool StoreUtil::InitPath(const std::string &path) +{ + if (BStoreUtil::storeUtil == nullptr) { + return false; + } + return BStoreUtil::storeUtil->InitPath(path); +} + +StoreUtil::DBIndexType StoreUtil::GetDBIndexType(IndexType type) +{ + if (BStoreUtil::storeUtil == nullptr) { + return DistributedDB::HASH; + } + return BStoreUtil::storeUtil->GetDBIndexType(type); +} + +std::vector StoreUtil::GetSubPath(const std::string &path) +{ + if (BStoreUtil::storeUtil == nullptr) { + std::vector vec; + return vec; + } + return BStoreUtil::storeUtil->GetSubPath(path); +} + +std::vector StoreUtil::GetFiles(const std::string &path) +{ + if (BStoreUtil::storeUtil == nullptr) { + std::vector fileInfos; + return fileInfos; + } + return BStoreUtil::storeUtil->GetFiles(path); +} + +bool StoreUtil::Rename(const std::string &oldName, const std::string &newName) +{ + if (BStoreUtil::storeUtil == nullptr) { + return false; + } + return BStoreUtil::storeUtil->Rename(oldName, newName); +} + +std::string StoreUtil::Anonymous(const std::string &name) +{ + if (BStoreUtil::storeUtil == nullptr) { + return ""; + } + return BStoreUtil::storeUtil->Anonymous(name); +} + +uint32_t StoreUtil::Anonymous(const void *ptr) +{ + if (BStoreUtil::storeUtil == nullptr) { + return 0; + } + return BStoreUtil::storeUtil->Anonymous(ptr); +} + +bool StoreUtil::RemoveRWXForOthers(const std::string &path) +{ + if (BStoreUtil::storeUtil == nullptr) { + return false; + } + return BStoreUtil::storeUtil->RemoveRWXForOthers(path); +} + +bool StoreUtil::CreateFile(const std::string &name) +{ + if (BStoreUtil::storeUtil == nullptr) { + return false; + } + return BStoreUtil::storeUtil->CreateFile(name); +} + +void StoreUtil::Flush() +{ +} + +int32_t StoreUtil::GetSecLevel(StoreUtil::DBSecurity dbSec) +{ + return NO_LABEL; +} + +uint64_t StoreUtil::GenSequenceId() +{ + return 0; +} + +StoreUtil::DBMode StoreUtil::GetDBMode(SyncMode syncMode) +{ + DBMode dbMode = DBMode::SYNC_MODE_PULL_ONLY; + return dbMode; +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/task_executor_mock.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/task_executor_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d554af14c7d29264f6824255f0be2c02425dd962 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src/task_executor_mock.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/task_executor_mock.h" + +namespace OHOS { +TaskExecutor &TaskExecutor::GetInstance() +{ + static TaskExecutor instance; + return instance; +} + +TaskExecutor::~TaskExecutor() +{ + pool_ = nullptr; +} + +TaskExecutor::TaskId TaskExecutor::Schedule(Duration delay, const Task &task, Duration interval, uint64_t times) +{ + if (BTaskExecutor::taskExecutor == nullptr) { + return INVALID_TASK_ID; + } + return BTaskExecutor::taskExecutor->Schedule(delay, task, interval, times); +} + +TaskExecutor::TaskId TaskExecutor::Execute(const Task &task) +{ + return INVALID_TASK_ID; +} + +bool TaskExecutor::Remove(TaskExecutor::TaskId taskId, bool wait) +{ + return true; +} + +TaskExecutor::TaskId TaskExecutor::Reset(TaskExecutor::TaskId taskId, Duration interval) +{ + return INVALID_TASK_ID; +} + +void TaskExecutor::SetExecutors(std::shared_ptr executors) { } + +void TaskExecutor::GenerateExecutors() { } +} // namespace OHOS \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/security_manager_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/security_manager_test.cpp index 8d3222522d6f9624a21487776b50e3d45b27da9d..23898f55b5030c9b88f53bb5d21e707753028c7b 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/security_manager_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/security_manager_test.cpp @@ -16,9 +16,9 @@ #include #include "block_data.h" +#include "log_print.h" #include "security_manager.h" #include "store_util.h" -#include "log_print.h" namespace OHOS::Test { using namespace testing::ext; @@ -31,30 +31,26 @@ public: void TearDown(); }; -void SecurityManagerTest::SetUpTestCase(void) -{} +void SecurityManagerTest::SetUpTestCase(void) { } -void SecurityManagerTest::TearDownTestCase(void) -{} +void SecurityManagerTest::TearDownTestCase(void) { } -void SecurityManagerTest::SetUp(void) -{} +void SecurityManagerTest::SetUp(void) { } -void SecurityManagerTest::TearDown(void) -{} +void SecurityManagerTest::TearDown(void) { } /** -* @tc.name: DBPasswordTest -* @tc.desc: Test DBPassword function -* @tc.type: FUNC -*/ + * @tc.name: DBPasswordTest + * @tc.desc: Test DBPassword function + * @tc.type: FUNC + */ HWTEST_F(SecurityManagerTest, DBPasswordTest, TestSize.Level1) { SecurityManager::DBPassword passwd; EXPECT_FALSE(passwd.IsValid()); std::vector key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; passwd.SetValue(key.data(), key.size()); EXPECT_TRUE(passwd.IsValid()); @@ -66,10 +62,10 @@ HWTEST_F(SecurityManagerTest, DBPasswordTest, TestSize.Level1) } /** -* @tc.name: KeyFilesMultiLockTest -* @tc.desc: Test KeyFiles function -* @tc.type: FUNC -*/ + * @tc.name: KeyFilesMultiLockTest + * @tc.desc: Test KeyFiles function + * @tc.type: FUNC + */ HWTEST_F(SecurityManagerTest, KeyFilesMultiLockTest, TestSize.Level1) { std::string dbPath = "/data/service/el1/public/database/SecurityManagerTest"; @@ -89,10 +85,10 @@ HWTEST_F(SecurityManagerTest, KeyFilesMultiLockTest, TestSize.Level1) } /** -* @tc.name: KeyFilesTest -* @tc.desc: Test KeyFiles function -* @tc.type: FUNC -*/ + * @tc.name: KeyFilesTest + * @tc.desc: Test KeyFiles function + * @tc.type: FUNC + */ HWTEST_F(SecurityManagerTest, KeyFilesTest, TestSize.Level1) { std::string dbPath = "/data/service/el1/public/database/SecurityManagerTest"; @@ -119,10 +115,10 @@ HWTEST_F(SecurityManagerTest, KeyFilesTest, TestSize.Level1) } /** -* @tc.name: KeyFilesAutoLockTest -* @tc.desc: Test KeyFilesAutoLock function -* @tc.type: FUNC -*/ + * @tc.name: KeyFilesAutoLockTest + * @tc.desc: Test KeyFilesAutoLock function + * @tc.type: FUNC + */ HWTEST_F(SecurityManagerTest, KeyFilesAutoLockTest, TestSize.Level1) { std::string dbPath = "/data/service/el1/public/database/SecurityManagerTest"; @@ -143,4 +139,4 @@ HWTEST_F(SecurityManagerTest, KeyFilesAutoLockTest, TestSize.Level1) } EXPECT_TRUE(blockResult->GetValue()); } -} \ No newline at end of file +} // namespace OHOS::Test \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_get_top_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_get_top_test.cpp index 987e2641ab3f9c1d620ec3172c832cac08640251..c0bf8db02cec36c8549e8ae05c7706777ce7d34b 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_get_top_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_get_top_test.cpp @@ -18,8 +18,8 @@ #include #include "dev_manager.h" -#include "store_manager.h" #include "distributed_kv_data_manager.h" +#include "store_manager.h" #include "types.h" namespace OHOS::Test { @@ -53,8 +53,9 @@ Status SingleStoreImplGetTopTest::initStatus = Status::ERROR; void SingleStoreImplGetTopTest::SetUpTestCase(void) { DistributedKvDataManager manager; - Options options = { .createIfMissing = true, .encrypt = false, .autoSync = true, - .kvStoreType = KvStoreType::SINGLE_VERSION }; + Options options = { + .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION + }; options.area = EL1; options.securityLevel = S1; options.baseDir = std::string("/data/service/el1/public/database/odmf"); @@ -72,19 +73,17 @@ void SingleStoreImplGetTopTest::TearDownTestCase(void) (void)remove("/data/service/el1/public/database/odmf"); } -void SingleStoreImplGetTopTest::SetUp(void) -{} +void SingleStoreImplGetTopTest::SetUp(void) { } -void SingleStoreImplGetTopTest::TearDown(void) -{} +void SingleStoreImplGetTopTest::TearDown(void) { } /** -* @tc.name: GetEntries -* @tc.desc: get entries order by write time Asc -* @tc.type: FUNC -* @tc.require:I5OM83 -* @tc.author:ht -*/ + * @tc.name: GetEntries + * @tc.desc: get entries order by write time Asc + * @tc.type: FUNC + * @tc.require:I5OM83 + * @tc.author:ht + */ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeAsc, TestSize.Level0) { ASSERT_NE(singleKvStore, nullptr); @@ -94,8 +93,7 @@ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeAsc, TestSize.Leve entry.key = std::to_string(i).append("_k"); entry.value = std::to_string(i).append("_v"); input.push_back(entry); - auto status =singleKvStore->Put( - entry.key, entry.value); + auto status = singleKvStore->Put(entry.key, entry.value); ASSERT_EQ(status, SUCCESS); } DataQuery query; @@ -112,12 +110,12 @@ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeAsc, TestSize.Leve } /** -* @tc.name: GetEntries -* @tc.desc: get entries order by write time Desc -* @tc.type: FUNC -* @tc.require:I5OM83 -* @tc.author:ht -*/ + * @tc.name: GetEntries + * @tc.desc: get entries order by write time Desc + * @tc.type: FUNC + * @tc.require:I5OM83 + * @tc.author:ht + */ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeDesc, TestSize.Level0) { ASSERT_NE(singleKvStore, nullptr); @@ -127,8 +125,7 @@ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeDesc, TestSize.Lev entry.key = std::to_string(i).append("_k"); entry.value = std::to_string(i).append("_v"); input.push_back(entry); - auto status =singleKvStore->Put( - entry.key, entry.value); + auto status = singleKvStore->Put(entry.key, entry.value); ASSERT_EQ(status, SUCCESS); } DataQuery query; @@ -139,18 +136,18 @@ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeDesc, TestSize.Lev ASSERT_EQ(status, SUCCESS); ASSERT_EQ(output.size(), 10); for (size_t i = 0; i < output.size(); ++i) { - ASSERT_TRUE(input[9-i].key == output[i].key); - ASSERT_TRUE(input[9-i].value == output[i].value); + ASSERT_TRUE(input[9 - i].key == output[i].key); + ASSERT_TRUE(input[9 - i].value == output[i].value); } } /** -* @tc.name: GetEntries -* @tc.desc: get entries order by write time no prefix -* @tc.type: FUNC -* @tc.require:I5OM83 -* @tc.author:ht -*/ + * @tc.name: GetEntries + * @tc.desc: get entries order by write time no prefix + * @tc.type: FUNC + * @tc.require:I5OM83 + * @tc.author:ht + */ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeNoPrefix, TestSize.Level0) { ASSERT_NE(singleKvStore, nullptr); @@ -160,8 +157,7 @@ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeNoPrefix, TestSize entry.key = std::to_string(i).append("_k"); entry.value = std::to_string(i).append("_v"); input.push_back(entry); - auto status =singleKvStore->Put( - entry.key, entry.value); + auto status = singleKvStore->Put(entry.key, entry.value); ASSERT_EQ(status, SUCCESS); } singleKvStore->Put("test_key_1", "{\"name\":1}"); @@ -175,12 +171,12 @@ HWTEST_F(SingleStoreImplGetTopTest, GetEntriesOrderByWriteTimeNoPrefix, TestSize } /** -* @tc.name: GetResultSet -* @tc.desc: get result set order by write time Asc -* @tc.type: FUNC -* @tc.require:I5OM83 -* @tc.author:ht -*/ + * @tc.name: GetResultSet + * @tc.desc: get result set order by write time Asc + * @tc.type: FUNC + * @tc.require:I5OM83 + * @tc.author:ht + */ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeAsc, TestSize.Level0) { ASSERT_NE(singleKvStore, nullptr); @@ -190,12 +186,11 @@ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeAsc, TestSize.Le entry.key = std::to_string(i).append("_k"); entry.value = std::to_string(i).append("_v"); input.push_back(entry); - auto status =singleKvStore->Put( - entry.key, entry.value); + auto status = singleKvStore->Put(entry.key, entry.value); ASSERT_EQ(status, SUCCESS); } DataQuery query; - query.InKeys({"10_k", "11_k"}); + query.InKeys({ "10_k", "11_k" }); query.OrderByWriteTime(true); std::shared_ptr output; auto status = singleKvStore->GetResultSet(query, output); @@ -205,7 +200,7 @@ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeAsc, TestSize.Le for (size_t i = 0; i < 2; ++i) { output->MoveToNext(); Entry entry; - status=output->GetEntry(entry); + status = output->GetEntry(entry); ASSERT_EQ(status, SUCCESS); ASSERT_TRUE(input[i].key == entry.key); ASSERT_TRUE(input[i].value == entry.value); @@ -213,17 +208,19 @@ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeAsc, TestSize.Le } /** -* @tc.name: GetResultSet -* @tc.desc: get result set order by write time Desc -* @tc.type: FUNC -* @tc.require:I5OM83 -* @tc.author:ht -*/ + * @tc.name: GetResultSet + * @tc.desc: get result set order by write time Desc + * @tc.type: FUNC + * @tc.require:I5OM83 + * @tc.author:ht + */ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeDesc, TestSize.Level0) { ASSERT_NE(singleKvStore, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (size_t i = 10; i < 30; ++i) { Entry entry; @@ -231,8 +228,7 @@ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeDesc, TestSize.L entry.value = std::to_string(i).append("_v"); input.push_back(entry); dictionary[entry.key] = entry.value; - auto status =singleKvStore->Put( - entry.key, entry.value); + auto status = singleKvStore->Put(entry.key, entry.value); ASSERT_EQ(status, SUCCESS); } DataQuery query; @@ -247,23 +243,25 @@ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeDesc, TestSize.L output->MoveToNext(); Entry entry; output->GetEntry(entry); - ASSERT_TRUE(input[9-i].key == entry.key); - ASSERT_TRUE(input[9-i].value == entry.value); + ASSERT_TRUE(input[9 - i].key == entry.key); + ASSERT_TRUE(input[9 - i].value == entry.value); } } /** -* @tc.name: GetResultSet -* @tc.desc: get result set order by write time no prefix -* @tc.type: FUNC -* @tc.require:I5OM83 -* @tc.author:ht -*/ + * @tc.name: GetResultSet + * @tc.desc: get result set order by write time no prefix + * @tc.type: FUNC + * @tc.require:I5OM83 + * @tc.author:ht + */ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeNoPrefix, TestSize.Level0) { ASSERT_NE(singleKvStore, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (size_t i = 10; i < 30; ++i) { Entry entry; @@ -271,8 +269,7 @@ HWTEST_F(SingleStoreImplGetTopTest, GetResultSetOrderByWriteTimeNoPrefix, TestSi entry.value = std::to_string(i).append("_v"); input.push_back(entry); dictionary[entry.key] = entry.value; - auto status =singleKvStore->Put( - entry.key, entry.value); + auto status = singleKvStore->Put(entry.key, entry.value); ASSERT_EQ(status, SUCCESS); } singleKvStore->Put("test_key_1", "{\"name\":1}"); diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_mock_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..354614f9ef2e0898cfdd6a720f506f3334499ecc --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_mock_test.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "convertor.h" +#include "include/dev_manager_mock.h" +#include "include/kvdb_notifier_client_mock.h" +#include "include/kvdb_service_client_mock.h" +#include "include/observer_bridge_mock.h" +#include "include/task_executor_mock.h" +#include "kvstore_observer.h" +#include "single_store_impl.h" +#include "store_factory.h" +#include "store_manager.h" + +namespace OHOS::DistributedKv { +using namespace std; +using namespace testing; +using namespace DistributedDB; + +static StoreId storeId = { "single_test" }; +static AppId appId = { "rekey" }; + +class SingleStoreImplMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + +public: + using DBStatus = DistributedDB::DBStatus; + using DBStore = DistributedDB::KvStoreNbDelegate; + using Observer = DistributedKv::KvStoreObserver; + static inline shared_ptr devManagerMock = nullptr; + static inline shared_ptr kVDBServiceClientMock = nullptr; + static inline shared_ptr kVDBNotifierClientMock = nullptr; + static inline shared_ptr observerBridgeMock = nullptr; + static inline shared_ptr taskExecutorMock = nullptr; + std::shared_ptr CreateKVStore(bool autosync = false); +}; + +void SingleStoreImplMockTest::SetUp() { } + +void SingleStoreImplMockTest::TearDown() { } + +void SingleStoreImplMockTest::SetUpTestCase() +{ + GTEST_LOG_(INFO) << "SetUpTestCase enter"; + std::string baseDir = "/data/service/el1/public/database/SingleStoreImplTest"; + mkdir(baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); + devManagerMock = make_shared(); + BDevManager::devManager = devManagerMock; + kVDBServiceClientMock = make_shared(); + BKVDBServiceClient::kVDBServiceClient = kVDBServiceClientMock; + kVDBNotifierClientMock = make_shared(); + BKVDBNotifierClient::kVDBNotifierClient = kVDBNotifierClientMock; + observerBridgeMock = make_shared(); + BObserverBridge::observerBridge = observerBridgeMock; + taskExecutorMock = make_shared(); + BTaskExecutor::taskExecutor = taskExecutorMock; +} + +void SingleStoreImplMockTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "TearDownTestCase enter"; + BDevManager::devManager = nullptr; + devManagerMock = nullptr; + BKVDBServiceClient::kVDBServiceClient = nullptr; + kVDBServiceClientMock = nullptr; + BKVDBNotifierClient::kVDBNotifierClient = nullptr; + kVDBNotifierClientMock = nullptr; + BObserverBridge::observerBridge = nullptr; + observerBridgeMock = nullptr; + BTaskExecutor::taskExecutor = nullptr; + taskExecutorMock = nullptr; + std::string baseDir = "/data/service/el1/public/database/SingleStoreImplTest"; + (void)remove("/data/service/el1/public/database/SingleStoreImplTest"); +} + +std::shared_ptr SingleStoreImplMockTest::CreateKVStore(bool autosync) +{ + AppId appId = { "SingleStoreImplTest" }; + StoreId storeId = { "DestructorTest" }; + std::shared_ptr kvStore; + Options options; + options.kvStoreType = SINGLE_VERSION; + options.securityLevel = S2; + options.area = EL1; + options.autoSync = autosync; + options.baseDir = "/data/service/el1/public/database/SingleStoreImplTest"; + StoreFactory storeFactory; + auto dbManager = storeFactory.GetDBManager(options.baseDir, appId); + auto dbPassword = SecurityManager::GetInstance().GetDBPassword(storeId.storeId, options.baseDir, options.encrypt); + DBStatus dbStatus = DBStatus::DB_ERROR; + dbManager->GetKvStore(storeId, storeFactory.GetDBOption(options, dbPassword), + [&dbManager, &kvStore, &appId, &dbStatus, &options, &storeFactory](auto status, auto *store) { + dbStatus = status; + if (store == nullptr) { + return; + } + auto release = [dbManager](auto *store) { + dbManager->CloseKvStore(store); + }; + auto dbStore = std::shared_ptr(store, release); + storeFactory.SetDbConfig(dbStore); + const Convertor &convertor = *(storeFactory.convertors_[options.kvStoreType]); + kvStore = std::make_shared(dbStore, appId, options, convertor); + }); + return kvStore; +} + +/** + * @tc.name: IsRemoteChanged + * @tc.desc: is remote changed. + * @tc.type: FUNC + * @tc.require: + * @tc.author: cao zhijun + */ +HWTEST_F(SingleStoreImplMockTest, IsRemoteChanged, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-begin IsRemoteChanged"; + try { + EXPECT_CALL(*taskExecutorMock, Schedule(_, _, _, _)).Times(1); + std::shared_ptr kvStore; + kvStore = CreateKVStore(); + ASSERT_NE(kvStore, nullptr); + std::shared_ptr client = make_shared(nullptr); + ASSERT_NE(client, nullptr); + EXPECT_CALL(*devManagerMock, ToUUID(_)).WillOnce(Return("")); + bool ret = kvStore->IsRemoteChanged("123456789"); + EXPECT_TRUE(ret); + + EXPECT_CALL(*devManagerMock, ToUUID(_)).WillOnce(Return("123456789")); + EXPECT_CALL(*kVDBServiceClientMock, GetInstance()).WillOnce(Return(nullptr)); + ret = kvStore->IsRemoteChanged("123456789"); + EXPECT_TRUE(ret); + + EXPECT_CALL(*devManagerMock, ToUUID(_)).WillOnce(Return("123456789")); + EXPECT_CALL(*kVDBServiceClientMock, GetInstance()).WillOnce(Return(client)); + EXPECT_CALL(*kVDBServiceClientMock, GetServiceAgent(_)).WillOnce(Return(nullptr)); + ret = kvStore->IsRemoteChanged("123456789"); + EXPECT_TRUE(ret); + + sptr testAgent = new (std::nothrow) KVDBNotifierClient(); + ASSERT_NE(testAgent, nullptr); + EXPECT_CALL(*devManagerMock, ToUUID(_)).WillOnce(Return("123456789")); + EXPECT_CALL(*kVDBServiceClientMock, GetInstance()).WillOnce(Return(client)); + EXPECT_CALL(*kVDBServiceClientMock, GetServiceAgent(_)).WillOnce(Return(testAgent)); + EXPECT_CALL(*kVDBNotifierClientMock, IsChanged(_, _)).WillOnce(Return(true)); + ret = kvStore->IsRemoteChanged("123456789"); + EXPECT_TRUE(ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-an exception occurred by IsRemoteChanged."; + } + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-end IsRemoteChanged"; +} + +/** + * @tc.name: OnRemoteDied + * @tc.desc: remote died. + * @tc.type: FUNC + * @tc.require: + * @tc.author: cao zhijun + */ +HWTEST_F(SingleStoreImplMockTest, OnRemoteDied, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-begin OnRemoteDied"; + try { + EXPECT_CALL(*taskExecutorMock, Schedule(_, _, _, _)).Times(1); + std::shared_ptr kvStore; + kvStore = CreateKVStore(); + ASSERT_NE(kvStore, nullptr); + kvStore->taskId_ = 1; + kvStore->OnRemoteDied(); + + kvStore->taskId_ = 0; + shared_ptr observer = make_shared(); + shared_ptr observer1 = make_shared(); + Convertor cvt; + Convertor cvt1; + shared_ptr obsBridge = make_shared(appId, storeId, observer, cvt); + shared_ptr obsBridge1 = make_shared(appId, storeId, observer1, cvt1); + + uint32_t firs = 0; + firs |= SUBSCRIBE_TYPE_REMOTE; + pair> one(0, obsBridge); + pair> two(firs, obsBridge1); + + kvStore->observers_.Insert(uintptr_t(observer.get()), one); + kvStore->observers_.Insert(uintptr_t(observer1.get()), two); + EXPECT_CALL(*observerBridgeMock, OnServiceDeath()).Times(1); + EXPECT_CALL(*taskExecutorMock, Schedule(_, _, _, _)).WillOnce(Return(1)); + kvStore->OnRemoteDied(); + kvStore->observers_.Erase(uintptr_t(observer.get())); + kvStore->observers_.Erase(uintptr_t(observer1.get())); + EXPECT_TRUE(kvStore->taskId_ == 1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-an exception occurred by OnRemoteDied."; + } + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-end OnRemoteDied"; +} + +/** + * @tc.name: Register + * @tc.desc: register. + * @tc.type: FUNC + * @tc.require: + * @tc.author: cao zhijun + */ +HWTEST_F(SingleStoreImplMockTest, Register, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-begin Register"; + try { + EXPECT_CALL(*taskExecutorMock, Schedule(_, _, _, _)).Times(1); + std::shared_ptr kvStore; + kvStore = CreateKVStore(); + ASSERT_NE(kvStore, nullptr); + + shared_ptr observer = make_shared(); + shared_ptr observer1 = make_shared(); + Convertor cvt; + Convertor cvt1; + shared_ptr obsBridge = make_shared(appId, storeId, observer, cvt); + shared_ptr obsBridge1 = make_shared(appId, storeId, observer1, cvt1); + + uint32_t firs = 0; + firs |= SUBSCRIBE_TYPE_CLOUD; + pair> one(0, obsBridge); + pair> two(firs, obsBridge1); + + kvStore->observers_.Insert(uintptr_t(observer.get()), one); + kvStore->observers_.Insert(uintptr_t(observer1.get()), two); + EXPECT_CALL(*observerBridgeMock, RegisterRemoteObserver(_)).WillOnce(Return(ERROR)); + EXPECT_CALL(*taskExecutorMock, Schedule(_, _, _, _)).WillOnce(Return(1)); + kvStore->Register(); + EXPECT_TRUE(kvStore->taskId_ == 1); + + EXPECT_CALL(*observerBridgeMock, RegisterRemoteObserver(_)).WillOnce(Return(SUCCESS)); + kvStore->Register(); + kvStore->observers_.Erase(uintptr_t(observer.get())); + kvStore->observers_.Erase(uintptr_t(observer1.get())); + EXPECT_TRUE(kvStore->taskId_ == 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-an exception occurred by Register."; + } + GTEST_LOG_(INFO) << "SingleStoreImplMockTest-end Register"; +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp index 247bff5e6ee2e1599351547885c5e6646fee52e5..b4f9567bd6b3e75d670b4b740fb6fbadcb5a7ad2 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp @@ -18,16 +18,16 @@ #include "block_data.h" #include "dev_manager.h" +#include "device_manager.h" #include "distributed_kv_data_manager.h" +#include "dm_device_info.h" #include "file_ex.h" #include "kv_store_nb_delegate.h" +#include "single_store_impl.h" +#include "store_factory.h" #include "store_manager.h" #include "sys/stat.h" #include "types.h" -#include "single_store_impl.h" -#include "store_factory.h" -#include "dm_device_info.h" -#include "device_manager.h" using namespace testing::ext; using namespace OHOS::DistributedKv; @@ -116,8 +116,8 @@ void SingleStoreImplTest::TearDown(void) ASSERT_EQ(status, SUCCESS); } -std::shared_ptr SingleStoreImplTest::CreateKVStore(std::string storeIdTest, KvStoreType type, - bool encrypt, bool backup) +std::shared_ptr SingleStoreImplTest::CreateKVStore( + std::string storeIdTest, KvStoreType type, bool encrypt, bool backup) { Options options; options.kvStoreType = type; @@ -146,21 +146,22 @@ std::shared_ptr SingleStoreImplTest::CreateKVStore(bool autosyn options.baseDir = "/data/service/el1/public/database/SingleStoreImplTest"; StoreFactory storeFactory; auto dbManager = storeFactory.GetDBManager(options.baseDir, appId); - auto dbPassword = - SecurityManager::GetInstance().GetDBPassword(storeId.storeId, options.baseDir, options.encrypt); + auto dbPassword = SecurityManager::GetInstance().GetDBPassword(storeId.storeId, options.baseDir, options.encrypt); DBStatus dbStatus = DBStatus::DB_ERROR; - dbManager->GetKvStore(storeId, storeFactory.GetDBOption(options, dbPassword), - [&dbManager, &kvStore, &appId, &dbStatus, &options, &storeFactory](auto status, auto *store) { - dbStatus = status; - if (store == nullptr) { - return; - } - auto release = [dbManager](auto *store) { dbManager->CloseKvStore(store); }; - auto dbStore = std::shared_ptr(store, release); - storeFactory.SetDbConfig(dbStore); - const Convertor &convertor = *(storeFactory.convertors_[options.kvStoreType]); - kvStore = std::make_shared(dbStore, appId, options, convertor); - }); + dbManager->GetKvStore(storeId, storeFactory.GetDBOption(options, dbPassword), + [&dbManager, &kvStore, &appId, &dbStatus, &options, &storeFactory](auto status, auto *store) { + dbStatus = status; + if (store == nullptr) { + return; + } + auto release = [dbManager](auto *store) { + dbManager->CloseKvStore(store); + }; + auto dbStore = std::shared_ptr(store, release); + storeFactory.SetDbConfig(dbStore); + const Convertor &convertor = *(storeFactory.convertors_[options.kvStoreType]); + kvStore = std::make_shared(dbStore, appId, options, convertor); + }); return kvStore; } @@ -561,8 +562,9 @@ HWTEST_F(SingleStoreImplTest, GetEntries_Prefix, TestSize.Level0) std::vector output; status = kvStore_->GetEntries({ "" }, output); ASSERT_EQ(status, SUCCESS); - std::sort(output.begin(), output.end(), - [](const Entry &entry, const Entry &sentry) { return entry.key.Data() < sentry.key.Data(); }); + std::sort(output.begin(), output.end(), [](const Entry &entry, const Entry &sentry) { + return entry.key.Data() < sentry.key.Data(); + }); for (int i = 0; i < 10; ++i) { ASSERT_TRUE(input[i].key == output[i].key); ASSERT_TRUE(input[i].value == output[i].value); @@ -684,8 +686,9 @@ HWTEST_F(SingleStoreImplTest, GetEntries_DataQuery, TestSize.Level0) std::vector output; status = kvStore_->GetEntries(query, output); ASSERT_EQ(status, SUCCESS); - std::sort(output.begin(), output.end(), - [](const Entry &entry, const Entry &sentry) { return entry.key.Data() < sentry.key.Data(); }); + std::sort(output.begin(), output.end(), [](const Entry &entry, const Entry &sentry) { + return entry.key.Data() < sentry.key.Data(); + }); ASSERT_LE(output.size(), 2); for (size_t i = 0; i < output.size(); ++i) { ASSERT_TRUE(input[i].key == output[i].key); @@ -704,7 +707,9 @@ HWTEST_F(SingleStoreImplTest, GetResultSet_Prefix, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (int i = 0; i < 10; ++i) { Entry entry; @@ -741,7 +746,9 @@ HWTEST_F(SingleStoreImplTest, GetResultSet_Query, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (int i = 0; i < 10; ++i) { Entry entry; @@ -780,7 +787,9 @@ HWTEST_F(SingleStoreImplTest, CloseResultSet, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (int i = 0; i < 10; ++i) { Entry entry; @@ -1148,7 +1157,9 @@ HWTEST_F(SingleStoreImplTest, GetCount, TestSize.Level0) { ASSERT_NE(kvStore_, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (int i = 0; i < 10; ++i) { Entry entry; @@ -1203,7 +1214,9 @@ HWTEST_F(SingleStoreImplTest, RemoveDeviceData, TestSize.Level0) auto store = CreateKVStore("DeviceKVStore", DEVICE_COLLABORATION, false, true); ASSERT_NE(store, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (int i = 0; i < 10; ++i) { Entry entry; @@ -1218,8 +1231,7 @@ HWTEST_F(SingleStoreImplTest, RemoveDeviceData, TestSize.Level0) status = store->GetCount({}, count); ASSERT_EQ(status, SUCCESS); ASSERT_EQ(count, 10); - ChangeOwnerToService( - "/data/service/el1/public/database/SingleStoreImplTest", + ChangeOwnerToService("/data/service/el1/public/database/SingleStoreImplTest", "703c6ec99aa7226bb9f6194cdd60e1873ea9ee52faebd55657ade9f5a5cc3cbd"); status = store->RemoveDeviceData(DevManager::GetInstance().GetLocalDevice().networkId); ASSERT_EQ(status, SUCCESS); @@ -1259,12 +1271,8 @@ HWTEST_F(SingleStoreImplTest, RegisterSyncCallback, TestSize.Level0) ASSERT_NE(kvStore_, nullptr); class TestSyncCallback : public KvStoreSyncCallback { public: - void SyncCompleted(const map &results) override - { - } - void SyncCompleted(const std::map &results, uint64_t sequenceId) override - { - } + void SyncCompleted(const map &results) override { } + void SyncCompleted(const std::map &results, uint64_t sequenceId) override { } }; auto callback = std::make_shared(); auto status = kvStore_->RegisterSyncCallback(callback); @@ -1283,12 +1291,8 @@ HWTEST_F(SingleStoreImplTest, UnRegisterSyncCallback, TestSize.Level0) ASSERT_NE(kvStore_, nullptr); class TestSyncCallback : public KvStoreSyncCallback { public: - void SyncCompleted(const map &results) override - { - } - void SyncCompleted(const std::map &results, uint64_t sequenceId) override - { - } + void SyncCompleted(const map &results) override { } + void SyncCompleted(const std::map &results, uint64_t sequenceId) override { } }; auto callback = std::make_shared(); auto status = kvStore_->RegisterSyncCallback(callback); @@ -1298,12 +1302,12 @@ HWTEST_F(SingleStoreImplTest, UnRegisterSyncCallback, TestSize.Level0) } /** -* @tc.name: disableBackup -* @tc.desc: Disable backup -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: disableBackup + * @tc.desc: Disable backup + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(SingleStoreImplTest, disableBackup, TestSize.Level0) { AppId appId = { "SingleStoreImplTest" }; @@ -1416,7 +1420,9 @@ HWTEST_F(SingleStoreImplTest, RemoveNullDeviceData, TestSize.Level0) auto store = CreateKVStore("DeviceKVStore", DEVICE_COLLABORATION, false, true); ASSERT_NE(store, nullptr); std::vector input; - auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); }; + auto cmp = [](const Key &entry, const Key &sentry) { + return entry.Data() < sentry.Data(); + }; std::map dictionary(cmp); for (int i = 0; i < 10; ++i) { Entry entry; @@ -1432,8 +1438,7 @@ HWTEST_F(SingleStoreImplTest, RemoveNullDeviceData, TestSize.Level0) ASSERT_EQ(status, SUCCESS); ASSERT_EQ(count, 10); const string device = { "" }; - ChangeOwnerToService( - "/data/service/el1/public/database/SingleStoreImplTest", + ChangeOwnerToService("/data/service/el1/public/database/SingleStoreImplTest", "703c6ec99aa7226bb9f6194cdd60e1873ea9ee52faebd55657ade9f5a5cc3cbd"); status = store->RemoveDeviceData(device); ASSERT_EQ(status, SUCCESS); @@ -1746,13 +1751,13 @@ HWTEST_F(SingleStoreImplTest, StaticStoreAsyncGet, TestSize.Level0) Status status; kvStore = StoreManager::GetInstance().GetKVStore(appId, storeId, options, status); ASSERT_NE(kvStore, nullptr); - BlockData blockData{ 1, false }; - std::function result = [&blockData](Status status, Value&& value) { + BlockData blockData { 1, false }; + std::function result = [&blockData](Status status, Value &&value) { ASSERT_EQ(status, Status::NOT_FOUND); blockData.SetValue(true); }; auto networkId = DevManager::GetInstance().GetLocalDevice().networkId; - kvStore->Get({"key"}, networkId, result); + kvStore->Get({ "key" }, networkId, result); blockData.GetValue(); status = StoreManager::GetInstance().CloseKVStore(appId, storeId); ASSERT_EQ(status, SUCCESS); @@ -1781,14 +1786,14 @@ HWTEST_F(SingleStoreImplTest, StaticStoreAsyncGetEntries, TestSize.Level0) Status status; kvStore = StoreManager::GetInstance().GetKVStore(appId, storeId, options, status); ASSERT_NE(kvStore, nullptr); - BlockData blockData{ 1, false }; - std::function&&)> result = - [&blockData](Status status, std::vector&& value) { - ASSERT_EQ(status, Status::SUCCESS); - blockData.SetValue(true); + BlockData blockData { 1, false }; + std::function &&)> result = [&blockData]( + Status status, std::vector &&value) { + ASSERT_EQ(status, Status::SUCCESS); + blockData.SetValue(true); }; auto networkId = DevManager::GetInstance().GetLocalDevice().networkId; - kvStore->GetEntries({"key"}, networkId, result); + kvStore->GetEntries({ "key" }, networkId, result); blockData.GetValue(); status = StoreManager::GetInstance().CloseKVStore(appId, storeId); ASSERT_EQ(status, SUCCESS); @@ -1819,13 +1824,13 @@ HWTEST_F(SingleStoreImplTest, DynamicStoreAsyncGet, TestSize.Level0) ASSERT_NE(kvStore, nullptr); status = kvStore->Put({ "Put Test" }, { "Put Value" }); auto networkId = DevManager::GetInstance().GetLocalDevice().networkId; - BlockData blockData{ 1, false }; - std::function result = [&blockData](Status status, Value&& value) { + BlockData blockData { 1, false }; + std::function result = [&blockData](Status status, Value &&value) { ASSERT_EQ(status, Status::SUCCESS); ASSERT_EQ(value.ToString(), "Put Value"); blockData.SetValue(true); }; - kvStore->Get({"Put Test"}, networkId, result); + kvStore->Get({ "Put Test" }, networkId, result); blockData.GetValue(); status = StoreManager::GetInstance().CloseKVStore(appId, storeId); ASSERT_EQ(status, SUCCESS); @@ -1864,14 +1869,14 @@ HWTEST_F(SingleStoreImplTest, DynamicStoreAsyncGetEntries, TestSize.Level0) status = kvStore->PutBatch(entries); ASSERT_EQ(status, SUCCESS); auto networkId = DevManager::GetInstance().GetLocalDevice().networkId; - BlockData blockData{ 1, false }; - std::function&&)> result = - [entries, &blockData](Status status, std::vector&& value) { - ASSERT_EQ(status, Status::SUCCESS); - ASSERT_EQ(value.size(), entries.size()); - blockData.SetValue(true); + BlockData blockData { 1, false }; + std::function &&)> result = [entries, &blockData]( + Status status, std::vector &&value) { + ASSERT_EQ(status, Status::SUCCESS); + ASSERT_EQ(value.size(), entries.size()); + blockData.SetValue(true); }; - kvStore->GetEntries({"key_"}, networkId, result); + kvStore->GetEntries({ "key_" }, networkId, result); blockData.GetValue(); status = StoreManager::GetInstance().CloseKVStore(appId, storeId); ASSERT_EQ(status, SUCCESS); @@ -2029,4 +2034,33 @@ HWTEST_F(SingleStoreImplTest, DoAutoSync001, TestSize.Level1) ASSERT_EQ(status, SUCCESS); ASSERT_EQ(!kvStore->autoSync_ || !kvStore->isApplication_, false); } + +/** + * @tc.name: IsRemoteChanged + * @tc.desc: is remote changed + * @tc.type: FUNC + */ +HWTEST_F(SingleStoreImplTest, IsRemoteChanged, TestSize.Level0) +{ + std::shared_ptr kvStore; + kvStore = CreateKVStore(); + ASSERT_NE(kvStore, nullptr); + bool ret = kvStore->IsRemoteChanged(""); + ASSERT_TRUE(ret); +} + +/** + * @tc.name: ReportDBCorruptedFault + * @tc.desc: report DB corrupted fault + * @tc.type: FUNC + */ +HWTEST_F(SingleStoreImplTest, ReportDBCorruptedFault, TestSize.Level0) +{ + std::shared_ptr kvStore; + kvStore = CreateKVStore(); + ASSERT_NE(kvStore, nullptr); + Status status = DATA_CORRUPTED; + kvStore->ReportDBCorruptedFault(status); + EXPECT_TRUE(status == DATA_CORRUPTED); +} } // namespace OHOS::Test \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_mock_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8acfb085b1ae7877cbb59ab51af318f9c5ec72e --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_mock_test.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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/security_manager_mock.h" +#include "include/store_util_mock.h" +#include "store_factory.h" + +namespace OHOS::DistributedKv { +using namespace std; +using namespace testing; + +static StoreId storeId = { "single_test" }; +static AppId appId = { "rekey" }; +static Options options = { + .encrypt = false, + .securityLevel = S1, + .area = EL1, + .kvStoreType = SINGLE_VERSION, + .baseDir = "/data/service/el1/public/database/rekey", +}; + +class StoreFactoryMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + +public: + using DBManager = DistributedDB::KvStoreDelegateManager; + using DBPassword = SecurityManager::DBPassword; + static inline shared_ptr storeUtilMock = nullptr; + static inline shared_ptr securityManagerMock = nullptr; +}; + +void StoreFactoryMockTest::SetUp() +{ + std::string baseDir = "/data/service/el1/public/database/rekey"; + mkdir(baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); +} + +void StoreFactoryMockTest::TearDown() +{ + (void)remove("/data/service/el1/public/database/rekey"); +} + +void StoreFactoryMockTest::SetUpTestCase() +{ + GTEST_LOG_(INFO) << "SetUpTestCase enter"; + storeUtilMock = make_shared(); + StoreUtilMock::storeUtil = storeUtilMock; + securityManagerMock = make_shared(); + BSecurityManager::securityManager = securityManagerMock; +} + +void StoreFactoryMockTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "TearDownTestCase enter"; + StoreUtilMock::storeUtil = nullptr; + storeUtilMock = nullptr; + BSecurityManager::securityManager = nullptr; + securityManagerMock = nullptr; +} + +/** + * @tc.name: RekeyRecover_001 + * @tc.desc: Rekey recover test. + * @tc.type: FUNC + * @tc.require: + * @tc.author: cao zhijun + */ +HWTEST_F(StoreFactoryMockTest, RekeyRecover_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "StoreFactoryMockTest-begin RekeyRecover_001"; + try { + std::string path = options.GetDatabaseDir(); + std::shared_ptr dbManager = std::make_shared(appId.appId, "default"); + DBPassword dbPassword; + + EXPECT_CALL(*storeUtilMock, IsFileExist(_)).WillOnce(Return(true)); + EXPECT_CALL(*securityManagerMock, GetDBPassword(_, _, _)).WillOnce(Return(SecurityManager::DBPassword())); + EXPECT_CALL(*storeUtilMock, GetDBSecurity(_)).Times(1); + EXPECT_CALL(*storeUtilMock, GetDBIndexType(_)).Times(1); + EXPECT_CALL(*storeUtilMock, ConvertStatus(_)).WillOnce(Return(SUCCESS)); + EXPECT_CALL(*storeUtilMock, Remove(_)).WillOnce(Return(true)); + auto status = StoreFactory::GetInstance().RekeyRecover(storeId, path, dbPassword, dbManager, options); + EXPECT_TRUE(status == SUCCESS); + + EXPECT_CALL(*storeUtilMock, IsFileExist(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*securityManagerMock, GetDBPassword(_, _, _)).Times(2); + EXPECT_CALL(*storeUtilMock, GetDBSecurity(_)).Times(2); + EXPECT_CALL(*storeUtilMock, GetDBIndexType(_)).Times(2); + EXPECT_CALL(*storeUtilMock, ConvertStatus(_)).WillOnce(Return(ERROR)).WillOnce(Return(ERROR)); + status = StoreFactory::GetInstance().RekeyRecover(storeId, path, dbPassword, dbManager, options); + EXPECT_TRUE(status != SUCCESS); + + EXPECT_CALL(*storeUtilMock, IsFileExist(_)).WillOnce(Return(true)).WillOnce(Return(false)); + EXPECT_CALL(*securityManagerMock, GetDBPassword(_, _, _)).Times(1); + EXPECT_CALL(*storeUtilMock, GetDBSecurity(_)).Times(1); + EXPECT_CALL(*storeUtilMock, GetDBIndexType(_)).Times(1); + EXPECT_CALL(*storeUtilMock, ConvertStatus(_)).WillOnce(Return(ERROR)); + status = StoreFactory::GetInstance().RekeyRecover(storeId, path, dbPassword, dbManager, options); + EXPECT_TRUE(status != SUCCESS); + + EXPECT_CALL(*storeUtilMock, IsFileExist(_)).WillOnce(Return(false)).WillOnce(Return(true)); + EXPECT_CALL(*securityManagerMock, GetDBPassword(_, _, _)).Times(1); + EXPECT_CALL(*storeUtilMock, GetDBSecurity(_)).Times(1); + EXPECT_CALL(*storeUtilMock, GetDBIndexType(_)).Times(1); + EXPECT_CALL(*storeUtilMock, ConvertStatus(_)).WillOnce(Return(SUCCESS)); + EXPECT_CALL(*securityManagerMock, SaveDBPassword(_, _, _)).Times(1); + status = StoreFactory::GetInstance().RekeyRecover(storeId, path, dbPassword, dbManager, options); + EXPECT_TRUE(status == SUCCESS); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "StoreFactoryMockTest-an exception occurred by GetSrcPath."; + } + GTEST_LOG_(INFO) << "StoreFactoryMockTest-end RekeyRecover_001"; +} +} // namespace OHOS::DistributedKv \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp index 6eb7faf78ed857299e5a38e1aee75e5309d0778a..9c932e503067581810aa5909c728bf7521a5a297 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp @@ -1,17 +1,17 @@ /* -* 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. -*/ + * 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 "store_factory.h" #include @@ -61,19 +61,15 @@ public: bool MoveToRekeyPath(Options options, StoreId storeId); std::shared_ptr GetDBManager(const std::string &path, const AppId &appId); DBOption GetOption(const Options &options, const DBPassword &dbPassword); - DBStatus ChangeKVStoreDate(const std::string &storeId, std::shared_ptr dbManager, - const Options &options, DBPassword &dbPassword, int time); + DBStatus ChangeKVStoreDate(const std::string &storeId, std::shared_ptr dbManager, const Options &options, + DBPassword &dbPassword, int time); bool ModifyDate(int time); static void DeleteKVStore(); }; -void StoreFactoryTest::SetUpTestCase(void) -{ -} +void StoreFactoryTest::SetUpTestCase(void) { } -void StoreFactoryTest::TearDownTestCase(void) -{ -} +void StoreFactoryTest::TearDownTestCase(void) { } void StoreFactoryTest::SetUp(void) { @@ -169,9 +165,9 @@ StoreFactoryTest::DBOption StoreFactoryTest::GetOption(const Options &options, c dbOption.passwd = dbPassword.password; } - dbOption.conflictResolvePolicy = options.kvStoreType == KvStoreType::SINGLE_VERSION - ? DistributedDB::LAST_WIN - : DistributedDB::DEVICE_COLLABORATION; + dbOption.conflictResolvePolicy = options.kvStoreType == KvStoreType::SINGLE_VERSION ? + DistributedDB::LAST_WIN : + DistributedDB::DEVICE_COLLABORATION; dbOption.schema = options.schema; dbOption.createDirByStoreIdOnly = true; @@ -207,12 +203,12 @@ bool StoreFactoryTest::ModifyDate(int time) } /** -* @tc.name: Rekey -* @tc.desc: test rekey function -* @tc.type: FUNC -* @tc.require: -* @tc.author: Cui Renjie -*/ + * @tc.name: Rekey + * @tc.desc: test rekey function + * @tc.type: FUNC + * @tc.require: + * @tc.author: Cui Renjie + */ HWTEST_F(StoreFactoryTest, Rekey, TestSize.Level1) { Status status = DB_ERROR; @@ -235,12 +231,12 @@ HWTEST_F(StoreFactoryTest, Rekey, TestSize.Level1) } /** -* @tc.name: RekeyNotOutdated -* @tc.desc: try to rekey kvstore with not outdated password -* @tc.type: FUNC -* @tc.require: -* @tc.author: Cui Renjie -*/ + * @tc.name: RekeyNotOutdated + * @tc.desc: try to rekey kvstore with not outdated password + * @tc.type: FUNC + * @tc.require: + * @tc.author: Cui Renjie + */ HWTEST_F(StoreFactoryTest, RekeyNotOutdated, TestSize.Level1) { Status status = DB_ERROR; @@ -260,13 +256,13 @@ HWTEST_F(StoreFactoryTest, RekeyNotOutdated, TestSize.Level1) } /** -* @tc.name: RekeyInterrupted0 -* @tc.desc: mock the situation that open store after rekey was interrupted last time, -* which caused key file lost but rekey key file exist. -* @tc.type: FUNC -* @tc.require: -* @tc.author: Cui Renjie -*/ + * @tc.name: RekeyInterrupted0 + * @tc.desc: mock the situation that open store after rekey was interrupted last time, + * which caused key file lost but rekey key file exist. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Cui Renjie + */ HWTEST_F(StoreFactoryTest, RekeyInterruptedWhileChangeKeyFile, TestSize.Level1) { Status status = DB_ERROR; @@ -290,13 +286,13 @@ HWTEST_F(StoreFactoryTest, RekeyInterruptedWhileChangeKeyFile, TestSize.Level1) } /** -* @tc.name: RekeyInterrupted1 -* @tc.desc: mock the situation that open store after rekey was interrupted last time, -* which caused key file not changed but rekey key file exist. -* @tc.type: FUNC -* @tc.require: -* @tc.author: Cui Renjie -*/ + * @tc.name: RekeyInterrupted1 + * @tc.desc: mock the situation that open store after rekey was interrupted last time, + * which caused key file not changed but rekey key file exist. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Cui Renjie + */ HWTEST_F(StoreFactoryTest, RekeyInterruptedBeforeChangeKeyFile, TestSize.Level1) { Status status = DB_ERROR; @@ -332,12 +328,12 @@ HWTEST_F(StoreFactoryTest, RekeyInterruptedBeforeChangeKeyFile, TestSize.Level1) } /** -* @tc.name: RekeyNoPwdFile -* @tc.desc: try to open kvstore and execute RekeyRecover() without key and rekey key files. -* @tc.type: FUNC -* @tc.require: -* @tc.author: Cui Renjie -*/ + * @tc.name: RekeyNoPwdFile + * @tc.desc: try to open kvstore and execute RekeyRecover() without key and rekey key files. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Cui Renjie + */ HWTEST_F(StoreFactoryTest, RekeyNoPwdFile, TestSize.Level1) { Status status = DB_ERROR; @@ -359,4 +355,4 @@ HWTEST_F(StoreFactoryTest, RekeyNoPwdFile, TestSize.Level1) isKeyExist = StoreUtil::IsFileExist(keyFileName); ASSERT_EQ(isKeyExist, true); } -} \ No newline at end of file +} // namespace \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/store_util_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_util_test.cpp index 568359a7d1f1af3d8d25520e537b6b62212669b6..a38afed1f02650909cecdc2578871dde83559252 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/store_util_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_util_test.cpp @@ -1,17 +1,17 @@ /* -* 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. -*/ + * 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 "store_util.h" @@ -35,20 +35,20 @@ public: void TearDown(); }; -void StoreUtilTest::SetUpTestCase(void) {} +void StoreUtilTest::SetUpTestCase(void) { } -void StoreUtilTest::TearDownTestCase(void) {} +void StoreUtilTest::TearDownTestCase(void) { } -void StoreUtilTest::SetUp(void) {} +void StoreUtilTest::SetUp(void) { } -void StoreUtilTest::TearDown(void) {} +void StoreUtilTest::TearDown(void) { } /** -* @tc.name: GetDBSecurity -* @tc.desc: get db security -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: GetDBSecurity + * @tc.desc: get db security + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(StoreUtilTest, GetDBSecurity, TestSize.Level1) { StoreUtil storeUtil_; @@ -69,12 +69,12 @@ HWTEST_F(StoreUtilTest, GetDBSecurity, TestSize.Level1) ASSERT_EQ(dbsecurity.securityFlag, DistributedDB::ECE); } /** -* @tc.name: GetSecLevel -* @tc.desc: get secLevel -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: GetSecLevel + * @tc.desc: get secLevel + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(StoreUtilTest, GetSecLevel, TestSize.Level1) { StoreUtil storeUtil_; @@ -94,12 +94,12 @@ HWTEST_F(StoreUtilTest, GetSecLevel, TestSize.Level1) ASSERT_EQ(security, S4); } /** -* @tc.name: GetDBMode -* @tc.desc: get db mode -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: GetDBMode + * @tc.desc: get db mode + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(StoreUtilTest, GetDBMode, TestSize.Level1) { StoreUtil storeUtil_; @@ -113,12 +113,12 @@ HWTEST_F(StoreUtilTest, GetDBMode, TestSize.Level1) ASSERT_EQ(dbMode, StoreUtil::DBMode::SYNC_MODE_PUSH_PULL); } /** -* @tc.name: GetObserverMode -* @tc.desc: get observer mode -* @tc.type: FUNC -* @tc.require: -* @tc.author: Wang Kai -*/ + * @tc.name: GetObserverMode + * @tc.desc: get observer mode + * @tc.type: FUNC + * @tc.require: + * @tc.author: Wang Kai + */ HWTEST_F(StoreUtilTest, GetObserverMode, TestSize.Level1) { StoreUtil storeUtil_; @@ -132,12 +132,12 @@ HWTEST_F(StoreUtilTest, GetObserverMode, TestSize.Level1) ASSERT_EQ(mode, DistributedDB::OBSERVER_CHANGES_FOREIGN | DistributedDB::OBSERVER_CHANGES_NATIVE); } /** -* @tc.name: CheckPermissions001 -* @tc.desc: Check if the permissions for the first file creation are normal -* @tc.type: FUNC -* @tc.require: -* @tc.author: Shao Yuanzhao -*/ + * @tc.name: CheckPermissions001 + * @tc.desc: Check if the permissions for the first file creation are normal + * @tc.type: FUNC + * @tc.require: + * @tc.author: Shao Yuanzhao + */ HWTEST_F(StoreUtilTest, CheckPermissions001, TestSize.Level1) { StoreUtil storeUtil_; @@ -161,12 +161,12 @@ HWTEST_F(StoreUtilTest, CheckPermissions001, TestSize.Level1) rmdir(path.c_str()); } /** -* @tc.name: CheckPermissions002 -* @tc.desc: Check if updating existing file permissions is correct -* @tc.type: FUNC -* @tc.require: -* @tc.author: Shao Yuanzhao -*/ + * @tc.name: CheckPermissions002 + * @tc.desc: Check if updating existing file permissions is correct + * @tc.type: FUNC + * @tc.require: + * @tc.author: Shao Yuanzhao + */ HWTEST_F(StoreUtilTest, CheckPermissions002, TestSize.Level1) { std::string path = "/data/store_utils_test2"; diff --git a/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_single_kv_store.cpp b/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_single_kv_store.cpp index 9f4d2f88b39cd462f98b53bb42af413364bb34c3..117dbb6f0898eeec4233f0fb65c1e70269756805 100644 --- a/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_single_kv_store.cpp +++ b/kv_store/frameworks/jskitsimpl/distributedkvstore/src/js_single_kv_store.cpp @@ -100,6 +100,10 @@ void JsSingleKVStore::SetSchemaInfo(bool isSchemaStore) bool JsSingleKVStore::IsSystemApp() const { + if (param_ == nullptr) { + ZLOGE("param_ is nullptr"); + return false; + } return param_->isSystemApp; } diff --git a/kv_store/frameworks/libs/distributeddb/common/include/auto_launch.h b/kv_store/frameworks/libs/distributeddb/common/include/auto_launch.h index 28a0cab03216ae457cba91048ae52be4c6843814..c73853386c426c8307882bc63b7b52c78c15c77f 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/auto_launch.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/auto_launch.h @@ -21,6 +21,9 @@ #include #include "auto_launch_export.h" #include "db_properties.h" +#ifdef USE_FFRT +#include "ffrt.h" +#endif #include "ikvdb_connection.h" #include "icommunicator_aggregator.h" #include "kv_store_observer.h" @@ -196,7 +199,11 @@ protected: ICommunicatorAggregator *communicatorAggregator_ = nullptr; std::condition_variable cv_; +#ifdef USE_FFRT + ffrt::mutex extLock_; +#else std::mutex extLock_; +#endif std::map autoLaunchRequestCallbackMap_; // key: label, value: std::map> extItemMap_; diff --git a/kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h b/kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h index a6aaeca91157bf10a1f8c25f1ff87f0df4df7eb1..8c436567d281fcddd252f71c696abf3d8f74aa00 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/concurrent_adapter.h @@ -24,11 +24,9 @@ namespace DistributedDB { #ifdef USE_FFRT using TaskHandle = ffrt::task_handle; -#define ADAPTER_AUTO_LOCK(n, m) #define ADAPTER_WAIT(x) ffrt::wait({x}) #else using TaskHandle = void *; -#define ADAPTER_AUTO_LOCK(n, m) std::lock_guard n(m) #define ADAPTER_WAIT(x) (void)(x) #endif using Dependence = void *; @@ -38,6 +36,13 @@ public: Dependence outDeps = nullptr); static TaskHandle ScheduleTaskH(const TaskAction &action, Dependence inDeps = nullptr, Dependence outDeps = nullptr); +#ifdef USE_FFRT + static void AdapterAutoLock(ffrt::mutex &mutex); + static void AdapterAutoUnLock(ffrt::mutex &mutex); +#else + static void AdapterAutoLock(std::mutex &mutex); + static void AdapterAutoUnLock(std::mutex &mutex); +#endif }; } diff --git a/kv_store/frameworks/libs/distributeddb/common/include/relational/tracker_table.h b/kv_store/frameworks/libs/distributeddb/common/include/relational/tracker_table.h index 0e1e9f7bb1b90ff114a9511215a8322d945bfc66..e46e1e8f4ac720644571a5edf259b0c353f2f81c 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/relational/tracker_table.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/relational/tracker_table.h @@ -40,6 +40,7 @@ public: const std::string GetDiffTrackerValSql() const; const std::string GetDiffIncCursorSql(const std::string &tableName) const; const std::string GetExtendName() const; + const std::set &GetExtendNames() const; std::string ToString() const; const std::vector GetDropTempTriggerSql() const; const std::string GetTempInsertTriggerSql(bool incFlag = false) const; @@ -49,6 +50,7 @@ public: const std::string GetTempUpdateTriggerSql(bool incFlag = false) const; const std::string GetTempDeleteTriggerSql(bool incFlag = false) const; void SetTableName(const std::string &tableName); + void SetExtendNames(const std::set &colNames); void SetExtendName(const std::string &colName); void SetTrackerNames(const std::set &trackerNames); bool IsEmpty() const; @@ -60,6 +62,7 @@ public: private: std::string tableName_; std::string extendColName_; + std::set extendColNames_; std::set trackerColNames_; bool isTrackerAction_ = false; }; diff --git a/kv_store/frameworks/libs/distributeddb/common/src/auto_launch.cpp b/kv_store/frameworks/libs/distributeddb/common/src/auto_launch.cpp index 32e6cdedc42c359935f282abc81f50ea48e11440..141d71dd3a9475ae0f5241cd765215a79a8fb7cf 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/auto_launch.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/auto_launch.cpp @@ -29,6 +29,7 @@ #include "param_check_utils.h" #include "relational_store_instance.h" #include "relational_store_changed_data_impl.h" +#include "res_finalizer.h" #include "runtime_context.h" #include "semaphore_utils.h" #include "sync_able_kvdb_connection.h" @@ -737,7 +738,8 @@ void AutoLaunch::SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &c { LOGI("[AutoLaunch] SetAutoLaunchRequestCallback type[%d]", static_cast(type)); TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, callback, type] () mutable { - ADAPTER_AUTO_LOCK(lock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); if (callback) { autoLaunchRequestCallbackMap_[type] = callback; } else { @@ -795,7 +797,8 @@ void AutoLaunch::AutoLaunchExtTask(const std::string &identifier, const std::str bool isReturn = false; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &userId, &autoLaunchItem, &isReturn] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); if (extItemMap_.count(identifier) != 0 && extItemMap_[identifier].count(userId) != 0) { LOGE("[AutoLaunch] extItemMap has this identifier"); isReturn = true; @@ -811,7 +814,8 @@ void AutoLaunch::AutoLaunchExtTask(const std::string &identifier, const std::str bool abort = ChkAutoLaunchAbort(identifier, autoLaunchItem); if (abort) { TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &userId] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); extItemMap_[identifier].erase(userId); if (extItemMap_[identifier].empty()) { extItemMap_.erase(identifier); @@ -821,7 +825,8 @@ void AutoLaunch::AutoLaunchExtTask(const std::string &identifier, const std::str return; } TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &userId, &autoLaunchItem] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); extItemMap_[identifier][userId] = autoLaunchItem; // Reassign item to prevent it from being erased extItemMap_[identifier][userId].isWriteOpenNotified = false; LOGI("[AutoLaunch] AutoLaunchExtTask ok"); @@ -839,7 +844,8 @@ void AutoLaunch::ExtObserverFunc(const KvDBCommitNotifyData ¬ifyData, const s bool isReturn = false; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &userId, &autoLaunchItem, &isReturn] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); if (extItemMap_.count(identifier) == 0 || extItemMap_[identifier].count(userId) == 0) { LOGE("[AutoLaunch] ExtObserverFunc this identifier not in map"); isReturn = true; @@ -862,7 +868,8 @@ void AutoLaunch::ExtObserverFunc(const KvDBCommitNotifyData ¬ifyData, const s bool isReturn = false; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &userId, &autoLaunchItem, ¬ifier, &isReturn] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); if (extItemMap_.count(identifier) != 0 && extItemMap_[identifier].count(userId) != 0 && !extItemMap_[identifier][userId].isWriteOpenNotified && autoLaunchItem.notifier != nullptr) { @@ -899,7 +906,8 @@ void AutoLaunch::ExtConnectionLifeCycleCallbackTask(const std::string &identifie bool isReturn = false; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &userId, &autoLaunchItem, &isReturn] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); if (extItemMap_.count(identifier) == 0 || extItemMap_[identifier].count(userId) == 0) { LOGE("[AutoLaunch] ExtConnectionLifeCycleCallbackTask identifier is not exist!"); isReturn = true; @@ -1059,7 +1067,8 @@ int AutoLaunch::ExtAutoLaunchRequestCallBack(const std::string &identifier, Auto { std::map callbackMap; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &callbackMap] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); callbackMap = autoLaunchRequestCallbackMap_; return E_OK; }, &autoLaunchRequestCallbackMap_); @@ -1306,7 +1315,8 @@ int AutoLaunch::RegisterRelationalObserver(AutoLaunchItem &autoLaunchItem, const bool isReturn = false; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &userId, ¬ifier, &isWriteOpenNotified, &isReturn] () mutable { - ADAPTER_AUTO_LOCK(autoLock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); if (extItemMap_.find(identifier) == extItemMap_.end() || extItemMap_[identifier].find(userId) == extItemMap_[identifier].end()) { LOGE("[AutoLaunch] ExtObserverFunc this identifier not in map"); @@ -1335,7 +1345,8 @@ void AutoLaunch::CloseConnection(DBTypeInner type, const DBProperties &propertie int closeId = properties.GetIntProp(DBProperties::AUTO_LAUNCH_ID, 0); TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, &identifier, &properties, closeId, type] () mutable { - ADAPTER_AUTO_LOCK(lock, extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); auto itemMapIter = extItemMap_.find(identifier); if (itemMapIter == extItemMap_.end()) { std::string dualIdentifier = properties.GetStringProp(DBProperties::DUAL_TUPLE_IDENTIFIER_DATA, ""); diff --git a/kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp b/kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp index da8bdec5882c6dc53b7da5de6132055ea082e23e..5f5223c6f4330c356be5aecef2c94922daf786be 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/concurrent_adapter.cpp @@ -51,4 +51,25 @@ TaskHandle ConcurrentAdapter::ScheduleTaskH(const TaskAction &action, Dependence return 0; #endif } + +#ifdef USE_FFRT +void ConcurrentAdapter::AdapterAutoLock(ffrt::mutex &mutex) +{ + mutex.lock(); +} + +void ConcurrentAdapter::AdapterAutoUnLock(ffrt::mutex &mutex) +{ + mutex.unlock(); +} +#else +void ConcurrentAdapter::AdapterAutoLock(std::mutex &mutex) +{ + std::lock_guard lock(mutex); +} + +void ConcurrentAdapter::AdapterAutoUnLock([[gnu::unused]] std::mutex &mutex) +{ +} +#endif } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/common/src/json_object.cpp b/kv_store/frameworks/libs/distributeddb/common/src/json_object.cpp index 6dfa9356f199c213e28d9738940a1a3e3a629b25..252459f76d3bfd3a6828dedc8a95c933e2e52ad4 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/json_object.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/json_object.cpp @@ -421,6 +421,10 @@ int JsonObject::GetArrayContentOfStringOrStringArray(const FieldPath &inPath, LOGE("[Json][GetArrayContent] Not an array."); return -E_NOT_SUPPORT; } + if (valueNode.size() > DBConstant::MAX_VALUE_SIZE) { + LOGE("[Json][GetArrayContent] Exceeds max value size."); + return -E_NOT_SUPPORT; + } for (uint32_t index = 0; index < valueNode.size(); index++) { const Json::Value &eachArrayItem = valueNode[index]; if (eachArrayItem.isString()) { @@ -601,6 +605,10 @@ int JsonObject::GetStringArrayContentByJsonValue(const Json::Value &value, LOGE("[Json][GetStringArrayByValue] Not an array."); return -E_NOT_SUPPORT; } + if (value.size() > DBConstant::MAX_VALUE_SIZE) { + LOGE("[Json][GetStringArrayByValue] Exceeds max value size."); + return -E_NOT_SUPPORT; + } for (uint32_t index = 0; index < value.size(); index++) { const Json::Value &eachArrayItem = value[index]; if (!eachArrayItem.isString()) { @@ -738,6 +746,10 @@ int JsonObject::GetObjectArrayByFieldPath(const FieldPath &inPath, std::vector DBConstant::MAX_VALUE_SIZE) { + LOGE("[Json][GetValue] Exceeds max value size."); + return -E_NOT_PERMIT; + } for (Json::ArrayIndex i = 0; i < valueNode.size(); ++i) { outArray.emplace_back(JsonObject(valueNode[i])); } diff --git a/kv_store/frameworks/libs/distributeddb/common/src/relational/relational_schema_object.cpp b/kv_store/frameworks/libs/distributeddb/common/src/relational/relational_schema_object.cpp index 1d34db8ea4bef6e249761ac0df860ffe2b934c03..fb3100c07e581f83f3224b22f29158e38bc7a7f5 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/relational/relational_schema_object.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/relational/relational_schema_object.cpp @@ -462,16 +462,46 @@ int RelationalSchemaObject::ParseCheckTrackerTableName(const JsonObject &inJsonO int RelationalSchemaObject::ParseCheckTrackerExtendName(const JsonObject &inJsonObject, TrackerTable &resultTable) { - FieldValue fieldValue; - int errCode = GetMemberFromJsonObject(inJsonObject, "EXTEND_NAME", FieldType::LEAF_FIELD_STRING, - true, fieldValue); - if (errCode == E_OK) { // LCOV_EXCL_BR_LINE - if (!DBCommon::CheckIsAlnumOrUnderscore(fieldValue.stringValue)) { // LCOV_EXCL_BR_LINE - LOGE("[RelationalSchema][Parse] Invalid characters in extend name, err=%d.", errCode); + FieldType fieldType; + int errCode = inJsonObject.GetFieldTypeByFieldPath(FieldPath {"EXTEND_NAMES"}, fieldType); + if (errCode != E_OK) { // LCOV_EXCL_BR_LINE + FieldValue fieldValue; + errCode = GetMemberFromJsonObject(inJsonObject, "EXTEND_NAME", FieldType::LEAF_FIELD_STRING, + true, fieldValue); + if (errCode == E_OK) { // LCOV_EXCL_BR_LINE + if (!DBCommon::CheckIsAlnumOrUnderscore(fieldValue.stringValue)) { // LCOV_EXCL_BR_LINE + LOGE("[RelationalSchema][Parse] Invalid characters in extend name, err=%d.", errCode); + } else { + resultTable.SetExtendName(fieldValue.stringValue); + resultTable.SetExtendNames({fieldValue.stringValue}); + return E_OK; + } + } + LOGE("[RelationalSchema][Parse] Get extend col names fieldType failed: %d.", errCode); + return -E_SCHEMA_PARSE_FAIL; + } + if (FieldType::LEAF_FIELD_ARRAY != fieldType) { // LCOV_EXCL_BR_LINE + LOGE("[RelationalSchema][Parse] Expect extend cols fieldType ARRAY but %s.", + SchemaUtils::FieldTypeString(fieldType).c_str()); + return -E_SCHEMA_PARSE_FAIL; + } + std::vector fieldValues; + errCode = inJsonObject.GetObjectArrayByFieldPath(FieldPath{"EXTEND_NAMES"}, fieldValues); + if (errCode != E_OK) { // LCOV_EXCL_BR_LINE + LOGE("[RelationalSchema][Parse] Get extend col names value failed: %d.", errCode); + return -E_SCHEMA_PARSE_FAIL; + } + std::set colNames; + for (const JsonObject &value : fieldValues) { + FieldValue fieldValue; + errCode = value.GetFieldValueByFieldPath(FieldPath {}, fieldValue); + if (errCode != E_OK) { // LCOV_EXCL_BR_LINE + LOGE("[RelationalSchema][Parse] Parse extend col name failed: %d.", errCode); return -E_SCHEMA_PARSE_FAIL; } - resultTable.SetExtendName(fieldValue.stringValue); + colNames.insert(fieldValue.stringValue); } + resultTable.SetExtendNames(colNames); return errCode; } diff --git a/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp b/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp index e9a184701134c4082cd7dbceb8bfcb4c9da6cd3c..0796a5f802d998b0c29316d5269a840779d0a71a 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp @@ -751,28 +751,36 @@ int TableInfo::CheckTrackerTable() if (trackerTable_.GetTrackerColNames().empty()) { return E_OK; } + const char *tableName = DBCommon::StringMiddleMasking(tableName_).c_str(); + size_t nameLength = tableName_.size(); for (const auto &colName: trackerTable_.GetTrackerColNames()) { if (colName.empty()) { - LOGE("tracker col cannot be empty."); + LOGE("[%s [%zu]] tracker col cannot be empty.", tableName, nameLength); return -E_INVALID_ARGS; } if (GetFields().find(colName) == GetFields().end()) { - LOGE("unable to match the tracker col from table schema."); + LOGE("[%s [%zu]] unable to match the tracker col from table schema.", tableName, nameLength); return -E_SCHEMA_MISMATCH; } } - if (trackerTable_.GetExtendName().empty()) { + if (trackerTable_.GetExtendNames().empty()) { return E_OK; } - auto iter = GetFields().find(trackerTable_.GetExtendName()); - if (iter == GetFields().end()) { - LOGE("unable to match the extend col from table schema."); - return -E_SCHEMA_MISMATCH; - } else { - if (iter->second.IsAssetType() || iter->second.IsAssetsType()) { - LOGE("extend col is not allowed to be set as an asset field."); + for (const auto &colName : trackerTable_.GetExtendNames()) { + if (colName.empty()) { + LOGE("[%s [%zu]] extend col cannot be empty.", tableName, nameLength); return -E_INVALID_ARGS; } + auto iter = GetFields().find(colName); + if (iter == GetFields().end()) { + LOGE("[%s [%zu]] unable to match the extend col from table schema.", tableName, nameLength); + return -E_SCHEMA_MISMATCH; + } else { + if (iter->second.IsAssetType() || iter->second.IsAssetsType()) { + LOGE("[%s [%zu]] extend col is not allowed to be set as an asset field.", tableName, nameLength); + return -E_INVALID_ARGS; + } + } } return E_OK; } diff --git a/kv_store/frameworks/libs/distributeddb/common/src/relational/tracker_table.cpp b/kv_store/frameworks/libs/distributeddb/common/src/relational/tracker_table.cpp index c498bdc726c2409fdab91e4f4d1cfb566db3c379..685740d916782bbfde4683e46e003d00b08644f3 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/relational/tracker_table.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/relational/tracker_table.cpp @@ -22,7 +22,7 @@ namespace DistributedDB { void TrackerTable::Init(const TrackerSchema &schema) { tableName_ = schema.tableName; - extendColName_ = schema.extendColName; + extendColNames_ = schema.extendColNames; trackerColNames_ = schema.trackerColNames; isTrackerAction_ = schema.isTrackAction; } @@ -37,20 +37,45 @@ const std::set &TrackerTable::GetTrackerColNames() const return trackerColNames_; } -const std::string TrackerTable::GetAssignValSql(bool isDelete) const +bool IsInvalidExtendColNames(const std::set &extendColNames) +{ + for (auto &extendColName : extendColNames) { + if (extendColName.empty()) { + return true; + } + } + return false; +} + +const std::string GetJsonAssignValSql(bool isDelete, const std::set &extendColNames) { - if (extendColName_.empty()) { + if (extendColNames.empty()) { return "''"; } - return isDelete ? ("OLD." + extendColName_) : ("NEW." + extendColName_); + std::string newOrOld = isDelete ? "OLD." : "NEW."; + std::string sql = "json_object("; + for (auto &extendColName : extendColNames) { + sql += "'" + extendColName + "'," + newOrOld + extendColName + ","; + } + sql.pop_back(); + sql += ")"; + return sql; +} + +const std::string TrackerTable::GetAssignValSql(bool isDelete) const +{ + if (!extendColNames_.empty() && !IsInvalidExtendColNames(extendColNames_)) { + return GetJsonAssignValSql(isDelete, extendColNames_); + } + return "''"; } const std::string TrackerTable::GetExtendAssignValSql(bool isDelete) const { - if (extendColName_.empty()) { - return ""; + if (!extendColNames_.empty() && !IsInvalidExtendColNames(extendColNames_)) { + return ", extend_field = " + GetJsonAssignValSql(isDelete, extendColNames_); } - return isDelete ? (", extend_field = OLD." + extendColName_) : (", extend_field = NEW." + extendColName_); + return ""; } const std::string TrackerTable::GetDiffTrackerValSql() const @@ -93,6 +118,11 @@ const std::string TrackerTable::GetDiffIncCursorSql(const std::string &tableName return sql; } +const std::set &TrackerTable::GetExtendNames() const +{ + return extendColNames_; +} + const std::string TrackerTable::GetExtendName() const { return extendColName_; @@ -103,7 +133,14 @@ std::string TrackerTable::ToString() const std::string attrStr; attrStr += "{"; attrStr += R"("NAME": ")" + tableName_ + "\","; - attrStr += R"("EXTEND_NAME": ")" + extendColName_ + "\","; + attrStr += R"("EXTEND_NAMES": [)"; + for (const auto &colName : extendColNames_) { + attrStr += "\"" + colName + "\","; + } + if (!extendColNames_.empty()) { + attrStr.pop_back(); + } + attrStr += "],"; attrStr += R"("TRACKER_NAMES": [)"; for (const auto &colName: trackerColNames_) { attrStr += "\"" + colName + "\","; @@ -252,9 +289,14 @@ void TrackerTable::SetTableName(const std::string &tableName) tableName_ = tableName; } +void TrackerTable::SetExtendNames(const std::set &colNames) +{ + extendColNames_ = std::move(colNames); +} + void TrackerTable::SetExtendName(const std::string &colName) { - extendColName_ = colName; + extendColName_ = std::move(colName); } void TrackerTable::SetTrackerNames(const std::set &trackerNames) @@ -274,12 +316,18 @@ bool TrackerTable::IsTableNameEmpty() const bool TrackerTable::IsChanging(const TrackerSchema &schema) { - if (tableName_ != schema.tableName || extendColName_ != schema.extendColName) { + if (tableName_ != schema.tableName || extendColNames_.size() != schema.extendColNames.size() || + trackerColNames_.size() != schema.trackerColNames.size()) { return true; } - if (trackerColNames_.size() != schema.trackerColNames.size()) { + if (!extendColName_.empty()) { return true; } + for (const auto &col: extendColNames_) { + if (schema.extendColNames.find(col) == schema.extendColNames.end()) { + return true; + } + } for (const auto &col: trackerColNames_) { if (schema.trackerColNames.find(col) == schema.trackerColNames.end()) { return true; @@ -335,4 +383,4 @@ void TrackerTable::SetTrackerAction(bool isTrackerAction) isTrackerAction_ = isTrackerAction; } } -#endif \ No newline at end of file +#endif diff --git a/kv_store/frameworks/libs/distributeddb/common/src/schema_utils.cpp b/kv_store/frameworks/libs/distributeddb/common/src/schema_utils.cpp index c6af2033bfabfbe48ddfd6108be5418cb964146c..7908acc63c6b7a31702a128984632c39bf5284a5 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/schema_utils.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/schema_utils.cpp @@ -20,6 +20,7 @@ #include #include +#include "db_common.h" #include "db_errno.h" #include "log_print.h" #include "schema_constant.h" @@ -507,13 +508,11 @@ void SchemaUtils::TransTrackerSchemaToLower(const TrackerSchema &srcSchema, Trac std::string tableName(srcSchema.tableName.length(), ' '); std::transform(srcSchema.tableName.begin(), srcSchema.tableName.end(), tableName.begin(), ::tolower); destSchema.tableName = tableName; - std::string extendName(srcSchema.extendColName.length(), ' '); - std::transform(srcSchema.extendColName.begin(), srcSchema.extendColName.end(), extendName.begin(), ::tolower); - destSchema.extendColName = extendName; + for (const auto &extendColName : srcSchema.extendColNames) { + destSchema.extendColNames.insert(DBCommon::ToLowerCase(extendColName)); + } for (const auto &srcName : srcSchema.trackerColNames) { - std::string colName(srcName.length(), ' '); - std::transform(srcName.begin(), srcName.end(), colName.begin(), ::tolower); - destSchema.trackerColNames.insert(colName); + destSchema.trackerColNames.insert(DBCommon::ToLowerCase(srcName)); } } } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/communicator/src/send_task_scheduler.cpp b/kv_store/frameworks/libs/distributeddb/communicator/src/send_task_scheduler.cpp index 5c3cb93610ee58933a5f25774e031633e28e333d..db1b9d4e33f4575e564311f3558c9d7de9b61d93 100644 --- a/kv_store/frameworks/libs/distributeddb/communicator/src/send_task_scheduler.cpp +++ b/kv_store/frameworks/libs/distributeddb/communicator/src/send_task_scheduler.cpp @@ -316,6 +316,7 @@ void SendTaskScheduler::InvalidSendTask(const std::string &target) void SendTaskScheduler::SetSoftBusErrCode(const std::string &target, int softBusErrCode) { + std::lock_guard overallLockGuard(overallMutex_); softBusErrCodeMap_[target] = softBusErrCode; } } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h b/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h index da91b56d8b99a5309af537b171dcb9bd8960b634..91f96be81635cf3d386f5c5426ddae2cf76e0c65 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h @@ -236,7 +236,7 @@ using UpdateKeyCallback = std::function extendColNames; std::set trackerColNames; bool isForceUpgrade = false; bool isTrackAction = false; diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h index 7c2f5d3ade25e3434eb6a4b7feef80f0a7d5f8fb..b7f13f5001036ff5605918270d5d87da40625e66 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_sync_able_storage.h @@ -18,6 +18,9 @@ #include "cloud/cloud_upload_recorder.h" #include "cloud/schema_mgr.h" +#ifdef USE_FFRT +#include "ffrt.h" +#endif #include "icloud_sync_storage_interface.h" #include "lru_map.h" #include "relational_db_sync_interface.h" @@ -303,7 +306,11 @@ private: std::shared_ptr storageEngine_ = nullptr; std::function onSchemaChanged_; mutable std::mutex onSchemaChangedMutex_; +#ifdef USE_FFRT + ffrt::mutex dataChangeDeviceMutex_; +#else std::mutex dataChangeDeviceMutex_; +#endif std::map> dataChangeCallbackMap_; std::function heartBeatListener_; mutable std::mutex heartBeatMutex_; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/relational/relational_sync_able_storage.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/relational/relational_sync_able_storage.cpp index ac754ca9a122e0cb4d0cf7b9d812b882290f6f8b..e6c2bdceb8cbcb956952a574aac3a8d6ccec8082 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/relational/relational_sync_able_storage.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/relational/relational_sync_able_storage.cpp @@ -734,7 +734,8 @@ int RelationalSyncAbleStorage::RegisterObserverAction(uint64_t connectionId, con { int errCode = E_OK; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, connectionId, observer, action, &errCode] () mutable { - ADAPTER_AUTO_LOCK(lock, dataChangeDeviceMutex_); + ConcurrentAdapter::AdapterAutoLock(dataChangeDeviceMutex_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(dataChangeDeviceMutex_); }); auto it = dataChangeCallbackMap_.find(connectionId); if (it != dataChangeCallbackMap_.end()) { if (it->second.find(observer) != it->second.end()) { @@ -765,7 +766,8 @@ int RelationalSyncAbleStorage::UnRegisterObserverAction(uint64_t connectionId, c } int errCode = -E_NOT_FOUND; TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, connectionId, observer, &errCode] () mutable { - ADAPTER_AUTO_LOCK(lock, dataChangeDeviceMutex_); + ConcurrentAdapter::AdapterAutoLock(dataChangeDeviceMutex_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(dataChangeDeviceMutex_); }); auto it = dataChangeCallbackMap_.find(connectionId); if (it == dataChangeCallbackMap_.end()) { return; @@ -811,7 +813,8 @@ void RelationalSyncAbleStorage::TriggerObserverAction(const std::string &deviceN ConcurrentAdapter::ScheduleTask([this, deviceName, changedData, isChangedData] () mutable { LOGD("begin to trigger relational observer."); int observerCnt = 0; - ADAPTER_AUTO_LOCK(lock, dataChangeDeviceMutex_); + ConcurrentAdapter::AdapterAutoLock(dataChangeDeviceMutex_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(dataChangeDeviceMutex_); }); for (const auto &item : dataChangeCallbackMap_) { ExecuteDataChangeCallback(item, deviceName, changedData, isChangedData, observerCnt); } @@ -1444,7 +1447,8 @@ std::string RelationalSyncAbleStorage::GetIdentify() const void RelationalSyncAbleStorage::EraseDataChangeCallback(uint64_t connectionId) { TaskHandle handle = ConcurrentAdapter::ScheduleTaskH([this, connectionId] () mutable { - ADAPTER_AUTO_LOCK(lock, dataChangeDeviceMutex_); + ConcurrentAdapter::AdapterAutoLock(dataChangeDeviceMutex_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(dataChangeDeviceMutex_); }); auto it = dataChangeCallbackMap_.find(connectionId); if (it != dataChangeCallbackMap_.end()) { dataChangeCallbackMap_.erase(it); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp index 330cde711c43eef9067b66e55d2c093aebcc1fc2..4b29ee62ba0f1399bbc5386b98d76cea244de19d 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_store.cpp @@ -1253,13 +1253,19 @@ void SQLiteRelationalStore::FillSyncInfo(const CloudSyncOption &option, const Sy int SQLiteRelationalStore::SetTrackerTable(const TrackerSchema &trackerSchema) { + int errCode = sqliteStorageEngine_->UpdateExtendField(trackerSchema); + if (errCode != E_OK) { + LOGE("[RelationalStore] update [%s [%zu]] extend_field failed: %d", + DBCommon::StringMiddleMasking(trackerSchema.tableName).c_str(), trackerSchema.tableName.size(), errCode); + return errCode; + } RelationalSchemaObject localSchema = sqliteStorageEngine_->GetSchema(); TableInfo tableInfo = localSchema.GetTable(trackerSchema.tableName); if (tableInfo.Empty()) { return sqliteStorageEngine_->SetTrackerTable(trackerSchema); } bool isFirstCreate = false; - int errCode = sqliteStorageEngine_->CheckAndCacheTrackerSchema(trackerSchema, tableInfo, isFirstCreate); + errCode = sqliteStorageEngine_->CheckAndCacheTrackerSchema(trackerSchema, tableInfo, isFirstCreate); if (errCode != E_OK) { return errCode == -E_IGNORE_DATA ? E_OK : errCode; } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp index c5729e09869e866eb4ffdee6acc269f77a741aea..4b200c9bc703ce3c4e788627d9dbba1c615c0074 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp @@ -1079,5 +1079,53 @@ std::map SQLiteSingleRelationalStorageEngine::GetTableWeightWi } return res; } + +int SQLiteSingleRelationalStorageEngine::UpdateExtendField(const DistributedDB::TrackerSchema &schema) +{ + if (schema.extendColNames.empty()) { + return E_OK; + } + RelationalSchemaObject tracker = trackerSchema_; + if (!tracker.GetTrackerTable(schema.tableName).IsChanging(schema) && !schema.isForceUpgrade) { + LOGI("[%s [%zu]] tracker schema is no change.", DBCommon::StringMiddleMasking(schema.tableName).c_str(), + schema.tableName.size()); + return E_OK; + } + int errCode = E_OK; + auto *handle = static_cast(FindExecutor(true, + OperatePerm::NORMAL_PERM, errCode)); + if (handle == nullptr) { + return errCode; + } + ResFinalizer finalizer([&handle, this] { this->ReleaseExecutor(handle); }); + + errCode = handle->StartTransaction(TransactType::IMMEDIATE); + if (errCode != E_OK) { + return errCode; + } + + errCode = handle->UpdateExtendField(schema.tableName, schema.extendColNames); + if (errCode != E_OK) { + LOGE("[%s [%zu]] Update extend field failed. %d", + DBCommon::StringMiddleMasking(schema.tableName).c_str(), schema.tableName.size(), errCode); + (void)handle->Rollback(); + return errCode; + } + + TrackerTable oldTrackerTable = tracker.GetTrackerTable(schema.tableName); + const std::set& oldExtendColNames = oldTrackerTable.GetExtendNames(); + const std::string lowVersionExtendColName = oldTrackerTable.GetExtendName(); + if (!oldExtendColNames.empty()) { + errCode = handle->UpdateDeleteDataExtendField(schema.tableName, lowVersionExtendColName, + oldExtendColNames, schema.extendColNames); + if (errCode != E_OK) { + LOGE("[%s [%zu]] Update extend field for delete data failed. %d", + DBCommon::StringMiddleMasking(schema.tableName).c_str(), schema.tableName.size(), errCode); + (void)handle->Rollback(); + return errCode; + } + } + return handle->Commit(); +} } #endif \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h index 9647b6a5de2f4e94bd40c5fbb739cbb3803a55f8..ee3f36a20b2871f42ce6b356a98fba24eec23935 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.h @@ -60,6 +60,7 @@ public: const std::map &alterTableNames); std::pair, int> CalTableRef(const std::vector &tableNames, const std::map &sharedTableOriginNames); + int UpdateExtendField(const TrackerSchema &schema); protected: StorageExecutor *NewSQLiteStorageExecutor(sqlite3 *dbHandle, bool isWrite, bool isMemDb) override; int Upgrade(sqlite3 *db) override; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.cpp index 263b3ec99d4b8d82dfda12294679f540fb585db8..6d3c932f91b35e0b9a32c8751a52a46c8c965b97 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.cpp @@ -164,6 +164,23 @@ int GetExistedDataTimeOffset(sqlite3 *db, const std::string &tableName, bool isM } } +std::string GetExtendValue(const TrackerTable &trackerTable) +{ + std::string extendValue; + const std::set &extendNames = trackerTable.GetExtendNames(); + if (!extendNames.empty()) { + extendValue += "json_object("; + for (const auto &extendName : extendNames) { + extendValue += "'" + extendName + "'," + extendName + ","; + } + extendValue.pop_back(); + extendValue += ")"; + } else { + extendValue = "''"; + } + return extendValue; +} + int SQLiteSingleVerRelationalStorageExecutor::GeneLogInfoForExistedData(sqlite3 *db, const std::string &tableName, const std::string &calPrimaryKeyHash, TableInfo &tableInfo) { @@ -196,7 +213,7 @@ int SQLiteSingleVerRelationalStorageExecutor::GeneLogInfoForExistedData(sqlite3 std::string sql = "INSERT OR REPLACE INTO " + logTable + " SELECT " + rowid + ", '', '', " + timeOffsetStr + " + " + rowid + ", " + timeOffsetStr + " + " + rowid + ", " + flag + ", " + calPrimaryKeyHash + ", '', "; - sql += tableInfo.GetTrackerTable().GetExtendName().empty() ? "''" : tableInfo.GetTrackerTable().GetExtendName(); + sql += GetExtendValue(tableInfo.GetTrackerTable()); sql += ", 0, '', '', 0 FROM '" + tableName + "' AS a WHERE 1=1;"; errCode = trackerTable.ReBuildTempTrigger(db, TriggerMode::TriggerModeEnum::INSERT, [db, &sql]() { int ret = SQLiteUtils::ExecuteRawSQL(db, sql); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.h b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.h index 551c96b4d102a4a04cd996157db3cfb73958ad32..863c748ebc5e55354aee117322e14378f4061794 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.h +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor.h @@ -220,6 +220,11 @@ public: int ReviseLocalModTime(const std::string &tableName, const std::vector &revisedData); int GetLocalDataCount(const std::string &tableName, int &dataCount, int &logicDeleteDataCount); + + int UpdateExtendField(const std::string &tableName, const std::set &extendColNames); + + int UpdateDeleteDataExtendField(const std::string &tableName, const std::string &lowVersionExtendColName, + const std::set &oldExtendColNames, const std::set &extendColNames); private: int DoCleanLogs(const std::vector &tableNameList, const RelationalSchemaObject &localSchema); @@ -331,13 +336,13 @@ private: int BindValueToUpsertStatement(const VBucket &vBucket, const std::vector &fields, sqlite3_stmt *upsertStmt); - int BindStatusSubQueryHashKeyStatement(sqlite3_stmt *insertLogStmt, std::vector &hashKey); + int BindStatusSubQueryHashKeyStatement(sqlite3_stmt *insertLogStmt, std::vector &hashKey, int &index); int BindHashKeyAndGidToInsertLogStatement(const VBucket &vBucket, const TableSchema &tableSchema, - const TrackerTable &trackerTable, sqlite3_stmt *insertLogStmt); + const TrackerTable &trackerTable, sqlite3_stmt *insertLogStmt, int &index); int BindShareValueToInsertLogStatement(const VBucket &vBucket, const TableSchema &tableSchema, - sqlite3_stmt *insertLogStmt); + sqlite3_stmt *insertLogStmt, int &index); int BindValueToInsertLogStatement(VBucket &vBucket, const TableSchema &tableSchema, const TrackerTable &trackerTable, sqlite3_stmt *insertLogStmt); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor_extend.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor_extend.cpp index 2b48b9333ad8d14959bdca09af37d7aa707e6671..150a4e565f44396e159b54a7c1cbbf047da66e35 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor_extend.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_executor_extend.cpp @@ -652,6 +652,24 @@ int SQLiteSingleVerRelationalStorageExecutor::InsertCloudData(VBucket &vBucket, return InsertLogRecord(tableSchema, trackerTable, vBucket); } +std::string GetInsertLogSql(const std::string &logTableName, const std::set &extendColNames) +{ + if (extendColNames.empty()) { + return "INSERT OR REPLACE INTO " + logTableName + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, " + + "CASE WHEN (SELECT status FROM " + logTableName + " WHERE hash_key=?) IS NULL THEN 0 ELSE " + + "(SELECT status FROM " + logTableName + " WHERE hash_key=?) " + "END)"; + } + std::string sql = "INSERT OR REPLACE INTO " + logTableName + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, json_object("; + for (const auto &extendColName : extendColNames) { + sql += "'" + extendColName + "',?,"; + } + sql.pop_back(); + sql += "), 0, ?, ?, CASE WHEN (SELECT status FROM " + logTableName + + " WHERE hash_key=?) IS NULL THEN 0 ELSE " + "(SELECT status FROM " + logTableName + + " WHERE hash_key=?) " + "END)"; + return sql; +} + int SQLiteSingleVerRelationalStorageExecutor::InsertLogRecord(const TableSchema &tableSchema, const TrackerTable &trackerTable, VBucket &vBucket) { @@ -673,10 +691,7 @@ int SQLiteSingleVerRelationalStorageExecutor::InsertLogRecord(const TableSchema } } - std::string sql = "INSERT OR REPLACE INTO " + DBCommon::GetLogTableName(tableSchema.name) + - " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, " + "CASE WHEN (SELECT status FROM " + - DBCommon::GetLogTableName(tableSchema.name) + " WHERE hash_key=?) IS NULL THEN 0 ELSE " + - "(SELECT status FROM " + DBCommon::GetLogTableName(tableSchema.name) + " WHERE hash_key=?) " + "END)"; + std::string sql = GetInsertLogSql(DBCommon::GetLogTableName(tableSchema.name), trackerTable.GetExtendNames()); sqlite3_stmt *insertLogStmt = nullptr; int errCode = SQLiteUtils::GetStatement(dbHandle_, sql, insertLogStmt); if (errCode != E_OK) { @@ -728,15 +743,15 @@ int SQLiteSingleVerRelationalStorageExecutor::BindValueToUpsertStatement(const V } int SQLiteSingleVerRelationalStorageExecutor::BindStatusSubQueryHashKeyStatement(sqlite3_stmt *insertLogStmt, - std::vector &hashKey) + std::vector &hashKey, int &index) { - int errCode = SQLiteUtils::BindBlobToStatement(insertLogStmt, 12, hashKey); // 12 is hash_key + int errCode = SQLiteUtils::BindBlobToStatement(insertLogStmt, index++, hashKey); // next is hash_key if (errCode != E_OK) { LOGE("Bind hash_key to status subQuery statement failed, %d", errCode); return errCode; } - errCode = SQLiteUtils::BindBlobToStatement(insertLogStmt, 13, hashKey); // 13 is hash_key + errCode = SQLiteUtils::BindBlobToStatement(insertLogStmt, index++, hashKey); // next is hash_key if (errCode != E_OK) { LOGE("Bind hash_key to status subQuery2 statement failed, %d", errCode); return errCode; @@ -744,15 +759,41 @@ int SQLiteSingleVerRelationalStorageExecutor::BindStatusSubQueryHashKeyStatement return errCode; } +int BindExtendValue(const VBucket &vBucket, const TrackerTable &trackerTable, sqlite3_stmt *stmt, int &index) +{ + const std::set &extendColNames = trackerTable.GetExtendNames(); + int errCode = E_OK; + int extendValueIndex = index; + if (extendColNames.empty()) { + return SQLiteUtils::BindTextToStatement(stmt, index++, ""); + } + for (const auto &extendColName : extendColNames) { + if (vBucket.find(extendColName) == vBucket.end()) { + errCode = SQLiteUtils::BindTextToStatement(stmt, extendValueIndex++, ""); + } else { + Type extendValue = vBucket.at(extendColName); + errCode = SQLiteRelationalUtils::BindStatementByType(stmt, extendValueIndex++, extendValue); + } + if (errCode != E_OK) { + const char *tableName = DBCommon::StringMiddleMasking(trackerTable.GetTableName()).c_str(); + size_t nameLength = trackerTable.GetTableName().size(); + LOGE("[%s [%zu]] Bind extend field failed: %d", tableName, nameLength, errCode); + return errCode; + } + } + index = extendValueIndex; + return E_OK; +} + int SQLiteSingleVerRelationalStorageExecutor::BindHashKeyAndGidToInsertLogStatement(const VBucket &vBucket, - const TableSchema &tableSchema, const TrackerTable &trackerTable, sqlite3_stmt *insertLogStmt) + const TableSchema &tableSchema, const TrackerTable &trackerTable, sqlite3_stmt *insertLogStmt, int &index) { std::vector hashKey; int errCode = GetPrimaryKeyHashValue(vBucket, tableSchema, hashKey); if (errCode != E_OK) { return errCode; } - errCode = SQLiteUtils::BindBlobToStatement(insertLogStmt, 7, hashKey); // 7 is hash_key + errCode = SQLiteUtils::BindBlobToStatement(insertLogStmt, index++, hashKey); // next is hash_key if (errCode != E_OK) { LOGE("Bind hash_key to insert log statement failed, %d", errCode); return errCode; @@ -767,47 +808,43 @@ int SQLiteSingleVerRelationalStorageExecutor::BindHashKeyAndGidToInsertLogStatem } } - errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, 8, cloudGid); // 8 is cloud_gid + errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, index++, cloudGid); // next is cloud_gid if (errCode != E_OK) { LOGE("Bind cloud_gid to insert log statement failed, %d", errCode); return errCode; } - if (trackerTable.GetExtendName().empty() || vBucket.find(trackerTable.GetExtendName()) == vBucket.end()) { - errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, 9, ""); // 9 is extend_field - } else { - Type extendValue = vBucket.at(trackerTable.GetExtendName()); - errCode = SQLiteRelationalUtils::BindStatementByType(insertLogStmt, 9, extendValue); // 9 is extend_field - } + errCode = BindExtendValue(vBucket, trackerTable, insertLogStmt, index); // next is extend_field if (errCode != E_OK) { LOGE("Bind extend_field to insert log statement failed, %d", errCode); return errCode; } - errCode = BindShareValueToInsertLogStatement(vBucket, tableSchema, insertLogStmt); + errCode = BindShareValueToInsertLogStatement(vBucket, tableSchema, insertLogStmt, index); if (errCode != E_OK) { return errCode; } - return BindStatusSubQueryHashKeyStatement(insertLogStmt, hashKey); + return BindStatusSubQueryHashKeyStatement(insertLogStmt, hashKey, index); } int SQLiteSingleVerRelationalStorageExecutor::BindValueToInsertLogStatement(VBucket &vBucket, const TableSchema &tableSchema, const TrackerTable &trackerTable, sqlite3_stmt *insertLogStmt) { int64_t rowid = SQLiteUtils::GetLastRowId(dbHandle_); - int errCode = SQLiteUtils::BindInt64ToStatement(insertLogStmt, 1, rowid); + int bindIndex = 1; // 1 is rowid + int errCode = SQLiteUtils::BindInt64ToStatement(insertLogStmt, bindIndex++, rowid); if (errCode != E_OK) { LOGE("Bind rowid to insert log statement failed, %d", errCode); return errCode; } - errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, 2, GetDev()); // 2 is device + errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, bindIndex++, GetDev()); // next is device if (errCode != E_OK) { LOGE("Bind device to insert log statement failed, %d", errCode); return errCode; } - errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, 3, GetDev()); // 3 is ori_device + errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, bindIndex++, GetDev()); // next is ori_device if (errCode != E_OK) { LOGE("Bind ori_device to insert log statement failed, %d", errCode); return errCode; @@ -820,7 +857,7 @@ int SQLiteSingleVerRelationalStorageExecutor::BindValueToInsertLogStatement(VBuc return -E_CLOUD_ERROR; } - errCode = SQLiteUtils::BindInt64ToStatement(insertLogStmt, 4, val); // 4 is timestamp + errCode = SQLiteUtils::BindInt64ToStatement(insertLogStmt, bindIndex++, val); // next is timestamp if (errCode != E_OK) { LOGE("Bind timestamp to insert log statement failed, %d", errCode); return errCode; @@ -832,20 +869,20 @@ int SQLiteSingleVerRelationalStorageExecutor::BindValueToInsertLogStatement(VBuc return -E_CLOUD_ERROR; } - errCode = SQLiteUtils::BindInt64ToStatement(insertLogStmt, 5, val); // 5 is wtimestamp + errCode = SQLiteUtils::BindInt64ToStatement(insertLogStmt, bindIndex++, val); // next is wtimestamp if (errCode != E_OK) { LOGE("Bind wtimestamp to insert log statement failed, %d", errCode); return errCode; } - errCode = SQLiteUtils::MapSQLiteErrno(sqlite3_bind_int(insertLogStmt, 6, GetDataFlag())); // 6 is flag + errCode = SQLiteUtils::MapSQLiteErrno(sqlite3_bind_int(insertLogStmt, bindIndex++, GetDataFlag())); // next is flag if (errCode != E_OK) { LOGE("Bind flag to insert log statement failed, %d", errCode); return errCode; } vBucket[CloudDbConstant::ROW_ID_FIELD_NAME] = rowid; // fill rowid to cloud data to notify user - return BindHashKeyAndGidToInsertLogStatement(vBucket, tableSchema, trackerTable, insertLogStmt); + return BindHashKeyAndGidToInsertLogStatement(vBucket, tableSchema, trackerTable, insertLogStmt, bindIndex); } std::string SQLiteSingleVerRelationalStorageExecutor::GetWhereConditionForDataTable(const std::string &gidStr, @@ -1596,5 +1633,135 @@ int SQLiteSingleVerRelationalStorageExecutor::GetLocalDataCount(const std::strin } return errCode; } + +int SQLiteSingleVerRelationalStorageExecutor::UpdateExtendField(const std::string &tableName, + const std::set &extendColNames) +{ + bool isLogTableExist = false; + int errCode = SQLiteUtils::CheckTableExists(dbHandle_, DBCommon::GetLogTableName(tableName), isLogTableExist); + if (errCode == E_OK && !isLogTableExist) { + LOGW("[RDBExecutor][UpdateExtendField] Log table of [%s [%zu]] not found!", + DBCommon::StringMiddleMasking(tableName).c_str(), tableName.size()); + return E_OK; + } + std::string sql = "update " + DBCommon::GetLogTableName(tableName) + " as log set extend_field = json_object("; + for (const auto &extendColName : extendColNames) { + sql += "'" + extendColName + "',data." + extendColName + ","; + } + sql.pop_back(); + sql += ") from " + tableName + " as data where log.data_key = data." + std::string(DBConstant::SQLITE_INNER_ROWID); + sqlite3_stmt *stmt = nullptr; + errCode = SQLiteUtils::GetStatement(dbHandle_, sql, stmt); + if (errCode != E_OK) { + return errCode; + } + + ResFinalizer finalizer([stmt]() { + sqlite3_stmt *statement = stmt; + int ret = E_OK; + SQLiteUtils::ResetStatement(statement, true, ret); + if (ret != E_OK) { + LOGW("[RDBExecutor][UpdateExtendField] Reset stmt failed %d", ret); + } + }); + errCode = SQLiteUtils::StepWithRetry(stmt); + if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { + LOGE("[RDBExecutor][UpdateExtendField] Update [%s [%zu]] extend field failed: %d", + DBCommon::StringMiddleMasking(tableName).c_str(), tableName.size(), errCode); + return errCode; + } + return E_OK; +} + +int BuildJsonExtendField(const std::string &tableName, const std::string &lowVersionExtendColName, sqlite3 *db) +{ + std::string sql = "update " + DBCommon::GetLogTableName(tableName) + " set extend_field = json_object('" + + lowVersionExtendColName + "',extend_field) where data_key = -1 and (json_valid(extend_field) = 0 or " + + "json_extract(extend_field, '$." + lowVersionExtendColName +"') is null)"; + sqlite3_stmt *stmt = nullptr; + int errCode = SQLiteUtils::GetStatement(db, sql, stmt); + if (errCode != E_OK) { + return errCode; + } + errCode = SQLiteUtils::StepWithRetry(stmt); + if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { + LOGE("[RDBExecutor][UpdateDeleteDataExtendField] Update [%s [%zu]] extend field non-JSON format failed: %d", + DBCommon::StringMiddleMasking(tableName).c_str(), tableName.size(), errCode); + } else { + errCode = E_OK; + } + int ret = E_OK; + SQLiteUtils::ResetStatement(stmt, true, ret); + if (ret != E_OK) { + LOGW("[RDBExecutor][UpdateExtendField] Reset stmt failed %d", ret); + } + return errCode; +} + +std::string GetUpdateExtendFieldSql(const std::string &tableName, const std::set &oldExtendColNames, + const std::set &extendColNames) +{ + std::string sql = "update " + DBCommon::GetLogTableName(tableName) + + " set extend_field = json_insert(extend_field,"; + bool isContainNewCol = false; + for (const auto &extendColName : extendColNames) { + if (oldExtendColNames.find(extendColName) != oldExtendColNames.end()) { + continue; + } + isContainNewCol = true; + sql += "'$." + extendColName + "',null,"; + } + if (!isContainNewCol) { + return ""; + } + sql.pop_back(); + sql += ") where data_key = -1 and json_valid(extend_field) = 1;"; + return sql; +} + +int SQLiteSingleVerRelationalStorageExecutor::UpdateDeleteDataExtendField(const std::string &tableName, + const std::string &lowVersionExtendColName, const std::set &oldExtendColNames, + const std::set &extendColNames) +{ + bool isLogTableExist = false; + if (SQLiteUtils::CheckTableExists(dbHandle_, DBCommon::GetLogTableName(tableName), isLogTableExist) == E_OK && + !isLogTableExist) { + LOGW("[RDBExecutor][UpdateDeleteDataExtendField] Log table of [%s [%zu]] not found!", + DBCommon::StringMiddleMasking(tableName).c_str(), tableName.size()); + return E_OK; + } + int errCode = E_OK; + if (!lowVersionExtendColName.empty()) { + errCode = BuildJsonExtendField(tableName, lowVersionExtendColName, dbHandle_); + if (errCode != E_OK) { + LOGE("[UpdateDeleteDataExtendField] Update low version extend field of [%s [%zu]] to json failed: %d", + DBCommon::StringMiddleMasking(tableName).c_str(), tableName.size(), errCode); + return errCode; + } + } + std::string sql = GetUpdateExtendFieldSql(tableName, oldExtendColNames, extendColNames); + if (sql.empty()) { + return E_OK; + } + + sqlite3_stmt *stmt = nullptr; + errCode = SQLiteUtils::GetStatement(dbHandle_, sql, stmt); + if (errCode != E_OK) { + return errCode; + } + errCode = SQLiteUtils::StepWithRetry(stmt); + if (errCode != SQLiteUtils::MapSQLiteErrno(SQLITE_DONE)) { + LOGE("[RDBExecutor][UpdateDeleteDataExtendField] Update extend field of [%s [%zu]] failed: %d", + DBCommon::StringMiddleMasking(tableName).c_str(), tableName.size(), errCode); + } else { + errCode = E_OK; + } + int ret = E_OK; + SQLiteUtils::ResetStatement(stmt, true, ret); + if (ret != E_OK) { + LOGW("[RDBExecutor][UpdateDeleteDataExtendField] Reset stmt failed %d", ret); + } + return errCode; +} } // namespace DistributedDB #endif diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_extend_executor.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_extend_executor.cpp index a8d1137ad4df77f5faf1c61f28c1251309ab5954..174978e8cead7256a613f1774d76cdaf0a1017ef 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_extend_executor.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_ver_relational_storage_extend_executor.cpp @@ -1919,7 +1919,7 @@ int SQLiteSingleVerRelationalStorageExecutor::GetRecordFromStmt(sqlite3_stmt *st } int SQLiteSingleVerRelationalStorageExecutor::BindShareValueToInsertLogStatement(const VBucket &vBucket, - const TableSchema &tableSchema, sqlite3_stmt *insertLogStmt) + const TableSchema &tableSchema, sqlite3_stmt *insertLogStmt, int &index) { int errCode = E_OK; std::string version; @@ -1930,7 +1930,7 @@ int SQLiteSingleVerRelationalStorageExecutor::BindShareValueToInsertLogStatement return -E_CLOUD_ERROR; } } - errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, 10, version); // 10 is version + errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, index++, version); // next is version if (errCode != E_OK) { LOGE("Bind version to insert log statement failed, %d", errCode); return errCode; @@ -1946,7 +1946,7 @@ int SQLiteSingleVerRelationalStorageExecutor::BindShareValueToInsertLogStatement } } - errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, 11, shareUri); // 11 is sharing_resource + errCode = SQLiteUtils::BindTextToStatement(insertLogStmt, index++, shareUri); // next is sharing_resource if (errCode != E_OK) { LOGE("Bind shareUri to insert log statement failed, %d", errCode); } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils_extend.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils_extend.cpp index 0b98cf2cfd44fb9d41c6c7fd21da94fa3bb844eb..194fd2985e9a92df28e4185ac2fd5978db811649 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils_extend.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils_extend.cpp @@ -71,7 +71,6 @@ constexpr int VALUE_CACHE_ID = -429938; void ValueParseCacheFree(ValueParseCache *inCache) { delete inCache; - inCache = nullptr; } // We don't use cache array since we only cache value column of sqlite table, see sqlite implementation for compare. @@ -224,7 +223,6 @@ constexpr uint32_t FLATBUFFER_MAX_CACHE_SIZE = 102400; // 100 KBytes void FlatBufferCacheFree(std::vector *inCache) { delete inCache; - inCache = nullptr; } } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp index 5e40a9d11876c50a17227207a264f53afa7956f7..7245aef5c23766ed889c2bdf6c6840e08ffb854c 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp @@ -245,12 +245,10 @@ void StorageEngine::Recycle(StorageExecutor *&handle, bool isExternal) if (!isEnhance_) { LOGD("Recycle executor[%d] for id[%.6s]", handle->GetWritable(), hashIdentifier_.c_str()); } - std::list &writeUsingList = isExternal ? externalWriteUsingList_ : writeUsingList_; - std::list &writeIdleList = isExternal ? externalWriteIdleList_ : writeIdleList_; - std::list &readUsingList = isExternal ? externalReadUsingList_ : readUsingList_; - std::list &readIdleList = isExternal ? externalReadIdleList_ : readIdleList_; if (handle->GetWritable()) { std::unique_lock lock(writeMutex_); + std::list &writeUsingList = isExternal ? externalWriteUsingList_ : writeUsingList_; + std::list &writeIdleList = isExternal ? externalWriteIdleList_ : writeIdleList_; auto iter = std::find(writeUsingList.begin(), writeUsingList.end(), handle); if (iter != writeUsingList.end()) { writeUsingList.remove(handle); @@ -266,6 +264,8 @@ void StorageEngine::Recycle(StorageExecutor *&handle, bool isExternal) } } else { std::unique_lock lock(readMutex_); + std::list &readUsingList = isExternal ? externalReadUsingList_ : readUsingList_; + std::list &readIdleList = isExternal ? externalReadIdleList_ : readIdleList_; auto iter = std::find(readUsingList.begin(), readUsingList.end(), handle); if (iter != readUsingList.end()) { readUsingList.remove(handle); @@ -416,11 +416,11 @@ void StorageEngine::AddStorageExecutor(StorageExecutor *handle, bool isExternal) return; } - std::list &writeIdleList = isExternal ? externalWriteIdleList_ : writeIdleList_; - std::list &readIdleList = isExternal ? externalReadIdleList_ : readIdleList_; if (handle->GetWritable()) { + std::list &writeIdleList = isExternal ? externalWriteIdleList_ : writeIdleList_; writeIdleList.push_back(handle); } else { + std::list &readIdleList = isExternal ? externalReadIdleList_ : readIdleList_; readIdleList.push_back(handle); } } diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp index 36318036f1fc6b88f3df76d6a1c591e4c35eb27a..d7ad65159a8710362a1ae6384093cbc37e2f618f 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp @@ -793,7 +793,7 @@ std::vector CloudDBProxy::GetNotEmptyAssetRecords(std::vector &originalRecords, - const std::vector indexes, std::vector &newRecords) + const std::vector &indexes, std::vector &newRecords) { int i = 0; for (const auto index : indexes) { diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h index f706c90e6b33dc64561a526eef91eff5edc0989c..018c987343e33b52b1ec73673bc4fb3548b139f8 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h @@ -187,11 +187,11 @@ protected: std::vector &necessaryRecords, const InnerBatchOpType operationType); // save record with assets in nonEmptyRecords, return the indexes of these records in the original vector - std::vector GetNotEmptyAssetRecords(std::vector &originalRecords, + static std::vector GetNotEmptyAssetRecords(std::vector &originalRecords, std::vector &nonEmptyRecords); // copy newRecords's assets and status back to originalRecords, based on indexes - void CopyAssetsBack(std::vector &originalRecords, const std::vector indexes, + static void CopyAssetsBack(std::vector &originalRecords, const std::vector &indexes, std::vector &newRecords); mutable std::shared_mutex cloudMutex_; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h index c37540fdd036e044addb83d232841d24d5241c99..eeb07ddc29e917ecb5a7b391989ae5197e5cb3ff 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h @@ -459,7 +459,7 @@ protected: using DownloadAssetsRecords = std::vector; using DownloadAssetDetail = std::tuple; DownloadAssetDetail GetDownloadRecords(const DownloadList &downloadList, const std::set &dupHashKeySet, - bool isSharedTable, InnerProcessInfo &info); + bool isSharedTable, const InnerProcessInfo &info); int BatchDownloadAndCommitRes(const DownloadList &downloadList, const std::set &dupHashKeySet, InnerProcessInfo &info, ChangedData &changedAssets, diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer_extend.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer_extend.cpp index cc3ef7ffb86542d5d147e09dbd6279b7fc51065a..9af87b83e03ae974cf030b56d90720de15a4417f 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer_extend.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer_extend.cpp @@ -1438,7 +1438,7 @@ void CloudSyncer::FillDownloadItem(const std::set &dupHashKeySet, const Dow } CloudSyncer::DownloadAssetDetail CloudSyncer::GetDownloadRecords(const DownloadList &downloadList, - const std::set &dupHashKeySet, bool isSharedTable, InnerProcessInfo &info) + const std::set &dupHashKeySet, bool isSharedTable, const InnerProcessInfo &info) { DownloadItemRecords downloadRecord; RemoveAssetsRecords removeAssets; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/device/sync_task_context.h b/kv_store/frameworks/libs/distributeddb/syncer/src/device/sync_task_context.h index 825dac4146db583d40686f885e2e15e3fdac6499..42d53e7dc59ca8896b35112575acf5d3ef9ac365 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/device/sync_task_context.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/device/sync_task_context.h @@ -290,7 +290,7 @@ protected: volatile bool isCommNormal_; volatile int taskErrCode_; - volatile int commErrCode_; + std::atomic commErrCode_; volatile uint64_t packetId_ = 0; // used for assignment to reSendMap_.ReSendInfo.packetId in 103 version or above volatile bool syncTaskRetryStatus_; volatile bool isSyncRetry_; diff --git a/kv_store/frameworks/libs/distributeddb/test/fuzztest/relationalstoredelegate_fuzzer/relationalstoredelegate_fuzzer.cpp b/kv_store/frameworks/libs/distributeddb/test/fuzztest/relationalstoredelegate_fuzzer/relationalstoredelegate_fuzzer.cpp index e2d3e45b2a42dfa65d3606156408f77809fdf43d..78c2971af70419dd5b64400656dc7b70fc4a5064 100644 --- a/kv_store/frameworks/libs/distributeddb/test/fuzztest/relationalstoredelegate_fuzzer/relationalstoredelegate_fuzzer.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/fuzztest/relationalstoredelegate_fuzzer/relationalstoredelegate_fuzzer.cpp @@ -97,12 +97,12 @@ void TearDown() DistributedDBToolsTest::RemoveTestDbFiles(g_testDir); } -void MultiCombineTest(const uint8_t *data, const std::string &tableName, const std::string &extendColName, +void MultiCombineTest(const uint8_t *data, const std::string &tableName, const std::set &extendColNames, const std::set &trackerColNames, const bool isDeleted) { TrackerSchema schema; schema.tableName = tableName; - schema.extendColName = extendColName; + schema.extendColNames = extendColNames; schema.trackerColNames = trackerColNames; g_delegate->SetTrackerTable(schema); g_delegate->SetReference({}); @@ -112,7 +112,7 @@ void MultiCombineTest(const uint8_t *data, const std::string &tableName, const s auto pragmaCmd = static_cast(data[0]); g_delegate->Pragma(pragmaCmd, pragmaData); VBucket records; - records[extendColName] = extendColName; + records[*extendColNames.begin()] = *extendColNames.begin(); auto recordStatus = static_cast(data[0]); g_delegate->UpsertData(tableName, { records }, recordStatus); DistributedDB::SqlCondition sqlCondition; @@ -151,10 +151,10 @@ void CombineTest(const uint8_t *data, size_t size) SyncStatusCallback callback = nullptr; g_delegate->Sync(device, mode, query, callback, len % 2); // 2 is mod num for wait parameter g_delegate->GetCloudSyncTaskCount(); - std::string extendColName = fuzzerData.GetString(len % lenMod); + std::set extendColNames = {fuzzerData.GetString(len % lenMod)}; std::set trackerColNames = fuzzerData.GetStringSet(len % lenMod); bool isLogicDeleted = static_cast(*data); - MultiCombineTest(data, tableName, extendColName, trackerColNames, isLogicDeleted); + MultiCombineTest(data, tableName, extendColNames, trackerColNames, isLogicDeleted); std::string deviceId = device.size() > 0 ? device[0] : tableName; g_delegate->RemoveDeviceData(); g_delegate->RemoveDeviceData(deviceId); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp index 7bf98eb51b869846942b250012f6af4545bf1b2a..797bb30b941ddd65da96dd3553fc8680c49dec28 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp @@ -806,7 +806,7 @@ HWTEST_F(DistributedDBCommonTest, AbnormalTrackerTableTest, TestSize.Level1) */ const TrackerSchema schema = { .tableName = "table1", - .extendColName = "extendCol1", + .extendColNames = {"extendCol1"}, .trackerColNames = {"trackerCol1"}, }; trackerObj1.Init(schema); @@ -816,8 +816,9 @@ HWTEST_F(DistributedDBCommonTest, AbnormalTrackerTableTest, TestSize.Level1) trackerObj1.SetTrackerNames(trackerNames); EXPECT_EQ(trackerObj1.IsChanging(schema), true); const std::string colName = "col"; - trackerObj1.SetExtendName(colName); - std::string str3 = trackerObj1.GetExtendName(); + trackerObj1.SetExtendNames({colName}); + std::set extendNames = trackerObj1.GetExtendNames(); + std::string str3 = *extendNames.begin(); EXPECT_TRUE(str3.compare(0, str3.length(), colName) == 0); EXPECT_EQ(trackerObj1.IsChanging(schema), true); } diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp index f8824a6cb22fc91e4975b68769ff9af18b12761b..d69bfe94d8a9ccb2fee762ac6835bc2ba77592ec 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_schema_unit_test.cpp @@ -525,13 +525,14 @@ HWTEST_F(DistributedDBSchemalTest, ParseTrackerSchemaAndName, TestSize.Level1) * @tc.steps: step1. Trans TrackerSchema to Lower. * @tc.expected: step1. Trans success. */ - const TrackerSchema srcSchema = {"Test", "Col", {"Col1", "Col2"}}; + const TrackerSchema srcSchema = {"Test", {"Col"}, {"Col1", "Col2"}}; TrackerSchema destSchema; SchemaUtils::TransTrackerSchemaToLower(srcSchema, destSchema); - TrackerSchema expectedSchema = {"test", "col", {"col1", "col2"}}; + TrackerSchema expectedSchema = {"test", {"col"}, {"col1", "col2"}}; EXPECT_TRUE(destSchema.tableName.compare(0, expectedSchema.tableName.length(), expectedSchema.tableName) == 0); - EXPECT_TRUE( - destSchema.extendColName.compare(0, expectedSchema.extendColName.length(), expectedSchema.extendColName) == 0); + for (const auto &extendColName : destSchema.extendColNames) { + EXPECT_TRUE(expectedSchema.extendColNames.find(extendColName) != expectedSchema.extendColNames.end()); + } /** * @tc.steps: step2. Strip space from name. diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.cpp index c25e42d4544c21bdc45ffeed8734d03406710a13..1ce3148bd9d7e54e560db8954e11a8654b0f0e4f 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.cpp @@ -269,6 +269,14 @@ void AdapterStub::SimulateSendRetryClear(const std::string &dstTarget, int softB } } +void AdapterStub::SimulateTriggerSendableCallback(const std::string &dstTarget, int softBusErrCode) +{ + std::lock_guard onSendableLockGuard(onSendableMutex_); + if (onSendableHandle_) { + onSendableHandle_(dstTarget, softBusErrCode); + } +} + void AdapterStub::SimulateSendPartialLoss() { isPartialLossSimulated_ = true; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.h index 1dc6839fc0ea84828374ac86bab9835096837e08..2040a210d5df7c45438ad26716cb90708829f17f 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/adapter_stub.h @@ -68,6 +68,7 @@ public: void SimulateSendRetry(const std::string &dstTarget); void SimulateSendRetryClear(const std::string &dstTarget, int softBusErrCode = E_OK); + void SimulateTriggerSendableCallback(const std::string &dstTarget, int softBusErrCode = E_OK); void SimulateSendPartialLoss(); void SimulateSendPartialLossClear(); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp index 95d82774af27ba305663d2695a17693fc878eeb4..3e27785c08cc78ef486bb8f97921c413b4b42574 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/communicator/distributeddb_communicator_deep_test.cpp @@ -1015,3 +1015,65 @@ HWTEST_F(DistributedDBCommunicatorDeepTest, RetrySendExceededLimit001, TestSize. g_envDeviceA.adapterHandle->ForkSendBytes(nullptr); AdapterStub::DisconnectAdapterStub(g_envDeviceA.adapterHandle, g_envDeviceB.adapterHandle); } + +/** + * @tc.name: RetrySendExceededLimit002 + * @tc.desc: Test multi thread call SendableCallback when the number of retry times exceeds the limit + * @tc.type: FUNC + * @tc.require: + * @tc.author: suyue + */ +HWTEST_F(DistributedDBCommunicatorDeepTest, RetrySendExceededLimit002, TestSize.Level2) +{ + /** + * @tc.steps: step1. DeviceA send SendMessage and set SendBytes interface return -E_WAIT_RETRY + * @tc.expected: step1. Send ok + */ + AdapterStub::ConnectAdapterStub(g_envDeviceA.adapterHandle, g_envDeviceB.adapterHandle); + std::atomic count = 0; + g_envDeviceA.adapterHandle->ForkSendBytes([&count]() { + count++; + return -E_WAIT_RETRY; + }); + std::vector> sendResult; + auto sendResultNotifier = [&sendResult](int result, bool isDirectEnd) { + sendResult.push_back(std::pair(result, isDirectEnd)); + }; + const uint32_t dataLength = 13 * 1024 * 1024; // 13 MB, 1024 is scale + Message *sendMsg = BuildRegedGiantMessage(dataLength); + ASSERT_NE(sendMsg, nullptr); + SendConfig conf = {false, false, 0}; + EXPECT_EQ(g_commAB->SendMessage(DEVICE_NAME_B, sendMsg, conf, sendResultNotifier), E_OK); + std::this_thread::sleep_for(std::chrono::seconds(1)); // Wait 1s to make sure send done + + /** + * @tc.steps: step2. Triggering multi thread call SendableCallback interface and set errorCode + * @tc.expected: step2. Callback success + */ + std::vector threads; + int threadNum = 3; + threads.reserve(threadNum); + for (int n = 0; n < threadNum; n++) { + threads.emplace_back([&]() { + g_envDeviceA.adapterHandle->SimulateTriggerSendableCallback(DEVICE_NAME_B, -E_BASE); + }); + } + for (std::thread &t : threads) { + t.join(); + } + + /** + * @tc.steps: step3. Make The number of messages sent by device A exceed the limit + * @tc.expected: step3. SendResult is the errorCode set by SendableCallback interface + */ + int reTryTimes = 5; + while ((count < 4) && (reTryTimes > 0)) { + std::this_thread::sleep_for(std::chrono::seconds(3)); + reTryTimes--; + } + ASSERT_EQ(sendResult.size(), static_cast(1)); + EXPECT_EQ(sendResult[0].first, -E_BASE); + EXPECT_EQ(sendResult[0].second, false); + g_envDeviceA.adapterHandle->ForkSendBytes(nullptr); + AdapterStub::DisconnectAdapterStub(g_envDeviceA.adapterHandle, g_envDeviceB.adapterHandle); +} diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp index bb08417a931ea672e569a8cad6f8431058f50aa9..7e7d1af7c670b6bfefb1f627537f70051e083266 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp @@ -157,7 +157,7 @@ static void SetTracerSchemaTest001(const std::string &tableName) { TrackerSchema schema; schema.tableName = tableName; - schema.extendColName = "id"; + schema.extendColNames = {"id"}; schema.trackerColNames = {"name"}; RelationalStoreDelegate *delegate = nullptr; DBStatus status = g_mgr.OpenStore(g_dbDir + STORE_ID + DB_SUFFIX, STORE_ID, {}, delegate); @@ -1074,7 +1074,11 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, DropDeleteData001, TestS HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest001, TestSize.Level0) { std::map ans; +#ifdef USE_FFRT + ffrt::mutex mutex; +#else std::mutex mutex; +#endif size_t num = 1000; /** @@ -1083,10 +1087,11 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest001, TestSize.Le */ TaskHandle h1 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { for (size_t j = 0; j < num; j++) { - ADAPTER_AUTO_LOCK(lock, mutex); + ConcurrentAdapter::AdapterAutoLock(mutex); for (size_t i = 0; i < num; i++) { ans.insert_or_assign(i, i); } + ConcurrentAdapter::AdapterAutoUnLock(mutex); } }, nullptr, &ans); @@ -1096,10 +1101,11 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest001, TestSize.Le */ TaskHandle h2 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { for (size_t i = 0; i < num; i++) { - ADAPTER_AUTO_LOCK(lock, mutex); + ConcurrentAdapter::AdapterAutoLock(mutex); for (auto it = ans.begin(); it != ans.end();) { it = ans.erase(it); } + ConcurrentAdapter::AdapterAutoUnLock(mutex); } }, nullptr, &ans); @@ -1109,11 +1115,12 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest001, TestSize.Le */ TaskHandle h3 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { for (size_t i = 0; i < num; i++) { - ADAPTER_AUTO_LOCK(lock, mutex); + ConcurrentAdapter::AdapterAutoLock(mutex); for (auto it = ans.begin(); it != ans.end(); it++) { int j = it->first; EXPECT_GE(j, 0); } + ConcurrentAdapter::AdapterAutoUnLock(mutex); } }, &ans, nullptr); ADAPTER_WAIT(h1); @@ -1132,7 +1139,11 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest001, TestSize.Le HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest002, TestSize.Level0) { std::map ans; +#ifdef USE_FFRT + ffrt::mutex mutex; +#else std::mutex mutex; +#endif size_t num = 1000; /** @@ -1142,10 +1153,11 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest002, TestSize.Le TaskHandle h1 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { TaskHandle hh1 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { for (size_t j = 0; j < num; j++) { - ADAPTER_AUTO_LOCK(lock, mutex); + ConcurrentAdapter::AdapterAutoLock(mutex); for (size_t i = 0; i < num; i++) { ans.insert_or_assign(i, i); } + ConcurrentAdapter::AdapterAutoUnLock(mutex); } }, nullptr, &ans); ADAPTER_WAIT(hh1); @@ -1158,10 +1170,11 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest002, TestSize.Le TaskHandle h2 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { TaskHandle hh2 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { for (size_t i = 0; i < num; i++) { - ADAPTER_AUTO_LOCK(lock, mutex); + ConcurrentAdapter::AdapterAutoLock(mutex); for (auto it = ans.begin(); it != ans.end();) { it = ans.erase(it); } + ConcurrentAdapter::AdapterAutoUnLock(mutex); } }, nullptr, &ans); ADAPTER_WAIT(hh2); @@ -1174,11 +1187,12 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, FfrtTest002, TestSize.Le TaskHandle h3 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { TaskHandle hh3 = ConcurrentAdapter::ScheduleTaskH([this, &ans, &mutex, num]() { for (size_t i = 0; i < num; i++) { - ADAPTER_AUTO_LOCK(lock, mutex); + ConcurrentAdapter::AdapterAutoLock(mutex); for (auto it = ans.begin(); it != ans.end(); it++) { int j = it->first; EXPECT_GE(j, 0); } + ConcurrentAdapter::AdapterAutoUnLock(mutex); } }, &ans, nullptr); ADAPTER_WAIT(hh3); @@ -1816,7 +1830,7 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, AbnormalDelegateImplTest EXPECT_EQ(delegateImpl->CleanTrackerData("", 0), INVALID_ARGS); TrackerSchema schema; EXPECT_EQ(delegateImpl->SetTrackerTable(schema), INVALID_ARGS); - schema = {.tableName = "test", .extendColName = "", .trackerColNames = {}}; + schema = {.tableName = "test", .extendColNames = {}, .trackerColNames = {}}; EXPECT_EQ(delegateImpl->SetTrackerTable(schema), NOT_FOUND); /** diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp index 6b4c0cd541ac7ce53372967ef5de17e256259a9a..1637a5887a88cad2536eb33db199e5b2d527917c 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp @@ -550,13 +550,13 @@ namespace { if (g_delegate != nullptr) { g_delegate->UnRegisterObserver(g_observer); } - delete g_observer; - g_observer = nullptr; - g_virtualCloudDb = nullptr; if (g_delegate != nullptr) { EXPECT_EQ(g_mgr.CloseStore(g_delegate), DBStatus::OK); g_delegate = nullptr; } + delete g_observer; + g_observer = nullptr; + g_virtualCloudDb = nullptr; } class DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest : public testing::Test { diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_set_cloud_schema_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_set_cloud_schema_test.cpp index 40cdbc7e5d81646a5e809848b014993f91c76967..0498181882743a2fb44ab2064d2aa741320f7548 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_set_cloud_schema_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_set_cloud_schema_test.cpp @@ -1148,7 +1148,7 @@ namespace { */ TrackerSchema trackerSchema = { .tableName = g_tableName1, - .extendColName = "married", + .extendColNames = {"married"}, .trackerColNames = {"married"} }; ASSERT_EQ(g_delegate->SetTrackerTable(trackerSchema), DBStatus::OK); @@ -2197,4 +2197,51 @@ namespace { g_observer->SetExpectedResult(changedData); EXPECT_EQ(g_observer->IsAllChangedDataEq(), true); } + + /** + * @tc.name: SetTrackerTable001 + * @tc.desc: Test set tracker table before cloud sync + * @tc.type: FUNC + * @tc.require: + * @tc.author: liaoyonghuang + */ + HWTEST_F(DistributedDBCloudInterfacesSetCloudSchemaTest, SetTrackerTable001, TestSize.Level0) + { + /** + * @tc.steps:step1. init cloud data + * @tc.expected: step1. return OK + */ + InitCloudEnv(); + int cloudCount = 10; + InsertCloudTableRecord(0, cloudCount, false); + /** + * @tc.steps:step2. set tracker table and sync cloud data + * @tc.expected: step2. return OK + */ + TrackerSchema schema = {g_tableName2, {"height", "name"}, {"name"}}; + g_delegate->SetTrackerTable(schema); + Query query = Query::Select().FromTable({ g_tableName2 }); + BlockSync(query, g_delegate, DBStatus::OK); + /** + * @tc.steps:step3. Check extend_field + * @tc.expected: step3. Return E_OK. + */ + std::string checkValidJsonSql = "select count(*) from " + DBCommon::GetLogTableName(g_tableName2) + + " where json_valid(extend_field) = 1"; + EXPECT_EQ(sqlite3_exec(db_, checkValidJsonSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(cloudCount), nullptr), SQLITE_OK); + + std::string checkHeightSql = "select count(*) from " + DBCommon::GetLogTableName(g_tableName2) + + " where json_extract(extend_field, '$.height') = 166.0"; + EXPECT_EQ(sqlite3_exec(db_, checkHeightSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(cloudCount), nullptr), SQLITE_OK); + + for (int i = 0; i < cloudCount; i++) { + std::string expectName = "Local" + std::to_string(i); + std::string checkNameSql = "select count(*) from " + DBCommon::GetLogTableName(g_tableName2) + + " where json_extract(extend_field, '$.name') = 'Cloud" + std::to_string(i) + "'"; + EXPECT_EQ(sqlite3_exec(db_, checkNameSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(1u), nullptr), SQLITE_OK); + } + } } // namespace \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_extend_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_extend_test.cpp index 1e1ad17ac6e80e54f5083be76e68974f97a2c616..bb9678ad83751e52d38eb108919bd2ac6c75d74b 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_extend_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_nb_delegate_extend_test.cpp @@ -925,46 +925,6 @@ HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, SyncRangeQuery001, TestSiz EXPECT_EQ(mgr.DeleteKvStore(STORE_ID_1), OK); } -#ifndef USE_RD_KERNEL -/** - * @tc.name: InvalidOption001 - * @tc.desc: Test get kv store use invalid options info func with rd, need execute in manual. - * @tc.type: FUNC - * @tc.require: - * @tc.author: zhujinlin - */ -HWTEST_F(DistributedDBInterfacesNBDelegateExtendTest, InvalidOption001, TestSize.Level3) -{ - /** - * @tc.steps:step1. Get the nb delegate. - * @tc.expected: step1. Get results OK and non-null delegate. - */ - KvStoreNbDelegate::Option option = {true, false, false}; - option.storageEngineType = GAUSSDB_RD; - option.rdconfig.pageSize = 64u; - option.rdconfig.cacheSize = 4u * 1024u * 1024u; - option.rdconfig.type = HASH; - g_mgr.GetKvStore("InvalidOption001", option, g_kvNbDelegateCallback); - ASSERT_EQ(g_kvNbDelegatePtr, nullptr); - EXPECT_EQ(g_kvDelegateStatus, INVALID_ARGS); - /** - * @tc.steps:step2. Get the nb delegate. - * @tc.expected: step2. Get results OK and non-null delegate. - */ - option.rdconfig.cacheSize = (4u * 1024u * 1024u) - 64u; - g_mgr.GetKvStore("InvalidOption001", option, g_kvNbDelegateCallback); - ASSERT_NE(g_kvNbDelegatePtr, nullptr); - EXPECT_EQ(g_kvDelegateStatus, OK); - /** - * @tc.steps:step3. Close and delete KV store - * @tc.expected: step3. Returns OK. - */ - g_mgr.CloseKvStore(g_kvNbDelegatePtr); - EXPECT_EQ(g_mgr.DeleteKvStore("InvalidOption001"), OK); - g_kvNbDelegatePtr = nullptr; -} -#endif - /** * @tc.name: OptionValidCheck001 * @tc.desc: test validation of option mode diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_tracker_table_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_tracker_table_test.cpp index f8d690973f7ab1dca1795f17126089d4e3641533..6028fabbd2529a126d2f4aca83ea077678689c9f 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_tracker_table_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_tracker_table_test.cpp @@ -82,13 +82,13 @@ namespace { const std::set LOCAL_TABLE_TRACKER_NAME_SET4 = { "height", "name" }; const std::set LOCAL_TABLE_TRACKER_NAME_SET5 = { "name", "" }; TrackerSchema g_normalSchema1 = { - .tableName = TABLE_NAME2, .extendColName = EXTEND_COL_NAME2, .trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET2 + .tableName = TABLE_NAME2, .extendColNames = {EXTEND_COL_NAME2}, .trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET2 }; TrackerSchema g_normalSchema2 = { - .tableName = TABLE_NAME2, .extendColName = EXTEND_COL_NAME3, .trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET2 + .tableName = TABLE_NAME2, .extendColNames = {EXTEND_COL_NAME3}, .trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET2 }; TrackerSchema g_normalSchema3 = { - .tableName = TABLE_NAME2, .extendColName = EXTEND_COL_NAME3, .trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET4 + .tableName = TABLE_NAME2, .extendColNames = {EXTEND_COL_NAME3}, .trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET4 }; void CreateMultiTable() @@ -142,7 +142,8 @@ namespace { void CheckExtendAndCursor(uint64_t num, int start, const std::string &tableName, bool addNum = true) { int index = 0; - string querySql = "select extend_field, cursor from " + std::string(DBConstant::RELATIONAL_PREFIX) + tableName + + string querySql = "select json_extract(extend_field, '$.name'), cursor from " + + std::string(DBConstant::RELATIONAL_PREFIX) + tableName + "_log" + " where data_key <= " + std::to_string(num); sqlite3_stmt *stmt = nullptr; EXPECT_EQ(SQLiteUtils::GetStatement(g_db, querySql, stmt), E_OK); @@ -342,7 +343,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest002, * @tc.steps:step2. trackerColNames is empty but extendColName is no exist * @tc.expected: step2. Return OK. */ - schema.extendColName = EXTEND_COL_NAME1; + schema.extendColNames = {EXTEND_COL_NAME1}; SetTrackerTableTest(schema, OK); /** @@ -350,7 +351,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest002, * @tc.expected: step1. Return OK. */ schema.trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET2; - schema.extendColName = {}; + schema.extendColNames = {}; SetTrackerTableTest(schema, OK); } @@ -384,7 +385,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest003, * @tc.expected: step3. Return SCHEMA_MISMATCH. */ schema.trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET2; - schema.extendColName = EXTEND_COL_NAME1; + schema.extendColNames = {EXTEND_COL_NAME1}; SetTrackerTableTest(schema, SCHEMA_MISMATCH); } @@ -530,9 +531,10 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest007, std::string sql = "UPDATE " + TABLE_NAME2 + " SET age='666'"; EXPECT_EQ(RelationalTestUtils::ExecSql(g_db, sql), SQLITE_OK); sql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + - " where extend_field=666;"; + " where json_extract(extend_field, '$.age')=666;"; + char *errmsg; EXPECT_EQ(sqlite3_exec(g_db, sql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, - reinterpret_cast(num), nullptr), SQLITE_OK); + reinterpret_cast(num), &errmsg), SQLITE_OK); CloseStore(); } @@ -563,8 +565,8 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest008, uint64_t updateNum = 2; BatchUpdateTableName2Data(updateNum, LOCAL_TABLE_TRACKER_NAME_SET3); int index = 0; - string querySql = "select extend_field, cursor from " + std::string(DBConstant::RELATIONAL_PREFIX) + TABLE_NAME2 + - "_log" + " where data_key <= " + std::to_string(updateNum); + string querySql = "select json_extract(extend_field, '$.name'), cursor from " + + DBCommon::GetLogTableName(TABLE_NAME2) + " where data_key <= " + std::to_string(updateNum); sqlite3_stmt *stmt = nullptr; EXPECT_EQ(SQLiteUtils::GetStatement(g_db, querySql, stmt), E_OK); while (SQLiteUtils::StepWithRetry(stmt) == SQLiteUtils::MapSQLiteErrno(SQLITE_ROW)) { @@ -887,7 +889,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest015, */ TrackerSchema schema = g_normalSchema1; EXPECT_EQ(g_delegate->SetTrackerTable(schema), WITH_INVENTORY_DATA); - string querySql = "select extend_field from " + std::string(DBConstant::RELATIONAL_PREFIX) + TABLE_NAME2 + "_log" + + string querySql = "select json_extract(extend_field, '$.name') from " + DBCommon::GetLogTableName(TABLE_NAME2) + " where data_key = 15;"; sqlite3_stmt *stmt = nullptr; EXPECT_EQ(SQLiteUtils::GetStatement(g_db, querySql, stmt), E_OK); @@ -1085,7 +1087,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest019, * @tc.expected: step4. Return OK. */ EXPECT_EQ(g_delegate->CleanTrackerData(TABLE_NAME2, num + (num / HALF)), OK); - std::string sql = "select count(*) from " + std::string(DBConstant::RELATIONAL_PREFIX) + TABLE_NAME2 + "_log" + + std::string sql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + " where extend_field is NULL;"; EXPECT_EQ(sqlite3_exec(g_db, sql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, reinterpret_cast(0), nullptr), SQLITE_OK); @@ -1125,8 +1127,8 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest020, * @tc.steps:step3. check the extend_field and cursor is null * @tc.expected: step3. Return OK. */ - sql = "select count(*) from " + std::string(DBConstant::RELATIONAL_PREFIX) + TABLE_NAME2 + - "_log where extend_field is NULL " + " AND cursor is NULL"; + sql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where extend_field is NULL " + " AND cursor is NULL"; EXPECT_EQ(sqlite3_exec(g_db, sql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, reinterpret_cast(0), nullptr), SQLITE_OK); @@ -1134,7 +1136,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest020, * @tc.steps:step4. set diff schema, check the extend_field and cursor is null * @tc.expected: step4. Return OK. */ - schema.extendColName = EXTEND_COL_NAME3; + schema.extendColNames = {EXTEND_COL_NAME3}; EXPECT_EQ(g_delegate->SetTrackerTable(schema), OK); sql = "select count(*) from " + std::string(DBConstant::RELATIONAL_PREFIX) + TABLE_NAME2 + "_log where extend_field is NULL " + " AND cursor is NULL"; @@ -1230,7 +1232,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest024, OpenStore(); TrackerSchema schema; schema.tableName = TABLE_NAME3; - schema.extendColName = EXTEND_COL_NAME3; + schema.extendColNames = {EXTEND_COL_NAME3}; schema.trackerColNames = { EXTEND_COL_NAME3 }; EXPECT_EQ(g_delegate->SetTrackerTable(schema), INVALID_ARGS); CloseStore(); @@ -1877,7 +1879,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest028, * @tc.steps:step2. trackerColNames is not empty * @tc.expected: step2. Return OK. */ - schema.extendColName = EXTEND_COL_NAME2; + schema.extendColNames = {EXTEND_COL_NAME2}; schema.trackerColNames = LOCAL_TABLE_TRACKER_NAME_SET2; SetTrackerTableTest(schema, OK); @@ -1999,7 +2001,7 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest031, */ TrackerSchema schema; schema.tableName = TABLE_NAME2; - schema.extendColName = EXTEND_COL_NAME2; + schema.extendColNames = {EXTEND_COL_NAME2}; schema.trackerColNames = {}; schema.isForceUpgrade = false; schema.isTrackAction = true; @@ -2087,6 +2089,182 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest033, CloseStore(); } +/** + * @tc.name: TrackerTableTest034 + * @tc.desc: Test set tracker table with multi extend names + * @tc.type: FUNC + * @tc.require: + * @tc.author: liaoyonghuang + */ +HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest034, TestSize.Level0) +{ + /** + * @tc.steps:step1. Init db and set tracker table with multi extend names + * @tc.expected: step1. Return OK. + */ + CreateMultiTable(); + OpenStore(); + TrackerSchema schema = g_normalSchema1; + schema.extendColNames = {EXTEND_COL_NAME2, EXTEND_COL_NAME3}; + EXPECT_EQ(g_delegate->SetTrackerTable(schema), OK); + /** + * @tc.steps:step2. Insert data to table2 + * @tc.expected: step2. Return E_OK. + */ + uint64_t num = 10; + BatchInsertTableName2Data(num); + /** + * @tc.steps:step3. Check extend_field + * @tc.expected: step3. Return E_OK. + */ + std::string checkValidJsonSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_valid(extend_field) = 1"; + EXPECT_EQ(sqlite3_exec(g_db, checkValidJsonSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(num), nullptr), SQLITE_OK); + + std::string checkAgeSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_extract(extend_field, '$.age') = 18"; + EXPECT_EQ(sqlite3_exec(g_db, checkAgeSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(num), nullptr), SQLITE_OK); + + for (uint64_t i = 0; i < num; i++) { + std::string expectName = "Local" + std::to_string(i); + std::string checkNameSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_extract(extend_field, '$.name') = 'Local" + std::to_string(i) + "'"; + EXPECT_EQ(sqlite3_exec(g_db, checkNameSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(1u), nullptr), SQLITE_OK); + } + CloseStore(); +} + +/** + * @tc.name: TrackerTableTest035 + * @tc.desc: Test set tracker table with multi extend names repeatedly + * @tc.type: FUNC + * @tc.require: + * @tc.author: liaoyonghuang + */ +HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest035, TestSize.Level0) +{ + /** + * @tc.steps:step1. Init db and set tracker table with multi extend names + * @tc.expected: step1. Return OK. + */ + CreateMultiTable(); + OpenStore(); + EXPECT_EQ(g_delegate->CreateDistributedTable(TABLE_NAME2, CLOUD_COOPERATION), OK); + TrackerSchema schema = g_normalSchema1; + schema.extendColNames = {EXTEND_COL_NAME3}; + EXPECT_EQ(g_delegate->SetTrackerTable(schema), OK); + /** + * @tc.steps:step2. Insert data to table2 + * @tc.expected: step2. Return E_OK. + */ + uint64_t num = 10; + BatchInsertTableName2Data(num); + std::string sql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_valid(extend_field) = 1 and json_extract(extend_field, '$.name') is not null"; + EXPECT_EQ(sqlite3_exec(g_db, sql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(0u), nullptr), SQLITE_OK); + /** + * @tc.steps:step3. Set tracker table repeatedly + * @tc.expected: step3. Return E_OK. + */ + schema.extendColNames = {EXTEND_COL_NAME2, EXTEND_COL_NAME3}; + EXPECT_EQ(g_delegate->SetTrackerTable(schema), OK); + /** + * @tc.steps:step4. Check extend_field + * @tc.expected: step4. Return E_OK. + */ + EXPECT_EQ(sqlite3_exec(g_db, sql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(num), nullptr), SQLITE_OK); + for (uint64_t i = 0; i < num; i++) { + std::string expectName = "Local" + std::to_string(i); + std::string checkNameSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_extract(extend_field, '$.name') = 'Local" + std::to_string(i) + "'"; + EXPECT_EQ(sqlite3_exec(g_db, checkNameSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(1u), nullptr), SQLITE_OK); + } + CloseStore(); +} + +void SetLowVersionSchema(sqlite3 *db) +{ + std::string sql = "update naturalbase_rdb_aux_metadata set value = " + "json_insert(value,'$.TABLES[0].EXTEND_NAME', 'age')" + "where json_valid(value)=1 and json_extract(value, '$.TABLES[0].EXTEND_NAMES') is not null"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); + sql = "update naturalbase_rdb_aux_metadata set value = json_remove(value,'$.TABLES[0].EXTEND_NAMES')" + "where json_valid(value)=1 and json_extract(value, '$.TABLES[0].EXTEND_NAMES') is not null"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); +} + +/** + * @tc.name: TrackerTableTest036 + * @tc.desc: Test Upgrade extend field + * @tc.type: FUNC + * @tc.require: + * @tc.author: liaoyonghuang + */ +HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, TrackerTableTest036, TestSize.Level0) +{ + /** + * @tc.steps:step1. Init db and init extend field to old version data + * @tc.expected: step1. Return OK. + */ + CreateMultiTable(); + OpenStore(); + EXPECT_EQ(g_delegate->CreateDistributedTable(TABLE_NAME2, CLOUD_COOPERATION), OK); + TrackerSchema schema = g_normalSchema1; + schema.extendColNames = {EXTEND_COL_NAME3}; + EXPECT_EQ(g_delegate->SetTrackerTable(schema), OK); + uint64_t num = 10; + BatchInsertTableName2Data(num); + std::string sql = "delete from " + TABLE_NAME2 + " where _rowid_ % 2 = 0"; + EXPECT_EQ(RelationalTestUtils::ExecSql(g_db, sql), SQLITE_OK); + sql = "update " + DBCommon::GetLogTableName(TABLE_NAME2) + " set extend_field = 'old_age'"; + EXPECT_EQ(RelationalTestUtils::ExecSql(g_db, sql), SQLITE_OK); + SetLowVersionSchema(g_db); + CloseStore(); + OpenStore(); + /** + * @tc.steps:step2. Set tracker table + * @tc.expected: step2. Return E_OK. + */ + schema.extendColNames = {EXTEND_COL_NAME2, EXTEND_COL_NAME3}; + EXPECT_EQ(g_delegate->SetTrackerTable(schema), OK); + /** + * @tc.steps:step3. Check extend_field + * @tc.expected: step3. Return E_OK. + */ + std::string checkValidJsonSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_valid(extend_field) = 1"; + EXPECT_EQ(sqlite3_exec(g_db, checkValidJsonSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(num), nullptr), SQLITE_OK); + + std::string checkAgeSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_extract(extend_field, '$.age') = 18"; + EXPECT_EQ(sqlite3_exec(g_db, checkAgeSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(num / 2), nullptr), SQLITE_OK); + checkAgeSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_extract(extend_field, '$.age') = 'old_age'"; + EXPECT_EQ(sqlite3_exec(g_db, checkAgeSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(num / 2), nullptr), SQLITE_OK); + + checkAgeSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_extract(extend_field, '$.name') is null"; + EXPECT_EQ(sqlite3_exec(g_db, checkAgeSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(num / 2), nullptr), SQLITE_OK); + for (uint64_t i = 0; i < num; i += 2) { + std::string expectName = "Local" + std::to_string(i); + std::string checkNameSql = "select count(*) from " + DBCommon::GetLogTableName(TABLE_NAME2) + + " where json_extract(extend_field, '$.name') = 'Local" + std::to_string(i) + "'"; + EXPECT_EQ(sqlite3_exec(g_db, checkNameSql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, + reinterpret_cast(1u), nullptr), SQLITE_OK); + } + CloseStore(); +} + /** * @tc.name: SchemaStrTest001 * @tc.desc: Test open reOpen stroe when schemaStr is empty @@ -2155,4 +2333,4 @@ HWTEST_F(DistributedDBInterfacesRelationalTrackerTableTest, SchemaStrTest001, Te EXPECT_EQ(g_delegate->SetTrackerTable(schema), OK); CloseStore(); } -} \ No newline at end of file +} diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_assets_operation_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_assets_operation_sync_test.cpp index 4e2186564e1524f9004cd6f08c80990ee1e4fe11..2de7c1e36118e5d05e6d65171b771be6e0abf585 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_assets_operation_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_assets_operation_sync_test.cpp @@ -128,7 +128,7 @@ protected: std::string tableName_ = "DistributedDBCloudAssetsOperationSyncTest"; VirtualCommunicatorAggregator *communicatorAggregator_ = nullptr; TrackerSchema trackerSchema = { - .tableName = tableName_, .extendColName = "name", .trackerColNames = {"age"} + .tableName = tableName_, .extendColNames = {"name"}, .trackerColNames = {"age"} }; }; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_assets_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_assets_test.cpp index 95d6edf7c7f226944d56fe4e0400c14419c98907..b1b5e974660c0a32f4ab420d0df21e7e423d6d3d 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_assets_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_assets_test.cpp @@ -397,12 +397,12 @@ void CheckCompensatedCount(sqlite3 *db, int64_t expectCount) void CloseDb() { - delete g_observer; - g_virtualCloudDb = nullptr; if (g_delegate != nullptr) { EXPECT_EQ(g_mgr.CloseStore(g_delegate), DBStatus::OK); g_delegate = nullptr; } + delete g_observer; + g_virtualCloudDb = nullptr; } class DistributedDBCloudSyncerDownloadAssetsTest : public testing::Test { diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_lock_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_lock_test.cpp index cfbcaca117b009a68cea5619a2e3a177677c2a58..c6e9694d21eae77b28788168d3c0677d499e7ab9 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_lock_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_lock_test.cpp @@ -945,7 +945,7 @@ HWTEST_F(DistributedDBCloudSyncerLockTest, QueryCursorTest004, TestSize.Level0) */ g_virtualCloudDb->ForkQuery([](const std::string &table, VBucket &) { TrackerSchema schema = { - .tableName = ASSETS_TABLE_NAME, .extendColName = COL_NAME, .trackerColNames = { COL_ID } + .tableName = ASSETS_TABLE_NAME, .extendColNames = {COL_NAME}, .trackerColNames = { COL_ID } }; EXPECT_EQ(g_delegate->SetTrackerTable(schema), WITH_INVENTORY_DATA); }); @@ -957,7 +957,7 @@ HWTEST_F(DistributedDBCloudSyncerLockTest, QueryCursorTest004, TestSize.Level0) * @tc.expected: step3. return ok. */ std::string sql = "select count(*) from " + DBCommon::GetLogTableName(ASSETS_TABLE_NAME) + - " where data_key='0' and extend_field='name10' and cursor='32';"; + " where data_key='0' and json_extract(extend_field, '$.name')='name10' and cursor='32';"; EXPECT_EQ(sqlite3_exec(db, sql.c_str(), CloudDBSyncUtilsTest::QueryCountCallback, reinterpret_cast(1), nullptr), SQLITE_OK); } diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_table_without_primary_key_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_table_without_primary_key_sync_test.cpp index d0e8f9db2b295076a3a0e396afa316ed1b89a9fd..182f342b98b9ca632715dda9aa1930641fde1353 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_table_without_primary_key_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_table_without_primary_key_sync_test.cpp @@ -52,13 +52,13 @@ namespace { RelationalStoreDelegate *g_delegate = nullptr; VirtualCommunicatorAggregator *communicatorAggregator_ = nullptr; TrackerSchema g_trackerSchema = { - .tableName = g_tableName, .extendColName = "name", .trackerColNames = {"age"} + .tableName = g_tableName, .extendColNames = {"name"}, .trackerColNames = {"age"} }; TrackerSchema g_trackerSchema2 = { - .tableName = g_tableName, .extendColName = "age", .trackerColNames = {"height"} + .tableName = g_tableName, .extendColNames = {"age"}, .trackerColNames = {"height"} }; TrackerSchema g_trackerSchema3 = { - .tableName = g_tableName, .extendColName = "", .trackerColNames = {} + .tableName = g_tableName, .extendColNames = {}, .trackerColNames = {} }; ChangeProperties g_onChangeProperties = { .isTrackedDataChange = true }; ChangeProperties g_unChangeProperties = { .isTrackedDataChange = false }; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_auto_launch.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_auto_launch.h index 1c95719f74ac5c523912ac5a3677c6198e5c37f7..dd981f8cf2616534728d1c0a27c35968e8486829 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_auto_launch.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_auto_launch.h @@ -18,13 +18,16 @@ #include #include "auto_launch.h" +#include "concurrent_adapter.h" +#include "res_finalizer.h" namespace DistributedDB { class MockAutoLaunch : public AutoLaunch { public: void SetAutoLaunchItem(const std::string &identify, const std::string &userId, const AutoLaunchItem &item) { - std::lock_guard autoLock(extLock_); + ConcurrentAdapter::AdapterAutoLock(extLock_); + ResFinalizer finalizer([this]() { ConcurrentAdapter::AdapterAutoUnLock(extLock_); }); extItemMap_[identify][userId] = item; } diff --git a/mock/innerkits/os_account/libaccountkits/include/ohos_account_kits.h b/mock/innerkits/os_account/libaccountkits/include/ohos_account_kits.h index 0922f8475126bdb0a9832c1861dd5ab53fa1a7d0..ad8985b160f4187688dababa6ae6e2f7691ce381 100644 --- a/mock/innerkits/os_account/libaccountkits/include/ohos_account_kits.h +++ b/mock/innerkits/os_account/libaccountkits/include/ohos_account_kits.h @@ -65,7 +65,9 @@ public: */ virtual std::pair QueryOhosAccountInfo() = 0; - /** + virtual int32_t GetOsAccountDistributedInfo(int32_t localId, OhosAccountInfo &accountInfo) = 0; + + /** * Query OHOS Account Info. * * @param OhosAccountInfo. ohos account info diff --git a/mock/src/mock_account.cpp b/mock/src/mock_account.cpp index 89c8f8cbd7d58cf6ad133f971112c19814f141c6..34b258bb61098e28c1e7ec4a7707ea44c11eac79 100644 --- a/mock/src/mock_account.cpp +++ b/mock/src/mock_account.cpp @@ -23,7 +23,10 @@ public: const std::string& eventStr) override; int32_t QueryDeviceAccountId(std::int32_t &accountId) override; int32_t GetDeviceAccountIdByUID(int32_t& uid) override; + int32_t GetOhosAccountInfoByUserId(int32_t userId, OhosAccountInfo &accountInfo) override; + + int32_t GetOsAccountDistributedInfo(int32_t localId, OhosAccountInfo &accountInfo) override; std::pair QueryOhosAccountInfoByUserId(std::int32_t userId) override; ~OhosAccountKitsImpl() override = default; int32_t GetOhosAccountInfo(OhosAccountInfo &accountInfo) override; @@ -106,4 +109,8 @@ int32_t OhosAccountKitsImpl::GetOhosAccountInfoByUserId(int32_t userId, OhosAcco { return 0; } +int32_t OhosAccountKitsImpl::GetOsAccountDistributedInfo(int32_t localId, OhosAccountInfo &accountInfo) +{ + return 0; +} } // namespace OHOS::AccountSA diff --git a/mock/src/mock_notification.cpp b/mock/src/mock_notification.cpp index 1c93e25623e383931fd391759a965867cb4ac97b..5cbcc7c0dc2c778c36be4b95dfa3cee2f2b5a578 100644 --- a/mock/src/mock_notification.cpp +++ b/mock/src/mock_notification.cpp @@ -297,6 +297,7 @@ CommonEventSubscriber::CommonEventSubscriber() {} CommonEventSubscriber::CommonEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo) {} CommonEventSubscriber::~CommonEventSubscriber() {} const std::string CommonEventSupport::COMMON_EVENT_USER_REMOVED = "COMMON_EVENT_USER_REMOVED"; +const std::string CommonEventSupport::COMMON_EVENT_USER_STARTING = "COMMON_EVENT_USER_STARTING"; const std::string CommonEventSupport::COMMON_EVENT_USER_UNLOCKED = "COMMON_EVENT_USER_UNLOCKED"; const std::string CommonEventSupport::COMMON_EVENT_USER_STOPPING = "COMMON_EVENT_USER_STOPPING"; const std::string CommonEventSupport::COMMON_EVENT_USER_STOPPED = "COMMON_EVENT_USER_STOPPED"; diff --git a/relational_store/frameworks/js/napi/cloud_data/include/js_cloud_utils.h b/relational_store/frameworks/js/napi/cloud_data/include/js_cloud_utils.h index 5ca64e63eccdcd2e838d5ce66bff1972fc9e3ca8..ca8651c4660cab49c7510e5f14ac840c8b2ab610 100644 --- a/relational_store/frameworks/js/napi/cloud_data/include/js_cloud_utils.h +++ b/relational_store/frameworks/js/napi/cloud_data/include/js_cloud_utils.h @@ -15,12 +15,12 @@ #ifndef CLOUD_DATA_JS_CLOUD_UTILS_H #define CLOUD_DATA_JS_CLOUD_UTILS_H -#include "js_utils.h" #include "cloud_types.h" #include "common_types.h" +#include "js_config.h" +#include "js_utils.h" #include "rdb_predicates.h" #include "result_set.h" -#include "js_config.h" namespace OHOS::AppDataMgrJsKit { namespace JSUtils { diff --git a/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h b/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h index b2cb6d13911222ad438d5843a82f109daf5e9f04..79e680741427641f9405ce161f50f805cb753745 100644 --- a/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h +++ b/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h @@ -55,13 +55,13 @@ napi_value GenerateErrorMsg(napi_env env, JsErrorCode jsInfo); } \ } while (0) -#define ASSERT_PERMISSION_ERR(ctxt, assertion, errorCode, message) \ - do { \ - if (!(assertion)) { \ - (ctxt)->isThrowError = true; \ - ThrowNapiError((ctxt)->env, errorCode, message); \ - return; \ - } \ +#define ASSERT_PERMISSION_ERR(ctxt, assertion, errorCode, message) \ + do { \ + if (!(assertion)) { \ + (ctxt)->isThrowError = true; \ + ThrowNapiError((ctxt)->env, errorCode, message); \ + return; \ + } \ } while (0) } // namespace CloudData diff --git a/relational_store/frameworks/js/napi/cloud_data/include/js_strategy_context.h b/relational_store/frameworks/js/napi/cloud_data/include/js_strategy_context.h index e3340aab17b9fcbe6152f91d961800a97f661a6a..79c3d616605e30935929ca585c498c5430e766d4 100644 --- a/relational_store/frameworks/js/napi/cloud_data/include/js_strategy_context.h +++ b/relational_store/frameworks/js/napi/cloud_data/include/js_strategy_context.h @@ -75,6 +75,6 @@ private: return true; } }; -} -} +} // namespace CloudData +} // namespace OHOS #endif //CLOUD_DATA_JS_STRATEGY_CONTEXT_H diff --git a/relational_store/frameworks/js/napi/cloud_data/src/entry_point.cpp b/relational_store/frameworks/js/napi/cloud_data/src/entry_point.cpp index 86f388a2ff6aac042b036c72b66dc5dfd0c0fbc4..ab267123fb7a7d18a4abba8df2114b2e6476e14e 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/entry_point.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/entry_point.cpp @@ -14,10 +14,10 @@ */ #define LOG_TAG "RegisterCloudDataModule" #include "js_client.h" +#include "js_cloud_share.h" #include "js_config.h" #include "js_const_properties.h" #include "logger.h" -#include "js_cloud_share.h" using namespace OHOS::CloudData; using namespace OHOS::Rdb; diff --git a/relational_store/frameworks/js/napi/cloud_data/src/js_client.cpp b/relational_store/frameworks/js/napi/cloud_data/src/js_client.cpp index 6e13d70619ad2fc2ec69f2d07520fb7dd85f046a..c123d653c7a18531d5694044759cc2ef1c13ba55 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/js_client.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/js_client.cpp @@ -18,6 +18,7 @@ #include #include #include + #include "cloud_types.h" #include "common_types.h" #include "js_cloud_utils.h" @@ -80,9 +81,7 @@ napi_value SetCloudStrategy(napi_env env, napi_callback_info info) napi_value InitClient(napi_env env, napi_value exports) { - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("setCloudStrategy", SetCloudStrategy) - }; + napi_property_descriptor properties[] = { DECLARE_NAPI_FUNCTION("setCloudStrategy", SetCloudStrategy) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(properties) / sizeof(*properties), properties)); return exports; } diff --git a/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_share.cpp b/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_share.cpp index 90813a3cd110ab7c3752d2c7487152c8c7fb3648..3d2f79d2f7209214da5a2c33fa18bda60c547467 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_share.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_share.cpp @@ -94,7 +94,7 @@ napi_value AllocResourceAndShare(napi_env env, napi_callback_info info) ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->resultSet); ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; @@ -122,11 +122,11 @@ napi_value Share(napi_env env, napi_callback_info info) // ShareContext have sharingRes, participants 2 required parameter ASSERT_BUSINESS_ERR(ctxt, argc >= 2, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->sharingRes); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), - Status::INVALID_ARGUMENT, "The type of sharingRes must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), Status::INVALID_ARGUMENT, + "The type of sharingRes must be string and not empty."); status = JSUtils::Convert2Value(env, argv[1], ctxt->participants); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->participants.empty(), - Status::INVALID_ARGUMENT, "The type of participants must be Array and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->participants.empty(), Status::INVALID_ARGUMENT, + "The type of participants must be Array and not empty."); }); ASSERT_NULL(!ctxt->isThrowError, "share exit"); @@ -142,12 +142,12 @@ napi_value Share(napi_env env, napi_callback_info info) } int32_t result = proxy->Share(ctxt->sharingRes, ctxt->participants, ctxt->results); LOG_DEBUG("share result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->results); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -173,11 +173,11 @@ napi_value Unshare(napi_env env, napi_callback_info info) // ShareContext have sharingRes, participants 2 required parameter ASSERT_BUSINESS_ERR(ctxt, argc >= 2, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->sharingRes); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), - Status::INVALID_ARGUMENT, "The type of sharingRes must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), Status::INVALID_ARGUMENT, + "The type of sharingRes must be string and not empty."); status = JSUtils::Convert2Value(env, argv[1], ctxt->participants); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->participants.empty(), - Status::INVALID_ARGUMENT, "The type of participants must be Array and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->participants.empty(), Status::INVALID_ARGUMENT, + "The type of participants must be Array and not empty."); }); ASSERT_NULL(!ctxt->isThrowError, "unShare exit"); auto execute = [env, ctxt]() { @@ -192,12 +192,12 @@ napi_value Unshare(napi_env env, napi_callback_info info) } int32_t result = proxy->Unshare(ctxt->sharingRes, ctxt->participants, ctxt->results); LOG_DEBUG("unshare result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->results); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -220,8 +220,8 @@ napi_value Exit(napi_env env, napi_callback_info info) ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value *argv) { ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->sharingRes); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), - Status::INVALID_ARGUMENT, "The type of sharingRes must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), Status::INVALID_ARGUMENT, + "The type of sharingRes must be string and not empty."); }); ASSERT_NULL(!ctxt->isThrowError, "exit exit"); auto execute = [env, ctxt]() { @@ -236,12 +236,12 @@ napi_value Exit(napi_env env, napi_callback_info info) } int32_t result = proxy->Exit(ctxt->sharingRes, ctxt->result); LOG_DEBUG("exit sharing result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->result); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -269,11 +269,11 @@ napi_value ChangePrivilege(napi_env env, napi_callback_info info) // ShareContext have sharingRes, participants 2 required parameter ASSERT_BUSINESS_ERR(ctxt, argc >= 2, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->sharingRes); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), - Status::INVALID_ARGUMENT, "The type of sharingRes must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), Status::INVALID_ARGUMENT, + "The type of sharingRes must be string and not empty."); status = JSUtils::Convert2Value(env, argv[1], ctxt->participants); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->participants.empty(), - Status::INVALID_ARGUMENT, "The type of participants must be Array and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->participants.empty(), Status::INVALID_ARGUMENT, + "The type of participants must be Array and not empty."); }); ASSERT_NULL(!ctxt->isThrowError, "changePrivilege exit"); auto execute = [env, ctxt]() { @@ -288,12 +288,12 @@ napi_value ChangePrivilege(napi_env env, napi_callback_info info) } int32_t result = proxy->ChangePrivilege(ctxt->sharingRes, ctxt->participants, ctxt->results); LOG_DEBUG("change privilege result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->results); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -316,8 +316,8 @@ napi_value Query(napi_env env, napi_callback_info info) ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value *argv) { ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->sharingRes); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), - Status::INVALID_ARGUMENT, "The type of sharingRes must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), Status::INVALID_ARGUMENT, + "The type of sharingRes must be string and not empty."); }); ASSERT_NULL(!ctxt->isThrowError, "query exit"); auto execute = [env, ctxt]() { @@ -332,12 +332,12 @@ napi_value Query(napi_env env, napi_callback_info info) } int32_t result = proxy->Query(ctxt->sharingRes, ctxt->results); LOG_DEBUG("query participants result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->results); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -361,8 +361,8 @@ napi_value QueryByInvitation(napi_env env, napi_callback_info info) ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value *argv) { ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->invitationCode); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->invitationCode.empty(), - Status::INVALID_ARGUMENT, "The type of invitationCode must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->invitationCode.empty(), Status::INVALID_ARGUMENT, + "The type of invitationCode must be string and not empty."); }); ASSERT_NULL(!ctxt->isThrowError, "queryByInvitation exit"); auto execute = [env, ctxt]() { @@ -377,12 +377,12 @@ napi_value QueryByInvitation(napi_env env, napi_callback_info info) } int32_t result = proxy->QueryByInvitation(ctxt->invitationCode, ctxt->results); LOG_DEBUG("query participants by invitation result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->results); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -407,12 +407,12 @@ napi_value ConfirmInvitation(napi_env env, napi_callback_info info) // ShareContext have sharingRes, participants 2 required parameter ASSERT_BUSINESS_ERR(ctxt, argc >= 2, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->invitationCode); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->invitationCode.empty(), - Status::INVALID_ARGUMENT, "The type of invitationCode must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->invitationCode.empty(), Status::INVALID_ARGUMENT, + "The type of invitationCode must be string and not empty."); int32_t confirmation; status = JSUtils::Convert2ValueExt(env, argv[1], confirmation); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && - confirmation > Confirmation::CFM_NIL && confirmation <= Confirmation::CFM_BUTT, + ASSERT_BUSINESS_ERR(ctxt, + status == JSUtils::OK && confirmation > Confirmation::CFM_NIL && confirmation <= Confirmation::CFM_BUTT, Status::INVALID_ARGUMENT, "The type of status must be Status."); ctxt->confirmation = confirmation; }); @@ -429,12 +429,12 @@ napi_value ConfirmInvitation(napi_env env, napi_callback_info info) } int32_t result = proxy->ConfirmInvitation(ctxt->invitationCode, ctxt->confirmation, ctxt->result); LOG_DEBUG("confirm invitation result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->result); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -459,12 +459,12 @@ napi_value ChangeConfirmation(napi_env env, napi_callback_info info) // ShareContext have sharingRes, participants 2 required parameter ASSERT_BUSINESS_ERR(ctxt, argc >= 2, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int status = JSUtils::Convert2Value(env, argv[0], ctxt->sharingRes); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), - Status::INVALID_ARGUMENT, "The type of sharingRes must be string and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && !ctxt->sharingRes.empty(), Status::INVALID_ARGUMENT, + "The type of sharingRes must be string and not empty."); int32_t confirmation; status = JSUtils::Convert2ValueExt(env, argv[1], confirmation); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && - confirmation > Confirmation::CFM_NIL && confirmation < Confirmation::CFM_BUTT, + ASSERT_BUSINESS_ERR(ctxt, + status == JSUtils::OK && confirmation > Confirmation::CFM_NIL && confirmation < Confirmation::CFM_BUTT, Status::INVALID_ARGUMENT, "The type of status must be Status."); ctxt->confirmation = confirmation; }); @@ -481,12 +481,12 @@ napi_value ChangeConfirmation(napi_env env, napi_callback_info info) } int32_t result = proxy->ChangeConfirmation(ctxt->sharingRes, ctxt->confirmation, ctxt->results); LOG_DEBUG("change confirmation result %{public}d", result); - ctxt->status = (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? - napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(result, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->results); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -513,4 +513,4 @@ napi_value InitCloudSharing(napi_env env, napi_value exports) NAPI_CALL(env, napi_set_named_property(env, exports, "sharing", sharing)); return sharing; } -} // namespace OHOS::CloudData \ No newline at end of file +} // namespace OHOS::CloudData diff --git a/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_utils.cpp b/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_utils.cpp index db040f2984d2c0cc9362f04b41c51e45d56c16d6..6d169485b28117f1044a20bc4d8c6142203b7dde 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_utils.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/js_cloud_utils.cpp @@ -14,10 +14,11 @@ */ #define LOG_TAG "JSCloudUtils" #include "js_cloud_utils.h" + #include "js_proxy.h" +#include "logger.h" #include "result_set.h" #include "result_set_bridge.h" -#include "logger.h" #define NAPI_CALL_RETURN_ERR(call, ret) \ ASSERT_RETURN((call) == napi_ok, ret) @@ -63,8 +64,7 @@ int32_t Convert2Value(napi_env env, napi_value input, Participant &output) return napi_invalid_arg; } NAPI_CALL_RETURN_ERR(GetNamedProperty(env, input, "state", output.state, true), napi_invalid_arg); - if (output.state < CloudData::Confirmation::CFM_NIL || - output.state >= CloudData::Confirmation::CFM_BUTT) { + if (output.state < CloudData::Confirmation::CFM_NIL || output.state >= CloudData::Confirmation::CFM_BUTT) { return napi_invalid_arg; } NAPI_CALL_RETURN_ERR(GetNamedProperty(env, input, "privilege", output.privilege, true), napi_invalid_arg); @@ -269,4 +269,4 @@ napi_value Convert2JSValue(napi_env env, const CloudSyncInfo &value) return jsValue; } }; // namespace JSUtils -} // namespace OHOS::AppDataMgrJsKit \ No newline at end of file +} // namespace OHOS::AppDataMgrJsKit diff --git a/relational_store/frameworks/js/napi/cloud_data/src/js_config.cpp b/relational_store/frameworks/js/napi/cloud_data/src/js_config.cpp index 31a5fe07f4801883df87ef4c317e7bb2b95e7377..c09939d6b5e9bc5ef8964c477c6bf87d8365bf45 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/js_config.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/js_config.cpp @@ -20,13 +20,13 @@ #include "cloud_manager.h" #include "cloud_service.h" -#include "js_error_utils.h" -#include "js_utils.h" #include "js_cloud_utils.h" +#include "js_df_manager.h" +#include "js_error_utils.h" #include "js_strategy_context.h" +#include "js_utils.h" #include "logger.h" #include "napi_queue.h" -#include "js_df_manager.h" using namespace OHOS::Rdb; using namespace OHOS::CloudData; @@ -280,12 +280,12 @@ napi_value JsConfig::NotifyDataChange(napi_env env, napi_callback_info info) "The type of bundleName must be string and not empty."); } else { int status = JSUtils::Convert2Value(env, argv[0], ctxt->extInfo); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && VerifyExtraData(ctxt->extInfo), Status::INVALID_ARGUMENT, - "The type of extInfo must be Extradata and not empty."); + ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && VerifyExtraData(ctxt->extInfo), + Status::INVALID_ARGUMENT, "The type of extInfo must be Extradata and not empty."); if (argc > 1) { status = JSUtils::Convert2ValueExt(env, argv[1], ctxt->userId); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK, Status::INVALID_ARGUMENT, - "The type of user must be number."); + ASSERT_BUSINESS_ERR( + ctxt, status == JSUtils::OK, Status::INVALID_ARGUMENT, "The type of user must be number."); } ctxt->notifyStatus = true; } @@ -303,15 +303,15 @@ napi_value JsConfig::NotifyDataChange(napi_env env, napi_callback_info info) ? napi_ok : napi_generic_failure; return; } - int32_t status ; + int32_t status; if (ctxt->notifyStatus == true) { status = proxy->NotifyDataChange(ctxt->extInfo.eventId, ctxt->extInfo.extraData, ctxt->userId); } else { status = proxy->NotifyDataChange(ctxt->accountId, ctxt->bundleName); } LOG_DEBUG("NotifyDataChange return %{public}d", status); - ctxt->status = (GenerateNapiError(status, ctxt->jsCode, ctxt->error) == Status::SUCCESS) - ? napi_ok : napi_generic_failure; + ctxt->status = + (GenerateNapiError(status, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; if (status == Status::INVALID_ARGUMENT) { ctxt->error += "The parameter required is a valid value."; } @@ -334,7 +334,7 @@ napi_value JsConfig::QueryStatistics(napi_env env, napi_callback_info info) std::map result; }; auto ctxt = std::make_shared(); - ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value* argv) { + ctxt->GetCbInfo(env, info, [env, ctxt](size_t argc, napi_value *argv) { // required 2 arguments :: ASSERT_BUSINESS_ERR(ctxt, argc >= 2, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); // 0 is the index of argument accountId @@ -349,8 +349,8 @@ napi_value JsConfig::QueryStatistics(napi_env env, napi_callback_info info) if (argc > 2 && !JSUtils::IsNull(ctxt->env, argv[2])) { // 2 is the index of argument storeId status = JSUtils::Convert2Value(env, argv[2], ctxt->storeId); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK, Status::INVALID_ARGUMENT, - "The type of storeId must be string."); + ASSERT_BUSINESS_ERR( + ctxt, status == JSUtils::OK, Status::INVALID_ARGUMENT, "The type of storeId must be string."); } }); @@ -372,9 +372,9 @@ napi_value JsConfig::QueryStatistics(napi_env env, napi_callback_info info) (GenerateNapiError(status, ctxt->jsCode, ctxt->error) == Status::SUCCESS) ? napi_ok : napi_generic_failure; ctxt->result = std::move(result); }; - auto output = [env, ctxt](napi_value& result) { + auto output = [env, ctxt](napi_value &result) { result = JSUtils::Convert2JSValue(env, ctxt->result); - ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); + ASSERT_VALUE(ctxt, result != nullptr, napi_generic_failure, "output failed"); }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); } @@ -387,9 +387,9 @@ napi_value JsConfig::SetGlobalCloudStrategy(napi_env env, napi_callback_info inf ASSERT_BUSINESS_ERR(ctxt, argc >= 1, Status::INVALID_ARGUMENT, "The number of parameters is incorrect."); int32_t strategy = -1; int status = JSUtils::Convert2ValueExt(env, argv[0], strategy); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK && strategy >= 0 && - strategy < static_cast(Strategy::STRATEGY_BUTT), Status::INVALID_ARGUMENT, - "The type of strategy must be StrategyType."); + ASSERT_BUSINESS_ERR(ctxt, + status == JSUtils::OK && strategy >= 0 && strategy < static_cast(Strategy::STRATEGY_BUTT), + Status::INVALID_ARGUMENT, "The type of strategy must be StrategyType."); ctxt->strategy = static_cast(strategy); // 'argv[1]' represents a vector param or null if (argc == 1 || JSUtils::IsNull(env, argv[1])) { @@ -480,8 +480,8 @@ napi_value JsConfig::QueryLastSyncInfo(napi_env env, napi_callback_info info) if (argc > 2 && !JSUtils::IsNull(ctxt->env, argv[2])) { // 2 is the index of argument storeId status = JSUtils::Convert2Value(env, argv[2], ctxt->storeId); - ASSERT_BUSINESS_ERR(ctxt, status == JSUtils::OK, Status::INVALID_ARGUMENT, - "The type of storeId must be string."); + ASSERT_BUSINESS_ERR( + ctxt, status == JSUtils::OK, Status::INVALID_ARGUMENT, "The type of storeId must be string."); } }); @@ -529,4 +529,4 @@ napi_value JsConfig::InitConfig(napi_env env, napi_value exports) auto jsCtor = JSUtils::DefineClass(env, "ohos.data.cloudData", "Config", lambda, JsConfig::New); NAPI_CALL(env, napi_set_named_property(env, exports, "Config", jsCtor)); return exports; -} \ No newline at end of file +} diff --git a/relational_store/frameworks/js/napi/cloud_data/src/js_const_properties.cpp b/relational_store/frameworks/js/napi/cloud_data/src/js_const_properties.cpp index 83f02d15b1b639ebfa109c5ad58b654ebc95cf3b..4924b18bf6b0ed518830ef5e961313fc4e596c10 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/js_const_properties.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/js_const_properties.cpp @@ -17,8 +17,8 @@ #include "cloud_service.h" #include "cloud_types.h" -#include "napi_queue.h" #include "js_utils.h" +#include "napi_queue.h" using namespace OHOS::Rdb; using Action = OHOS::CloudData::CloudService::Action; @@ -113,8 +113,8 @@ napi_status InitConstProperties(napi_env env, napi_value exports) const napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("Action", ExportAction(env)), DECLARE_NAPI_PROPERTY("ClearAction", ExportAction(env)), - DECLARE_NAPI_PROPERTY("DATA_CHANGE_EVENT_ID", AppDataMgrJsKit::JSUtils::Convert2JSValue(env, - std::string(CloudData::DATA_CHANGE_EVENT_ID))), + DECLARE_NAPI_PROPERTY("DATA_CHANGE_EVENT_ID", + AppDataMgrJsKit::JSUtils::Convert2JSValue(env, std::string(CloudData::DATA_CHANGE_EVENT_ID))), }; size_t count = sizeof(properties) / sizeof(properties[0]); diff --git a/relational_store/frameworks/js/napi/cloud_data/src/js_error_utils.cpp b/relational_store/frameworks/js/napi/cloud_data/src/js_error_utils.cpp index b2de441870fb0e8a52c1cf69b1f1abdbba0b59bc..5445becc611319238fd5589690b5bb7dea98744e 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/js_error_utils.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/js_error_utils.cpp @@ -38,8 +38,8 @@ const std::optional GetJsErrorCode(int32_t errorCode) [](const JsErrorCode &jsErrorCode1, const JsErrorCode &jsErrorCode2) { return jsErrorCode1.status < jsErrorCode2.status; }); - if (iter < JS_ERROR_CODE_MSGS + sizeof(JS_ERROR_CODE_MSGS) / sizeof(JS_ERROR_CODE_MSGS[0]) - && iter->status == errorCode) { + if (iter < JS_ERROR_CODE_MSGS + sizeof(JS_ERROR_CODE_MSGS) / sizeof(JS_ERROR_CODE_MSGS[0]) && + iter->status == errorCode) { return *iter; } return std::nullopt; diff --git a/relational_store/frameworks/js/napi/cloud_data/src/napi_queue.cpp b/relational_store/frameworks/js/napi/cloud_data/src/napi_queue.cpp index 0d031116a1075653a011e790043e0d64c72bc302..27d681c42cf4deee6fe2ae18d7431d22cc636188 100644 --- a/relational_store/frameworks/js/napi/cloud_data/src/napi_queue.cpp +++ b/relational_store/frameworks/js/napi/cloud_data/src/napi_queue.cpp @@ -110,8 +110,8 @@ napi_value NapiQueue::AsyncWork(napi_env env, std::shared_ptr ctxt, ASSERT_VOID(data != nullptr, "napi_async_complete_callback nullptr"); auto actx = static_cast(data); ASSERT_VOID(actx->ctx != nullptr, "napi_async_complete_callback nullptr"); - LOG_DEBUG("napi_async_complete_callback status=%{public}d, ctxt->status=%{public}d", - status, actx->ctx->status); + LOG_DEBUG( + "napi_async_complete_callback status=%{public}d, ctxt->status=%{public}d", status, actx->ctx->status); if ((status != napi_ok) && (actx->ctx->status == napi_ok)) { actx->ctx->status = status; } diff --git a/relational_store/frameworks/js/napi/cloud_extension/cloud_extension.cpp b/relational_store/frameworks/js/napi/cloud_extension/cloud_extension.cpp index 8da423c758b7b734e76f2cde54c95508ad91f35c..5c1d2a4378b544b22bfb356ed3fb69730183963a 100644 --- a/relational_store/frameworks/js/napi/cloud_extension/cloud_extension.cpp +++ b/relational_store/frameworks/js/napi/cloud_extension/cloud_extension.cpp @@ -13,10 +13,9 @@ * limitations under the License. */ -#include "native_engine/native_engine.h" - #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "native_engine/native_engine.h" extern const char _binary_cloud_extension_abc_start[]; extern const char _binary_cloud_extension_abc_end[]; @@ -40,7 +39,7 @@ static __attribute__((constructor)) void CloudExtensionRegisterModule(void) .nm_flags = 0, .nm_filename = nullptr, .nm_modname = "data.cloudExtension", - .nm_priv = ((void*)0), + .nm_priv = ((void *)0), .reserved = { 0 }, }; napi_module_register(&cloudExtensionModule); diff --git a/relational_store/frameworks/js/napi/common/include/js_ability.h b/relational_store/frameworks/js/napi/common/include/js_ability.h index 86ce41de3589abdf00d2686a549616aa6ac6cd26..3e3ae36fe042a80ae0738f910e0cb6b12e385a14 100644 --- a/relational_store/frameworks/js/napi/common/include/js_ability.h +++ b/relational_store/frameworks/js/napi/common/include/js_ability.h @@ -18,8 +18,8 @@ #include #include -#include "napi/native_api.h" #include "ability.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" #include "napi_base_context.h" diff --git a/relational_store/frameworks/js/napi/common/include/js_df_manager.h b/relational_store/frameworks/js/napi/common/include/js_df_manager.h index e30fc60b57697564519575c4de9acddcb5ad7e4c..a401bdd463e7d08967b79f89340cc3fc9fb4cfdf 100644 --- a/relational_store/frameworks/js/napi/common/include/js_df_manager.h +++ b/relational_store/frameworks/js/napi/common/include/js_df_manager.h @@ -16,6 +16,7 @@ #ifndef OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_JS_NAPI_COMMON_JSUAF_MANAGER_H #define OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_JS_NAPI_COMMON_JSUAF_MANAGER_H #include + #include #include namespace OHOS::AppDataMgrJsKit { @@ -29,7 +30,7 @@ private: std::map instances_; std::mutex mapMutex; }; -} +} // namespace OHOS::AppDataMgrJsKit -constexpr auto LOWER_24_BITS_MASK = (1u << 24) - 1; +constexpr auto LOWER_24_BITS_MASK = (1u << 24) - 1; #endif // OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_JS_NAPI_COMMON_JSUAF_MANAGER_H diff --git a/relational_store/frameworks/js/napi/common/include/js_scope.h b/relational_store/frameworks/js/napi/common/include/js_scope.h index c0579207e6585b6804d191c2a3d6bfd2fb78a4ea..64c912846326e1be84109f71af08f6fd66daa7f8 100644 --- a/relational_store/frameworks/js/napi/common/include/js_scope.h +++ b/relational_store/frameworks/js/napi/common/include/js_scope.h @@ -23,9 +23,10 @@ class Scope { public: Scope(napi_env env); ~Scope(); + private: napi_env env_ = nullptr; napi_handle_scope scope_ = nullptr; }; -} +} // namespace OHOS::AppDataMgrJsKit #endif // DISTRIBUTEDDATAMGR_APPDATAMGR_SCOPE_H diff --git a/relational_store/frameworks/js/napi/common/include/js_uv_queue.h b/relational_store/frameworks/js/napi/common/include/js_uv_queue.h index 0da19cf850723d4196e651ef8cd673a2b04cbe74..c99ff5ca8b8bcc6d33413ab95b249728737d5be4 100644 --- a/relational_store/frameworks/js/napi/common/include/js_uv_queue.h +++ b/relational_store/frameworks/js/napi/common/include/js_uv_queue.h @@ -15,6 +15,7 @@ #ifndef DISTRIBUTEDDATAMGR_APPDATAMGR_UV_QUEUE_H #define DISTRIBUTEDDATAMGR_APPDATAMGR_UV_QUEUE_H #include + #include "event_handler.h" #include "napi/native_api.h" #include "napi/native_common.h" diff --git a/relational_store/frameworks/js/napi/common/mock/include/event_handler.h b/relational_store/frameworks/js/napi/common/mock/include/event_handler.h index 7b4c425a57493503d84b3b67dfe362e5c8dbf27f..c02769ce0cbfb506b7ce00c2a905635c836264f8 100644 --- a/relational_store/frameworks/js/napi/common/mock/include/event_handler.h +++ b/relational_store/frameworks/js/napi/common/mock/include/event_handler.h @@ -15,8 +15,8 @@ #ifndef DISTRIBUTEDDATAMGR_APPDATAMGR_EVENT_HANDLER_H #define DISTRIBUTEDDATAMGR_APPDATAMGR_EVENT_HANDLER_H -#include #include +#include namespace OHOS { namespace AppExecFwk { using Callback = std::function; @@ -32,6 +32,6 @@ public: return false; } }; -} -} // namespace OHOS::AppDataMgrJsKit +} // namespace AppExecFwk +} // namespace OHOS #endif // DISTRIBUTEDDATAMGR_APPDATAMGR_EVENT_HANDLER_H diff --git a/relational_store/frameworks/js/napi/common/mock/src/js_ability.cpp b/relational_store/frameworks/js/napi/common/mock/src/js_ability.cpp index 29f63a2ef50fe8aaa3ed9f2a10cb02964d376499..069015e2120fe09f2c48dd9acd62bb98688f96c2 100644 --- a/relational_store/frameworks/js/napi/common/mock/src/js_ability.cpp +++ b/relational_store/frameworks/js/napi/common/mock/src/js_ability.cpp @@ -14,10 +14,10 @@ */ #define LOG_TAG "JSAbility" #include "js_ability.h" -#include "js_utils.h" #include +#include "js_utils.h" #include "logger.h" #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) #include "napi_base_context.h" @@ -106,7 +106,6 @@ std::shared_ptr JSAbility::GetContext(napi_env env, napi_value value) return GetStageModeContext(env, value); } - std::shared_ptr JSAbility::GetStageModeContext(napi_env env, napi_value value) { #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) @@ -122,14 +121,12 @@ std::shared_ptr JSAbility::GetStageModeContext(napi_env env, napi_value #endif } - std::shared_ptr JSAbility::GetCurrentAbility(napi_env env, napi_value value) { LOG_ERROR("Get context as feature ability mode."); return std::make_shared(); } - bool Context::IsHasProxyDataConfig() const { return hasProxyDataConfig_; diff --git a/relational_store/frameworks/js/napi/common/src/js_ability.cpp b/relational_store/frameworks/js/napi/common/src/js_ability.cpp index d3092338110d0806d2625da02ff10477289e55fc..f39f1cba67c734608236de8e0adcf0221bca389c 100644 --- a/relational_store/frameworks/js/napi/common/src/js_ability.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_ability.cpp @@ -14,9 +14,9 @@ */ #define LOG_TAG "JSAbility" #include "js_ability.h" -#include "js_utils.h" #include "extension_context.h" +#include "js_utils.h" #include "logger.h" #define API_VERSION_MOD 100 diff --git a/relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp b/relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp index 2e613030161b71eb87fce6a74770a955c6019adb..f0a2b26416c04a864b01a44736d7980a3932720a 100644 --- a/relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_common_type_init.cpp @@ -13,13 +13,12 @@ * limitations under the License. */ +#include "common_types.h" #include "napi/native_api.h" #include "napi/native_node_api.h" -#include "common_types.h" namespace OHOS::CommonType { -static napi_status SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, - int32_t value) +static napi_status SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, int32_t value) { napi_value property = nullptr; napi_status status = napi_create_int32(env, value, &property); @@ -43,7 +42,7 @@ static napi_value ExportAssetStatus(napi_env env) napi_object_freeze(env, assetStatus); return assetStatus; } -} +} // namespace OHOS::CommonType static napi_value CommonTypeExport(napi_env env, napi_value exports) { diff --git a/relational_store/frameworks/js/napi/common/src/js_df_manager.cpp b/relational_store/frameworks/js/napi/common/src/js_df_manager.cpp index 5638415bf462506964a97031a1ff9f9327e4c665..37ee17bd144951cf42420badb593ab3c7794f1e6 100644 --- a/relational_store/frameworks/js/napi/common/src/js_df_manager.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_df_manager.cpp @@ -13,11 +13,11 @@ * limitations under the License. */ -#include +#include "js_df_manager.h" #include -#include "js_df_manager.h" +#include namespace OHOS::AppDataMgrJsKit { JSDFManager &JSDFManager::GetInstance() @@ -53,4 +53,4 @@ int32_t JSDFManager::GetFreedTid(void *data) } return freedTid; } -} \ No newline at end of file +} // namespace OHOS::AppDataMgrJsKit \ No newline at end of file diff --git a/relational_store/frameworks/js/napi/common/src/js_utils.cpp b/relational_store/frameworks/js/napi/common/src/js_utils.cpp index 53ecd2d4dee29cb9ed38c40462d0b18cb9b64ba7..a6f761cd245d37bad7244b64657fdfd638d5caf9 100644 --- a/relational_store/frameworks/js/napi/common/src/js_utils.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_utils.cpp @@ -34,7 +34,7 @@ using namespace OHOS::Rdb; namespace OHOS { namespace AppDataMgrJsKit { namespace JSUtils { - static int32_t g_hapVersion = -1; // the current apiVersion of hap +static int32_t g_hapVersion = -1; // the current apiVersion of hap } static constexpr JSUtils::JsFeatureSpace FEATURE_NAME_SPACES[] = { diff --git a/relational_store/frameworks/js/napi/common/src/js_uv_queue.cpp b/relational_store/frameworks/js/napi/common/src/js_uv_queue.cpp index 36b6b9899dd676a5690a703e6f7608d3fd6e42b1..d5c612af4ac720581a0651ba45df1fd72f1b2f1c 100644 --- a/relational_store/frameworks/js/napi/common/src/js_uv_queue.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_uv_queue.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ #define LOG_TAG "UvQueue" +#include "js_uv_queue.h" + #include #include "js_scope.h" -#include "js_uv_queue.h" #include "logger.h" namespace OHOS::AppDataMgrJsKit { using namespace OHOS::Rdb; diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h b/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h index d04c84b58cfdaecd1e814d0bc9c286634558b077..b28d51685cd16006f0399320aac5d201da3950cf 100644 --- a/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h +++ b/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h @@ -28,7 +28,8 @@ constexpr int OK = 0; constexpr int ERR = -1; // T inherits AysncContext -template class NapiAsyncProxy { +template +class NapiAsyncProxy { public: constexpr static int RESULT_COUNT = 2; using InputParser = void (*)(const napi_env &, const napi_value &, T *); diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h b/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h index b9044f1166f754e9e585a2343606f3d4ed81174c..cbe35b56de3d17b812cb7abafd9d162978662a28 100644 --- a/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h +++ b/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h @@ -17,6 +17,7 @@ #define DATAABILITY_JSKIT_NAPI_DATA_ABILITY_PREDICATES_H #include + #include "data_ability_predicates.h" #include "napi/native_api.h" #include "napi/native_common.h" @@ -39,8 +40,7 @@ private: ~DataAbilityPredicatesProxy(); static napi_value New(napi_env env, napi_callback_info info); - static std::shared_ptr GetNativePredicates(napi_env env, - napi_callback_info info); + static std::shared_ptr GetNativePredicates(napi_env env, napi_callback_info info); static napi_value EqualTo(napi_env env, napi_callback_info info); static napi_value NotEqualTo(napi_env env, napi_callback_info info); static napi_value BeginWrap(napi_env env, napi_callback_info info); @@ -90,12 +90,10 @@ private: } // namespace OHOS EXTERN_C_START -__attribute__((visibility("default"))) - napi_value NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance(napi_env env, - OHOS::NativeRdb::DataAbilityPredicates *predicates); +__attribute__((visibility("default"))) napi_value NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance( + napi_env env, OHOS::NativeRdb::DataAbilityPredicates *predicates); __attribute__((visibility("default"))) OHOS::NativeRdb::DataAbilityPredicates * -NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject( - const napi_env env, const napi_value arg); +NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_GetNativeObject(const napi_env env, const napi_value arg); EXTERN_C_END #endif // DATAABILITY_JSKIT_NAPI_DATA_ABILITY_PREDICATES_H \ No newline at end of file diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h b/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h index 4c4ee48b8be9cc02bd72cf586aa5efcccd3fd92b..ed62fd667c5551657d5a7576a398183ead6ad4ac 100644 --- a/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h +++ b/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h @@ -23,12 +23,12 @@ namespace OHOS { namespace DataAbilityJsKit { napi_value InitPredicatesUtils(napi_env env, napi_value info); -#define RDB_CHECK_RETURN_NULLPTR(assertion, message) \ - do { \ - if (!(assertion)) { \ - LOG_ERROR("%{public}s", message); \ - return nullptr; \ - } \ +#define RDB_CHECK_RETURN_NULLPTR(assertion, message) \ + do { \ + if (!(assertion)) { \ + LOG_ERROR("%{public}s", message); \ + return nullptr; \ + } \ } while (0) } // namespace DataAbilityJsKit } // namespace OHOS diff --git a/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp b/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp index 3a91edd52a6880fc7b57ee1a49635be600ce4453..9b5056735778a2ab34c2bcb80d9da4481fa59cd5 100644 --- a/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp +++ b/relational_store/frameworks/js/napi/dataability/src/napi_data_ability_predicates.cpp @@ -15,11 +15,11 @@ #define LOG_TAG "DataAbilityPredicatesProxy" #include "napi_data_ability_predicates.h" +#include "js_df_manager.h" #include "js_utils.h" #include "logger.h" #include "napi_async_proxy.h" #include "napi_predicates_utils.h" -#include "js_df_manager.h" using namespace OHOS::Rdb; using namespace OHOS::NativeRdb; @@ -805,9 +805,8 @@ napi_value DataAbilityPredicatesProxy::IsSorted(napi_env env, napi_callback_info } // namespace OHOS EXTERN_C_START -__attribute__((visibility("default"))) - napi_value NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance( - napi_env env, OHOS::NativeRdb::DataAbilityPredicates *predicates) +__attribute__((visibility("default"))) napi_value NAPI_OHOS_Data_DataAbilityJsKit_DataAbilityPredicatesProxy_NewInstance( + napi_env env, OHOS::NativeRdb::DataAbilityPredicates *predicates) { return OHOS::DataAbilityJsKit::DataAbilityPredicatesProxy::NewInstance( env, std::shared_ptr(predicates)); diff --git a/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp b/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp index 74aa0822653fa882b7fbbf1d3b03258a2657b44a..1a3f4fae1f1eaba0e213090c44742ab51e0f4315 100644 --- a/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp +++ b/relational_store/frameworks/js/napi/dataability/src/napi_predicates_utils.cpp @@ -50,9 +50,8 @@ napi_value CreateRdbPredicates(napi_env env, napi_callback_info info) auto predicates = new NativeRdb::RdbPredicates(tableName); NativeRdb::PredicatesUtils::SetWhereClauseAndArgs( predicates, absPredicates->GetWhereClause(), absPredicates->GetBindArgs()); - NativeRdb::PredicatesUtils::SetAttributes(predicates, absPredicates->IsDistinct(), - absPredicates->GetIndex(), absPredicates->GetGroup(), absPredicates->GetOrder(), absPredicates->GetLimit(), - absPredicates->GetOffset()); + NativeRdb::PredicatesUtils::SetAttributes(predicates, absPredicates->IsDistinct(), absPredicates->GetIndex(), + absPredicates->GetGroup(), absPredicates->GetOrder(), absPredicates->GetLimit(), absPredicates->GetOffset()); return RdbJsKit::RdbPredicatesProxy::NewInstance(env, std::shared_ptr(predicates)); } diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h index bfdad8a91f60abbb18bf13c3de5d688cd4339e59..625dd0b7496600878795ce2c0c7851a1f5560206 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h @@ -16,8 +16,8 @@ #ifndef NAPI_RDB_CONST_PROPERTIES_H #define NAPI_RDB_CONST_PROPERTIES_H -#include "napi/native_common.h" #include "napi/native_api.h" +#include "napi/native_common.h" #include "napi/native_node_api.h" namespace OHOS::RdbJsKit { diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h index 4b81bc0ad5ecf839d3bcbb5483a3e7b1e5c46362..79e174a4f9148da55a449bf6a26d9ac5a74638ff 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h @@ -68,32 +68,31 @@ constexpr int E_RESULT_GOTO_ERROR = 14800012; } \ } while (0) -#define RDB_CHECK_RETURN_NULLPTR(assertion, message) \ - do { \ - if (!(assertion)) { \ - LOG_ERROR("%{public}s", message); \ - return nullptr; \ - } \ +#define RDB_CHECK_RETURN_NULLPTR(assertion, message) \ + do { \ + if (!(assertion)) { \ + LOG_ERROR("%{public}s", message); \ + return nullptr; \ + } \ } while (0) -#define RDB_CHECK_RETURN_VOID(assertion, message) \ +#define RDB_CHECK_RETURN_VOID(assertion, message) \ + do { \ + if (!(assertion)) { \ + LOG_ERROR("%{public}s", message); \ + return; \ + } \ + } while (0) + +#define CHECK_RETURN_CORE(assertion, theCall, revt) \ do { \ if (!(assertion)) { \ - LOG_ERROR("%{public}s", message); \ - return; \ + theCall; \ + return revt; \ } \ } while (0) -#define CHECK_RETURN_CORE(assertion, theCall, revt) \ - do { \ - if (!(assertion)) { \ - theCall; \ - return revt; \ - } \ - } while (0) - -#define CHECK_RETURN_ERR(assertion) \ - CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, ERR) +#define CHECK_RETURN_ERR(assertion) CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, ERR) #define RDB_CHECK_RETURN_CALL_RESULT(assertion, theCall) \ do { \ @@ -105,7 +104,7 @@ constexpr int E_RESULT_GOTO_ERROR = 14800012; class Error { public: - virtual ~Error(){}; + virtual ~Error() {}; virtual std::string GetMessage() = 0; virtual int GetCode() = 0; }; @@ -125,7 +124,7 @@ public: class ParamTypeError : public Error { public: - ParamTypeError(const std::string &name, const std::string &wantType) : name(name), wantType(wantType){}; + 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; @@ -142,7 +141,7 @@ private: class ParamNumError : public Error { public: - ParamNumError(const std::string &wantNum) : wantNum(wantNum){}; + ParamNumError(const std::string &wantNum) : wantNum(wantNum) {}; std::string GetMessage() override { return "Parameter error. Need " + wantNum + " parameters!"; diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_observer.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_observer.h index b8ab83cdf33dee3fc495300bf566616203ffaff8..5b14315afa8ce7b8f569b0c5020012df5362c8ab 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_observer.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_observer.h @@ -16,8 +16,8 @@ #ifndef NAPI_RDB_STORE_OBSERVER_H #define NAPI_RDB_STORE_OBSERVER_H -#include "rdb_types.h" #include "napi_uv_queue.h" +#include "rdb_types.h" namespace OHOS::RdbJsKit { class NapiRdbStoreObserver : public DistributedRdb::RdbStoreObserver, public NapiUvQueue { @@ -25,7 +25,7 @@ public: explicit NapiRdbStoreObserver(napi_env env, napi_value callback); virtual ~NapiRdbStoreObserver() noexcept; - void OnChange(const std::vector& devices) override; + void OnChange(const std::vector &devices) override; }; -} +} // namespace OHOS::RdbJsKit #endif 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 4ad567b7029b91d061f05e5f4669153ff2f86af3..e033584b50e2a86b0243a0f7650f735076e51823 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 @@ -36,8 +36,8 @@ public: ResultSetProxy &operator=(std::shared_ptr resultSet); static napi_value NewInstance(napi_env env, std::shared_ptr resultSet, int version = AppDataMgrJsKit::APIVERSION_8); - static napi_value NewInstance(napi_env env, std::shared_ptr resultSet, - int version = AppDataMgrJsKit::APIVERSION_8); + static napi_value NewInstance( + napi_env env, std::shared_ptr resultSet, int version = AppDataMgrJsKit::APIVERSION_8); static std::shared_ptr GetNativeObject(const napi_env env, const napi_value arg); static napi_value GetConstructor(napi_env env, int version); std::shared_ptr Create() override; @@ -46,7 +46,7 @@ public: private: static ResultSetProxy *GetInnerResultSet(napi_env env, napi_callback_info info, int &version); static ResultSetProxy *ParseInt32FieldByName( - napi_env env, napi_callback_info info, int32_t &field, const std::string& fieldName); + 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); static napi_value InnerInitialize( diff --git a/relational_store/frameworks/js/napi/rdb/src/entry_point.cpp b/relational_store/frameworks/js/napi/rdb/src/entry_point.cpp index 21a6d6bdb61401ec9541e843528f2b751fec496d..8cf0d930a716eca4a699e3a265023b2fee7d2ea5 100644 --- a/relational_store/frameworks/js/napi/rdb/src/entry_point.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/entry_point.cpp @@ -13,11 +13,11 @@ * limitations under the License. */ +#include "napi/native_api.h" +#include "napi_rdb_const_properties.h" #include "napi_rdb_predicates.h" #include "napi_rdb_store.h" #include "napi_rdb_store_helper.h" -#include "napi_rdb_const_properties.h" -#include "napi/native_api.h" using namespace OHOS::RdbJsKit; 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 068a0c0a20cc591d1ea25b8f17b9a5f5661c6f7d..1b27562cb4fcc16142a7aaf66a22d13c5a656b25 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 @@ -18,13 +18,13 @@ #include "rdb_store_config.h" #include "rdb_types.h" -using OHOS::DistributedRdb::SyncMode; using OHOS::DistributedRdb::SubscribeMode; +using OHOS::DistributedRdb::SyncMode; #endif namespace OHOS::RdbJsKit { #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -static napi_status SetNamedProperty(napi_env env, napi_value& obj, const std::string& name, int32_t value) +static napi_status SetNamedProperty(napi_env env, napi_value &obj, const std::string &name, int32_t value) { napi_value property = nullptr; napi_status status = napi_create_int32(env, value, &property); @@ -63,10 +63,10 @@ static napi_value ExportSecurityLevel(napi_env env) napi_value securityLevel = nullptr; napi_create_object(env, &securityLevel); - (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); + (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_js_utils.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_js_utils.cpp index f346f757bdc7909374d42e087af77ea4c15cbd40..c5fa0a69fd7686d079524b783f4e2eee130cfe9b 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_js_utils.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_js_utils.cpp @@ -82,7 +82,7 @@ int32_t Convert2Value(napi_env env, napi_value jsValue, ValueObject &valueObject } template<> -napi_value Convert2JSValue(napi_env env, const BigInt& value) +napi_value Convert2JSValue(napi_env env, const BigInt &value) { napi_value val = nullptr; napi_status status = napi_create_bigint_words(env, value.Sign(), value.Size(), value.TrueForm(), &val); @@ -93,7 +93,7 @@ napi_value Convert2JSValue(napi_env env, const BigInt& value) } template<> -int32_t Convert2Value(napi_env env, napi_value jsValue, BigInt& value) +int32_t Convert2Value(napi_env env, napi_value jsValue, BigInt &value) { napi_valuetype type = napi_undefined; napi_status status = napi_typeof(env, jsValue, &type); 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 6ad5b674f219922efbf554ab753d0e73a6d16593..5ec99f3bc7d711ec4b0c1e1a3d4ed29b314f0697 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 @@ -15,11 +15,11 @@ #define LOG_TAG "RdbPredicatesProxy" #include "napi_rdb_predicates.h" +#include "js_df_manager.h" #include "js_utils.h" #include "logger.h" #include "napi_rdb_error.h" #include "napi_rdb_trace.h" -#include "js_df_manager.h" using namespace OHOS::Rdb; using namespace OHOS::NativeRdb; @@ -237,12 +237,12 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldArrayByName(napi_env env, napi if (ret != napi_ok && fieldName == "devices") { std::string field; ret = JSUtils::Convert2Value(env, args[0], field); - RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, - std::make_shared(fieldName, "a " + fieldType + " array."), version); + RDB_NAPI_ASSERT_FROMV9( + env, ret == napi_ok, std::make_shared(fieldName, "a " + fieldType + " array."), version); fieldarray.push_back(field); } - RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, - std::make_shared(fieldName, "a " + fieldType + " array."), version); + RDB_NAPI_ASSERT_FROMV9( + env, ret == napi_ok, std::make_shared(fieldName, "a " + fieldType + " array."), version); return predicatesProxy; } @@ -261,8 +261,8 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldByName( 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); + RDB_NAPI_ASSERT_FROMV9( + env, !field.empty(), std::make_shared(fieldName, "a non empty string."), version); return predicatesProxy; } @@ -281,8 +281,7 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseInt32FieldByName( 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); + RDB_NAPI_ASSERT_FROMV9(env, status == napi_ok, std::make_shared(fieldName, "a number."), version); return predicatesProxy; } @@ -302,12 +301,12 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValueArray(napi_env env, na 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); + RDB_NAPI_ASSERT_FROMV9( + env, !field.empty(), std::make_shared("field", "a non empty string."), version); int32_t ret = JSUtils::Convert2Value(env, args[1], values); - RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, - std::make_shared("value", "a " + valueType + " array."), version); + RDB_NAPI_ASSERT_FROMV9( + env, ret == napi_ok, std::make_shared("value", "a " + valueType + " array."), version); return predicatesProxy; } @@ -330,13 +329,13 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndValue(napi_env env, napi_ca // args[0] represents the first parameter field = JSUtils::Convert2String(env, args[0]); - RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), - std::make_shared("field", "a non empty string."), version); + RDB_NAPI_ASSERT_FROMV9( + env, !field.empty(), std::make_shared("field", "a non empty string."), version); // args[1] represents the second parameter int ret = JSUtils::Convert2Value(env, args[1], value.value); - RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, - std::make_shared("value", "a non empty string."), version); + RDB_NAPI_ASSERT_FROMV9( + env, ret == napi_ok, std::make_shared("value", "a non empty string."), version); return predicatesProxy; } @@ -357,8 +356,8 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldAndStringValue(napi_env env, n 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); + RDB_NAPI_ASSERT_FROMV9( + env, !field.empty(), std::make_shared("field", "a non empty string."), version); value = JSUtils::Convert2String(env, args[1]); return predicatesProxy; @@ -382,18 +381,18 @@ RdbPredicatesProxy *RdbPredicatesProxy::ParseFieldLowAndHigh( // args[0] represents the first parameter field = JSUtils::Convert2String(env, args[0]); - RDB_NAPI_ASSERT_FROMV9(env, !field.empty(), - std::make_shared("field", "a non empty string."), version); + RDB_NAPI_ASSERT_FROMV9( + env, !field.empty(), std::make_shared("field", "a non empty string."), version); // args[1] represents the second parameter int32_t ret = JSUtils::Convert2Value(env, args[1], low); - RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, - std::make_shared("low", "a non empty ValueType."), version); + RDB_NAPI_ASSERT_FROMV9( + env, ret == napi_ok, std::make_shared("low", "a non empty ValueType."), version); // args[2] represents the third parameter ret = JSUtils::Convert2Value(env, args[2], high); - RDB_NAPI_ASSERT_FROMV9(env, ret == napi_ok, - std::make_shared("high", "a non empty ValueType."), version); + RDB_NAPI_ASSERT_FROMV9( + env, ret == napi_ok, std::make_shared("high", "a non empty ValueType."), version); return predicatesProxy; } 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 0a20b3fe6b69cc8ef41b2ddd9a3a8e8489727ddf..7d3bfdcbf1946355b30d9b1af577c724c6338a58 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 @@ -19,6 +19,7 @@ #include #include +#include "js_df_manager.h" #include "js_utils.h" #include "logger.h" #include "napi_async_call.h" @@ -27,7 +28,6 @@ #include "napi_rdb_trace.h" #include "napi_result_set.h" #include "rdb_errno.h" -#include "js_df_manager.h" #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) #include "rdb_utils.h" @@ -268,9 +268,9 @@ int ParseDevice(const napi_env env, const napi_value arg, std::shared_ptr context) { uint32_t arrLen = 0; - napi_get_array_length(env, arg, &arrLen); + napi_status status = napi_get_array_length(env, arg, &arrLen); std::shared_ptr paramError = std::make_shared("tables", "a string array."); - RDB_CHECK_RETURN_CALL_RESULT(arrLen >= 0, context->SetError(paramError)); + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok, context->SetError(paramError)); for (uint32_t i = 0; i < arrLen; ++i) { napi_value element = nullptr; @@ -318,12 +318,13 @@ int ParsePredicates(const napi_env env, const napi_value arg, std::shared_ptr paramError = std::make_shared("predicates", "an RdbPredicates."); - if (CheckGlobalProperty(env, arg, "RdbPredicatesConstructor") - || CheckGlobalProperty(env, arg, "RdbPredicatesConstructorV9")) { + if (CheckGlobalProperty(env, arg, "RdbPredicatesConstructor") || + CheckGlobalProperty(env, arg, "RdbPredicatesConstructorV9")) { LOG_DEBUG("Parse RDB Predicates."); napi_unwrap(env, arg, reinterpret_cast(&context->predicatesProxy)); - RDB_CHECK_RETURN_CALL_RESULT(context->predicatesProxy != nullptr && - context->predicatesProxy->GetPredicates() != nullptr, context->SetError(paramError)); + RDB_CHECK_RETURN_CALL_RESULT( + context->predicatesProxy != nullptr && context->predicatesProxy->GetPredicates() != nullptr, + context->SetError(paramError)); context->tableName = context->predicatesProxy->GetPredicates()->GetTableName(); context->rdbPredicates = context->predicatesProxy->GetPredicates(); LOG_DEBUG("ParsePredicates end."); @@ -443,8 +444,7 @@ int ParseValuesBucket(const napi_env env, const napi_value arg, std::shared_ptr< { napi_value keys = nullptr; napi_get_all_property_names(env, arg, napi_key_own_only, - static_cast(napi_key_enumerable | napi_key_skip_symbols), - napi_key_numbers_to_strings, &keys); + static_cast(napi_key_enumerable | napi_key_skip_symbols), napi_key_numbers_to_strings, &keys); uint32_t arrLen = 0; napi_status status = napi_get_array_length(env, keys, &arrLen); std::shared_ptr paramError = std::make_shared("values", "a ValuesBucket."); @@ -474,8 +474,8 @@ int ParseValuesBucket(const napi_env env, const napi_value arg, std::shared_ptr< if (ret == napi_ok) { context->valuesBucket.Put(keyStr, std::move(valueObject)); } else if (ret != napi_generic_failure) { - std::shared_ptr paramError = std::make_shared( - "The value type of " + keyStr, "valid."); + std::shared_ptr paramError = + std::make_shared("The value type of " + keyStr, "valid."); RDB_CHECK_RETURN_CALL_RESULT(false, context->SetError(paramError)); } } @@ -494,12 +494,12 @@ int ParseValuesBuckets(const napi_env env, const napi_value arg, std::shared_ptr } uint32_t arrLen = 0; napi_status status = napi_get_array_length(env, arg, &arrLen); - RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok || arrLen >= 0, context->SetError(paramError)); + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok, context->SetError(paramError)); for (uint32_t i = 0; i < arrLen; ++i) { napi_value obj = nullptr; status = napi_get_element(env, arg, i, &obj); - RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok || arrLen >= 0, context->SetError(paramError)); + RDB_CHECK_RETURN_CALL_RESULT(status == napi_ok, context->SetError(paramError)); ParseValuesBucket(env, obj, context); context->valuesBuckets.push_back(context->valuesBucket); @@ -586,8 +586,7 @@ napi_value RdbStoreProxy::BatchInsert(napi_env env, napi_callback_info info) }; 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. tableName is: %{public}s.", - context->tableName.c_str()); + LOG_DEBUG("RdbStoreProxy::BatchInsert end. tableName is: %{public}s.", context->tableName.c_str()); return (status == napi_ok) ? OK : ERR; }; context->SetAction(env, info, input, exec, output); @@ -716,8 +715,7 @@ napi_value RdbStoreProxy::Query(napi_env env, napi_callback_info info) return (context->resultSet != nullptr) ? OK : ERR; }; auto output = [context](napi_env env, napi_value &result) -> int { - result = ResultSetProxy::NewInstance( - env, context->resultSet, context->apiversion); + result = ResultSetProxy::NewInstance(env, context->resultSet, context->apiversion); return (result != nullptr) ? OK : ERR; }; context->SetAction(env, info, input, exec, output); @@ -761,8 +759,7 @@ napi_value RdbStoreProxy::QuerySql(napi_env env, napi_callback_info info) #endif }; auto output = [context](napi_env env, napi_value &result) -> int { - result = ResultSetProxy::NewInstance( - env, context->resultSet, context->apiversion); + result = ResultSetProxy::NewInstance(env, context->resultSet, context->apiversion); return (result != nullptr) ? OK : ERR; }; context->SetAction(env, info, input, exec, output); @@ -848,8 +845,7 @@ napi_value RdbStoreProxy::Count(napi_env env, napi_callback_info info) RdbStoreProxy *obj = reinterpret_cast(context->boundObj); std::int64_t temp = 0; CHECK_RETURN_ERR(obj != nullptr && obj->rdbStore_ != nullptr); - CHECK_RETURN_ERR(context->predicatesProxy != nullptr && - context->predicatesProxy->GetPredicates() != nullptr); + CHECK_RETURN_ERR(context->predicatesProxy != nullptr && context->predicatesProxy->GetPredicates() != nullptr); int errCode = obj->rdbStore_->Count(temp, *(context->predicatesProxy->GetPredicates())); context->rowId = temp; LOG_DEBUG("RdbStoreProxy::Count errCode is: %{public}d.", errCode); @@ -936,8 +932,8 @@ napi_value RdbStoreProxy::IsHoldingConnection(napi_env env, napi_callback_info i napi_value thisObj = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thisObj, nullptr); RdbStoreProxy *rdbStoreProxy = GetNativeInstance(env, thisObj); - NAPI_ASSERT(env, rdbStoreProxy != nullptr && - rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); + NAPI_ASSERT( + env, rdbStoreProxy != nullptr && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); bool out = rdbStoreProxy->rdbStore_->IsHoldingConnection(); LOG_DEBUG("RdbStoreProxy::IsHoldingConnection out is : %{public}d.", out); return JSUtils::Convert2JSValue(env, out); @@ -948,8 +944,8 @@ napi_value RdbStoreProxy::IsReadOnly(napi_env env, napi_callback_info info) napi_value thisObj = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thisObj, nullptr); RdbStoreProxy *rdbStoreProxy = GetNativeInstance(env, thisObj); - NAPI_ASSERT(env, rdbStoreProxy != nullptr - && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); + NAPI_ASSERT( + env, rdbStoreProxy != nullptr && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); bool out = rdbStoreProxy->rdbStore_->IsReadOnly(); LOG_DEBUG("RdbStoreProxy::IsReadOnly out is : %{public}d.", out); return JSUtils::Convert2JSValue(env, out); @@ -960,8 +956,8 @@ napi_value RdbStoreProxy::IsMemoryRdb(napi_env env, napi_callback_info info) napi_value thisObj = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thisObj, nullptr); RdbStoreProxy *rdbStoreProxy = GetNativeInstance(env, thisObj); - NAPI_ASSERT(env, rdbStoreProxy != nullptr - && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); + NAPI_ASSERT( + env, rdbStoreProxy != nullptr && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); bool out = rdbStoreProxy->rdbStore_->IsMemoryRdb(); LOG_DEBUG("RdbStoreProxy::IsMemoryRdb out is : %{public}d.", out); return JSUtils::Convert2JSValue(env, out); @@ -972,8 +968,8 @@ napi_value RdbStoreProxy::GetPath(napi_env env, napi_callback_info info) napi_value thisObj = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thisObj, nullptr); RdbStoreProxy *rdbStoreProxy = GetNativeInstance(env, thisObj); - NAPI_ASSERT(env, rdbStoreProxy != nullptr - && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); + NAPI_ASSERT( + env, rdbStoreProxy != nullptr && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); std::string path = rdbStoreProxy->rdbStore_->GetPath(); LOG_DEBUG("RdbStoreProxy::GetPath path is empty ? %{public}d.", path.empty()); return JSUtils::Convert2JSValue(env, path); @@ -984,8 +980,8 @@ napi_value RdbStoreProxy::BeginTransaction(napi_env env, napi_callback_info info napi_value thisObj = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisObj, nullptr)); RdbStoreProxy *rdbStoreProxy = GetNativeInstance(env, thisObj); - NAPI_ASSERT(env, rdbStoreProxy != nullptr - && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); + NAPI_ASSERT( + env, rdbStoreProxy != nullptr && rdbStoreProxy->rdbStore_ != nullptr, "RdbStoreProxy or rdbStore_ is nullptr"); int errCode = rdbStoreProxy->rdbStore_->BeginTransaction(); NAPI_ASSERT(env, errCode == E_OK, "call BeginTransaction failed"); LOG_DEBUG("RdbStoreProxy::BeginTransaction end, errCode is:%{public}d.", errCode); 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 71a54cd7cb4fc4f3121059f6e25e1d6e89009635..a70b5e9678cfbad147daf8089f0ba808aca563ea 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 @@ -253,7 +253,7 @@ struct HelperRdbContext : public BaseContext { HelperRdbContext() : config(""), version(0), iscontext(false), openCallback(), proxy(nullptr) { } - virtual ~HelperRdbContext(){}; + virtual ~HelperRdbContext() {}; }; using ParseStoreConfigFunction = int (*)( @@ -463,8 +463,8 @@ napi_value InnerGetRdbStore(napi_env env, napi_callback_info info, std::shared_p }; context->SetAction(env, info, input, exec, output); - RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK, - "RdbJsKit::GetRdbStore end with err"); + RDB_CHECK_RETURN_NULLPTR( + context->error == nullptr || context->error->GetCode() == OK, "RdbJsKit::GetRdbStore end with err"); return AsyncCall::Call(env, context); } @@ -517,8 +517,8 @@ napi_value InnerDeleteRdbStore(napi_env env, napi_callback_info info, std::share }; context->SetAction(env, info, input, exec, output); - RDB_CHECK_RETURN_NULLPTR(context->error == nullptr || context->error->GetCode() == OK, - "RdbJsKit::DeleteRdbStore end with err"); + RDB_CHECK_RETURN_NULLPTR( + context->error == nullptr || context->error->GetCode() == OK, "RdbJsKit::DeleteRdbStore end with err"); return AsyncCall::Call(env, context); } 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 3ecf55c107bb11bf488b14c8356bded780d7fdd6..1c47039cb0a6fd59c1e955e631db7b6f1a48889d 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 @@ -17,12 +17,12 @@ #include +#include "js_df_manager.h" #include "js_utils.h" #include "logger.h" #include "napi_rdb_error.h" #include "napi_rdb_trace.h" #include "rdb_errno.h" -#include "js_df_manager.h" #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) #include "abs_shared_result_set.h" @@ -86,8 +86,7 @@ napi_value ResultSetProxy::NewInstance(napi_env env, std::shared_ptr ResultSetProxy::GetNativeObject( - napi_env const env, napi_value const arg) +std::shared_ptr ResultSetProxy::GetNativeObject(napi_env const env, napi_value const arg) { if (arg == nullptr) { LOG_ERROR("ResultSetProxy GetNativeObject arg is null."); @@ -243,7 +242,7 @@ ResultSetProxy *ResultSetProxy::GetInnerResultSet(napi_env env, napi_callback_in } ResultSetProxy *ResultSetProxy::ParseInt32FieldByName( - napi_env env, napi_callback_info info, int32_t &field, const std::string& name) + napi_env env, napi_callback_info info, int32_t &field, const std::string &name) { DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); napi_value self = nullptr; @@ -254,8 +253,7 @@ ResultSetProxy *ResultSetProxy::ParseInt32FieldByName( napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)); RDB_NAPI_ASSERT_FROMV9(env, resultSetProxy && resultSetProxy->GetInstance(), std::make_shared("resultSet", "not null"), resultSetProxy->apiversion); - RDB_NAPI_ASSERT_FROMV9( - env, argc == 1, std::make_shared("1"), resultSetProxy->apiversion); + RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), resultSetProxy->apiversion); napi_status status = napi_get_value_int32(env, args[0], &field); RDB_NAPI_ASSERT_FROMV9( @@ -272,8 +270,7 @@ ResultSetProxy *ResultSetProxy::ParseFieldByName(napi_env env, napi_callback_inf ResultSetProxy *resultSetProxy = nullptr; napi_unwrap(env, self, reinterpret_cast(&resultSetProxy)); RDB_CHECK_RETURN_NULLPTR(resultSetProxy && resultSetProxy->GetInstance(), "Proxy or instance is nullptr"); - RDB_NAPI_ASSERT_FROMV9( - env, argc == 1, std::make_shared("1"), resultSetProxy->apiversion); + RDB_NAPI_ASSERT_FROMV9(env, argc == 1, std::make_shared("1"), resultSetProxy->apiversion); field = JSUtils::Convert2String(env, args[0]); return resultSetProxy; @@ -608,8 +605,7 @@ napi_value ResultSetProxy::GetSharedBlockName(napi_env env, napi_callback_info i ResultSetProxy *proxy; NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&proxy))); - RDB_CHECK_RETURN_NULLPTR(proxy != nullptr, - "ResultSetProxy::GetSharedBlockName proxy is nullptr"); + RDB_CHECK_RETURN_NULLPTR(proxy != nullptr, "ResultSetProxy::GetSharedBlockName proxy is nullptr"); return JSUtils::Convert2JSValue(env, proxy->sharedBlockName_); } @@ -621,8 +617,7 @@ napi_value ResultSetProxy::GetSharedBlockAshmemFd(napi_env env, napi_callback_in ResultSetProxy *proxy; NAPI_CALL(env, napi_unwrap(env, thiz, reinterpret_cast(&proxy))); - RDB_CHECK_RETURN_NULLPTR(proxy != nullptr, - "ResultSetProxy::GetSharedBlockAshmemFd proxy is nullptr"); + RDB_CHECK_RETURN_NULLPTR(proxy != nullptr, "ResultSetProxy::GetSharedBlockAshmemFd proxy is nullptr"); return JSUtils::Convert2JSValue(env, proxy->sharedBlockAshmemFd_); } @@ -631,15 +626,15 @@ napi_value ResultSetProxy::GetSharedBlockAshmemFd(napi_env env, napi_callback_in #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) -__attribute__((visibility("default"))) napi_value NewCInstance(napi_env env, - napi_value arg) asm("NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_NewInstance"); +__attribute__((visibility("default"))) napi_value NewCInstance(napi_env env, napi_value arg) asm( + "NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_NewInstance"); napi_value NewCInstance(napi_env env, std::shared_ptr resultSet) { return OHOS::RdbJsKit::ResultSetProxy::NewInstance(env, resultSet); } -__attribute__((visibility("default"))) std::shared_ptr GetCObject(napi_env env, - napi_value arg) asm("NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_GetNativeObject"); +__attribute__((visibility("default"))) std::shared_ptr GetCObject( + napi_env env, napi_value arg) asm("NAPI_OHOS_Data_RdbJsKit_ResultSetProxy_GetNativeObject"); std::shared_ptr GetCObject(napi_env env, napi_value arg) { return OHOS::RdbJsKit::ResultSetProxy::GetNativeObject(env, arg); diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_uv_queue.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_uv_queue.cpp index 4ea3ed6bb421c548eb1b8aa693db6cf6a012713c..9badcf03749b41f742ca8492934fcd3cda74d36e 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_uv_queue.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_uv_queue.cpp @@ -45,7 +45,7 @@ bool NapiUvQueue::operator==(napi_value value) void NapiUvQueue::CallFunction(NapiArgsGenerator genArgs) { - uv_work_t* work = new (std::nothrow) uv_work_t; + uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { return; } @@ -84,4 +84,4 @@ void NapiUvQueue::CallFunction(NapiArgsGenerator genArgs) delete work; } } -} // namespace OHOS::RdbJsKit \ No newline at end of file +} // namespace OHOS::RdbJsKit diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp index 6a145fca2e768090267ce6434e339a98718b6c7c..81032b826cd418ffb9d56ad53b370349ef27379f 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_values_bucket.cpp @@ -28,7 +28,7 @@ __attribute__((visibility("default"))) napi_value NAPI_OHOS_Data_RdbJsKit_Values { napi_value ret = nullptr; NAPI_CALL(env, napi_create_object(env, &ret)); - for (auto &[key, value]: valuesBucket.values_) { + for (auto &[key, value] : valuesBucket.values_) { napi_value jsValue = JSUtils::Convert2JSValue(env, value.value); NAPI_CALL(env, napi_set_named_property(env, ret, key.c_str(), jsValue)); } diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h index 920be7036adcdd920e0019d22e323d476be39feb..7340d9d86e3f3ebc24396e3241703a871ec4cefe 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h @@ -15,9 +15,9 @@ #ifndef RDB_JS_NAPI_ASYNC_CALL_H #define RDB_JS_NAPI_ASYNC_CALL_H -#include -#include #include +#include +#include #include #include @@ -42,7 +42,7 @@ extern bool g_sync; class ContextBase { public: struct RecordData { - std::atomic_uint64_t times_{0}; + std::atomic_uint64_t times_{ 0 }; int64_t lastTime_ = 0; RecordData() = default; RecordData(const RecordData &record) @@ -50,7 +50,7 @@ public: times_.store(record.times_); lastTime_ = record.lastTime_; } - RecordData& operator= (const RecordData &record) + RecordData &operator=(const RecordData &record) { times_.store(record.times_); lastTime_ = record.lastTime_; diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h index 1ff7aa4b376a745693b78d61b2eeba7e8a14bb1a..4ea2ec0298741aeacd391096dfc9b9bc6db6abd3 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_error.h @@ -18,6 +18,7 @@ #include #include #include + #include "logger.h" #include "rdb_errno.h" @@ -43,50 +44,45 @@ const std::optional GetJsErrorCode(int32_t errorCode); #define RDB_REVT_NOTHING #define RDB_DO_NOTHING -#define RDB_NAPI_ASSERT_BASE(env, assertion, error, retVal) \ - do { \ - if (!(assertion)) { \ - if ((error) == nullptr) { \ - LOG_ERROR("throw error: error message is empty"); \ - napi_throw_error((env), nullptr, "error message is empty"); \ - return retVal; \ - } \ - LOG_ERROR("throw error: code = %{public}d , message = %{public}s", (error)->GetCode(), \ - (error)->GetMessage().c_str()); \ +#define RDB_NAPI_ASSERT_BASE(env, assertion, error, retVal) \ + do { \ + if (!(assertion)) { \ + if ((error) == nullptr) { \ + LOG_ERROR("throw error: error message is empty"); \ + napi_throw_error((env), nullptr, "error message is empty"); \ + return retVal; \ + } \ + 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; \ - } \ + return retVal; \ + } \ } while (0) -#define RDB_NAPI_ASSERT(env, assertion, error) \ - RDB_NAPI_ASSERT_BASE(env, assertion, error, nullptr) +#define RDB_NAPI_ASSERT(env, assertion, error) RDB_NAPI_ASSERT_BASE(env, assertion, error, nullptr) -#define CHECK_RETURN_CORE(assertion, theCall, revt) \ - do { \ - if (!(assertion)) { \ - theCall; \ - return revt; \ - } \ +#define CHECK_RETURN_CORE(assertion, theCall, revt) \ + do { \ + if (!(assertion)) { \ + theCall; \ + return revt; \ + } \ } while (0) #define CHECK_RETURN_SET_E(assertion, paramError) \ CHECK_RETURN_CORE(assertion, context->SetError(paramError), RDB_REVT_NOTHING) -#define CHECK_RETURN_SET(assertion, paramError) \ - CHECK_RETURN_CORE(assertion, context->SetError(paramError), ERR) +#define CHECK_RETURN_SET(assertion, paramError) CHECK_RETURN_CORE(assertion, context->SetError(paramError), ERR) -#define CHECK_RETURN_NULL(assertion) \ - CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, nullptr) +#define CHECK_RETURN_NULL(assertion) CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, nullptr) -#define CHECK_RETURN_ERR(assertion) \ - CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, ERR) +#define CHECK_RETURN_ERR(assertion) CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, ERR) -#define CHECK_RETURN(assertion) \ - CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, RDB_REVT_NOTHING) +#define CHECK_RETURN(assertion) CHECK_RETURN_CORE(assertion, RDB_REVT_NOTHING, RDB_REVT_NOTHING) class Error { public: - virtual ~Error(){}; + virtual ~Error() {}; virtual std::string GetMessage() = 0; virtual int GetCode() = 0; }; @@ -121,6 +117,7 @@ public: { return code_; } + private: int code_; std::string msg_; @@ -169,7 +166,7 @@ public: class ParamNumError : public Error { public: - ParamNumError(const std::string &wantNum) : wantNum(wantNum){}; + ParamNumError(const std::string &wantNum) : wantNum(wantNum) {}; std::string GetMessage() override { return "Parameter error. Need " + wantNum + " parameter(s)!"; diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_error.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_error.cpp index 795433e706eeeb873cfe29f80cc99161c12bb8cb..8218b0280df6ccf0204f75ccb5ed64a983ee2b80 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_error.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_error.cpp @@ -51,6 +51,7 @@ static constexpr JsErrorCode JS_ERROR_CODE_MSGS[] = { { NativeRdb::E_SQLITE_MISMATCH, 14800033, "SQLite: Data type mismatch." }, { NativeRdb::E_SQLITE_MISUSE, 14800034, "SQLite: Library used incorrectly." }, { NativeRdb::E_CONFIG_INVALID_CHANGE, 14800017, "Config changed." }, + { NativeRdb::E_INVALID_SECRET_KEY, 14800020, "The key parameter is invalid." }, { NativeRdb::E_NOT_SUPPORT, 801, "Capability not support." }, }; diff --git a/relational_store/frameworks/js/napi/sendablerelationalstore/src/entry_point.cpp b/relational_store/frameworks/js/napi/sendablerelationalstore/src/entry_point.cpp index f24ae3da80325f9cf0cb33fad81fc5ed0ab3d6ae..726ea4f9a5d1828300676c51fc1918c966b18037 100644 --- a/relational_store/frameworks/js/napi/sendablerelationalstore/src/entry_point.cpp +++ b/relational_store/frameworks/js/napi/sendablerelationalstore/src/entry_point.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ -#include "napi_rdb_store_convert_utils.h" #include "napi/native_api.h" +#include "napi_rdb_store_convert_utils.h" using namespace OHOS::SendableRdb; diff --git a/relational_store/frameworks/native/appdatafwk/src/general_endian.cpp b/relational_store/frameworks/native/appdatafwk/src/general_endian.cpp index c9c296b671c2a78e8e5df8093c22440601edd005..2dfdbd8e019a7c4d53c73798d45bceafcb2eeca9 100644 --- a/relational_store/frameworks/native/appdatafwk/src/general_endian.cpp +++ b/relational_store/frameworks/native/appdatafwk/src/general_endian.cpp @@ -13,9 +13,10 @@ * limitations under the License. */ -#include "multi_platform_endian.h" #include +#include "multi_platform_endian.h" + namespace OHOS { uint16_t Endian::LeToH(uint16_t value) { @@ -46,4 +47,4 @@ uint64_t Endian::HToLe(uint64_t value) { return htole64(value); } -} +} // namespace OHOS diff --git a/relational_store/frameworks/native/appdatafwk/src/mingw_endian.cpp b/relational_store/frameworks/native/appdatafwk/src/mingw_endian.cpp index adf1efb65009b646d49c63cf2ade17fb42f8b828..f83bf4acedabed5d33e5339a7008f9e83ed7203d 100644 --- a/relational_store/frameworks/native/appdatafwk/src/mingw_endian.cpp +++ b/relational_store/frameworks/native/appdatafwk/src/mingw_endian.cpp @@ -41,4 +41,4 @@ uint64_t Endian::HToLe(uint64_t value) { return value; } -} +} // namespace OHOS diff --git a/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp b/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp index ab87e51ef43a93369a3eeca6d9ef9106572d698c..83a2e3b3c756412c774a0e583fbc95eb53880975 100644 --- a/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp +++ b/relational_store/frameworks/native/appdatafwk/src/shared_block.cpp @@ -30,7 +30,7 @@ namespace OHOS { namespace AppDataFwk { using namespace OHOS::Rdb; -std::atomic identifier {0}; +std::atomic identifier{ 0 }; #define LIKELY(x) __builtin_expect(!!(x), 1) #define UNLIKELY(x) __builtin_expect(!!(x), 0) @@ -58,8 +58,8 @@ bool SharedBlock::Init() return true; } -int SharedBlock::CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, - SharedBlock *&outSharedBlock) +int SharedBlock::CreateSharedBlock( + const std::string &name, size_t size, sptr ashmem, SharedBlock *&outSharedBlock) { outSharedBlock = new SharedBlock(name, ashmem, size, false); if (outSharedBlock == nullptr) { @@ -137,8 +137,8 @@ int SharedBlock::ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block) LOG_DEBUG("Created SharedBlock from parcel: unusedOffset=%{private}" PRIu32 ", " "rowNums=%{private}" PRIu32 ", columnNums=%{private}" PRIu32 ", mSize=%{private}d", - block->mHeader->unusedOffset, block->mHeader->rowNums, block->mHeader->columnNums, - static_cast(block->mSize)); + block->mHeader->unusedOffset, block->mHeader->rowNums, block->mHeader->columnNums, + static_cast(block->mSize)); return SHARED_BLOCK_OK; } @@ -198,8 +198,8 @@ int SharedBlock::AllocRow() uint32_t fieldDirOffset = Alloc(fieldDirSize); if (UNLIKELY(!fieldDirOffset)) { mHeader->rowNums--; - LOG_INFO("Alloc the row size %{public}u failed, roll back row number %{public}u", fieldDirOffset, - mHeader->rowNums); + LOG_INFO( + "Alloc the row size %{public}u failed, roll back row number %{public}u", fieldDirOffset, mHeader->rowNums); return SHARED_BLOCK_NO_MEMORY; } @@ -223,7 +223,7 @@ uint32_t SharedBlock::Alloc(size_t size) uint32_t nextFreeOffset = offset + size; if (UNLIKELY(nextFreeOffset > mSize)) { LOG_ERROR("SharedBlock is full: requested allocation %{public}zu bytes," - " free space %{public}zu bytes, block size %{public}zu bytes", + " free space %{public}zu bytes, block size %{public}zu bytes", size, mSize - mHeader->unusedOffset, mSize); return 0; } @@ -242,7 +242,7 @@ uint32_t *SharedBlock::AllocRowOffset() mHeader->groupOffset[groupPos] = Alloc(sizeof(RowGroupHeader)); if (UNLIKELY(mHeader->groupOffset[groupPos] == 0)) { LOG_ERROR("SharedBlock::AllocRowOffset() Failed to alloc group->nextGroupOffset " - "when while loop."); + "when while loop."); return nullptr; } } @@ -260,7 +260,7 @@ SharedBlock::CellUnit *SharedBlock::GetCellUnit(uint32_t row, uint32_t column) { if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" - " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", row, column, mHeader->rowNums, mHeader->columnNums); return nullptr; } @@ -291,12 +291,12 @@ int SharedBlock::PutAssets(uint32_t row, uint32_t column, const void *value, siz return PutBlobOrString(row, column, value, size, CELL_UNIT_TYPE_ASSETS); } -int SharedBlock::PutFloats(uint32_t row, uint32_t column, const void* value, size_t size) +int SharedBlock::PutFloats(uint32_t row, uint32_t column, const void *value, size_t size) { return PutBlobOrString(row, column, value, size, CELL_UNIT_TYPE_FLOATS); } -int SharedBlock::PutBigInt(uint32_t row, uint32_t column, const void* value, size_t size) +int SharedBlock::PutBigInt(uint32_t row, uint32_t column, const void *value, size_t size) { return PutBlobOrString(row, column, value, size, CELL_UNIT_TYPE_BIGINT); } @@ -305,8 +305,8 @@ int SharedBlock::PutBlobOrString(uint32_t row, uint32_t column, const void *valu { if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" - " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", - row, column, mHeader->rowNums, mHeader->columnNums); + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + row, column, mHeader->rowNums, mHeader->columnNums); return SHARED_BLOCK_BAD_VALUE; } uint32_t groupPos = row / ROW_NUM_IN_A_GROUP; @@ -337,8 +337,8 @@ int SharedBlock::PutLong(uint32_t row, uint32_t column, int64_t value) { if (UNLIKELY(row >= mHeader->rowNums || column >= mHeader->columnNums)) { LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" - " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", - row, column, mHeader->rowNums, mHeader->columnNums); + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + row, column, mHeader->rowNums, mHeader->columnNums); return SHARED_BLOCK_BAD_VALUE; } @@ -409,23 +409,23 @@ size_t SharedBlock::SetRawData(const void *rawData, size_t size) std::string SharedBlock::CellUnit::GetString(SharedBlock *block) const { - auto value = static_cast(block->OffsetToPtr(cell.stringOrBlobValue.offset, cell.stringOrBlobValue.size)); + auto value = static_cast(block->OffsetToPtr(cell.stringOrBlobValue.offset, cell.stringOrBlobValue.size)); if (cell.stringOrBlobValue.size < 1 || value == nullptr) { return ""; } return value; } -std::vector SharedBlock::CellUnit::GetBlob(SharedBlock* block) const +std::vector SharedBlock::CellUnit::GetBlob(SharedBlock *block) const { - auto value = reinterpret_cast(block->OffsetToPtr(cell.stringOrBlobValue.offset, - cell.stringOrBlobValue.size)); + auto value = + reinterpret_cast(block->OffsetToPtr(cell.stringOrBlobValue.offset, cell.stringOrBlobValue.size)); return std::vector(value, value + cell.stringOrBlobValue.size); } -const uint8_t* SharedBlock::CellUnit::GetRawData(SharedBlock* block) const +const uint8_t *SharedBlock::CellUnit::GetRawData(SharedBlock *block) const { - return static_cast(block->OffsetToPtr(cell.stringOrBlobValue.offset, cell.stringOrBlobValue.size)); + return static_cast(block->OffsetToPtr(cell.stringOrBlobValue.offset, cell.stringOrBlobValue.size)); } } // namespace AppDataFwk } // namespace OHOS diff --git a/relational_store/frameworks/native/cloud_data/include/cloud_service_proxy.h b/relational_store/frameworks/native/cloud_data/include/cloud_service_proxy.h index 6fef7cf577a23c20e6ab249ef02f72b6d7ca80c0..780c5dd2b1cb1a4b53a7659f5be62cd55dff8afd 100644 --- a/relational_store/frameworks/native/cloud_data/include/cloud_service_proxy.h +++ b/relational_store/frameworks/native/cloud_data/include/cloud_service_proxy.h @@ -31,26 +31,25 @@ public: int32_t Clean(const std::string &id, const std::map &actions) override; int32_t NotifyDataChange(const std::string &id, const std::string &bundleName) override; int32_t NotifyDataChange(const std::string &eventId, const std::string &extraData, int32_t userId) override; - std::pair> QueryStatistics(const std::string& id, - const std::string& bundleName, const std::string& storeId) override; - int32_t SetGlobalCloudStrategy(Strategy strategy, const std::vector& values) override; + std::pair> QueryStatistics( + const std::string &id, const std::string &bundleName, const std::string &storeId) override; + int32_t SetGlobalCloudStrategy(Strategy strategy, const std::vector &values) override; - std::pair> AllocResourceAndShare(const std::string& storeId, - const DistributedRdb::PredicatesMemo& predicates, const std::vector& columns, - const Participants& participants) override; + std::pair> AllocResourceAndShare(const std::string &storeId, + const DistributedRdb::PredicatesMemo &predicates, const std::vector &columns, + const Participants &participants) override; int32_t Share(const std::string &sharingRes, const Participants &participants, Results &results) override; int32_t Unshare(const std::string &sharingRes, const Participants &participants, Results &results) override; int32_t Exit(const std::string &sharingRes, std::pair &result) override; - int32_t ChangePrivilege( - const std::string &sharingRes, const Participants &participants, Results &results) override; + int32_t ChangePrivilege(const std::string &sharingRes, const Participants &participants, Results &results) override; int32_t Query(const std::string &sharingRes, QueryResults &results) override; int32_t QueryByInvitation(const std::string &invitation, QueryResults &results) override; - int32_t ConfirmInvitation(const std::string &invitation, - int32_t confirmation, std::tuple &result) override; - int32_t ChangeConfirmation(const std::string &sharingRes, - int32_t confirmation, std::pair &result) override; + int32_t ConfirmInvitation(const std::string &invitation, int32_t confirmation, + std::tuple &result) override; + int32_t ChangeConfirmation( + const std::string &sharingRes, int32_t confirmation, std::pair &result) override; - int32_t SetCloudStrategy(Strategy strategy, const std::vector& values) override; + int32_t SetCloudStrategy(Strategy strategy, const std::vector &values) override; std::pair QueryLastSyncInfo( const std::string &id, const std::string &bundleName, const std::string &storeId) override; diff --git a/relational_store/frameworks/native/cloud_data/include/cloud_types_util.h b/relational_store/frameworks/native/cloud_data/include/cloud_types_util.h index 50b0b2907afde1ad8eea3f7f5b48df507d5dbc22..e0ab11dd7b760b6791054e9723b9592ebcc8835d 100644 --- a/relational_store/frameworks/native/cloud_data/include/cloud_types_util.h +++ b/relational_store/frameworks/native/cloud_data/include/cloud_types_util.h @@ -15,10 +15,10 @@ #ifndef OHOS_DISTRIBUTED_DATA_CLOUD_CLOUD_TYPES_UTIL_H #define OHOS_DISTRIBUTED_DATA_CLOUD_CLOUD_TYPES_UTIL_H -#include "itypes_util.h" #include "cloud_types.h" -#include "values_bucket.h" #include "common_types.h" +#include "itypes_util.h" +#include "values_bucket.h" namespace OHOS::ITypesUtil { using Participant = OHOS::CloudData::Participant; diff --git a/relational_store/frameworks/native/cloud_data/include/icloud_service.h b/relational_store/frameworks/native/cloud_data/include/icloud_service.h index fe6c3e546e2d3afe1953f2f97e55eef6ff8c8ccc..25d266edbf5122b1a3d985d0aa77c8e5a1632e80 100644 --- a/relational_store/frameworks/native/cloud_data/include/icloud_service.h +++ b/relational_store/frameworks/native/cloud_data/include/icloud_service.h @@ -17,8 +17,8 @@ #define OHOS_DISTRIBUTED_DATA_CLOUD_ICLOUD_SERVICE_H #include "cloud_service.h" -#include "iremote_broker.h" #include "distributeddata_relational_store_ipc_interface_code.h" +#include "iremote_broker.h" namespace OHOS::CloudData { class ICloudService : public CloudService, public IRemoteBroker { diff --git a/relational_store/frameworks/native/cloud_data/src/cloud_manager.cpp b/relational_store/frameworks/native/cloud_data/src/cloud_manager.cpp index 020e01062118774abced40f8e01aa79cd08a968b..832f4903097cdda68bb70590934f939eb0ef58e1 100644 --- a/relational_store/frameworks/native/cloud_data/src/cloud_manager.cpp +++ b/relational_store/frameworks/native/cloud_data/src/cloud_manager.cpp @@ -35,7 +35,7 @@ public: class CloudDeath : public IRemoteObject::DeathRecipient { public: - explicit CloudDeath(std::function action) : action_(std::move(action)){}; + explicit CloudDeath(std::function action) : action_(std::move(action)) {}; void OnRemoteDied(const wptr &object) override { if (action_) { diff --git a/relational_store/frameworks/native/cloud_data/src/cloud_service_proxy.cpp b/relational_store/frameworks/native/cloud_data/src/cloud_service_proxy.cpp index f432e1a22e096140d7dd6e6acee715d896bf1811..b68ad90ee72aec0eb6eed6bc162655e2a7c236cc 100644 --- a/relational_store/frameworks/native/cloud_data/src/cloud_service_proxy.cpp +++ b/relational_store/frameworks/native/cloud_data/src/cloud_service_proxy.cpp @@ -21,30 +21,30 @@ namespace OHOS::CloudData { using namespace OHOS::Rdb; -#define IPC_SEND(code, reply, ...) \ -({ \ - int32_t __status = SUCCESS; \ - do { \ - MessageParcel request; \ - if (!request.WriteInterfaceToken(GetDescriptor())) { \ - __status = IPC_PARCEL_ERROR; \ - break; \ - } \ - if (!ITypesUtil::Marshal(request, ##__VA_ARGS__)) { \ - __status = IPC_PARCEL_ERROR; \ - break; \ - } \ - MessageOption option; \ - auto result = remote_->SendRequest((code), request, reply, option); \ - if (result != 0) { \ - __status = IPC_ERROR; \ - break; \ - } \ - \ - ITypesUtil::Unmarshal(reply, __status); \ - } while (0); \ - __status; \ -}) +#define IPC_SEND(code, reply, ...) \ + ({ \ + int32_t __status = SUCCESS; \ + do { \ + MessageParcel request; \ + if (!request.WriteInterfaceToken(GetDescriptor())) { \ + __status = IPC_PARCEL_ERROR; \ + break; \ + } \ + if (!ITypesUtil::Marshal(request, ##__VA_ARGS__)) { \ + __status = IPC_PARCEL_ERROR; \ + break; \ + } \ + MessageOption option; \ + auto result = remote_->SendRequest((code), request, reply, option); \ + if (result != 0) { \ + __status = IPC_ERROR; \ + break; \ + } \ + \ + ITypesUtil::Unmarshal(reply, __status); \ + } while (0); \ + __status; \ + }) CloudServiceProxy::CloudServiceProxy(const sptr &object) : IRemoteProxy(object) @@ -77,8 +77,8 @@ int32_t CloudServiceProxy::ChangeAppSwitch(const std::string &id, const std::str MessageParcel reply; int32_t status = IPC_SEND(TRANS_CHANGE_APP_SWITCH, reply, id, bundleName, appSwitch); if (status != SUCCESS) { - LOG_ERROR("status:0x%{public}x id:%{public}.6s bundleName:%{public}s switch:%{public}d", - status, id.c_str(), bundleName.c_str(), appSwitch); + LOG_ERROR("status:0x%{public}x id:%{public}.6s bundleName:%{public}s switch:%{public}d", status, id.c_str(), + bundleName.c_str(), appSwitch); } return static_cast(status); } @@ -139,41 +139,39 @@ int32_t CloudServiceProxy::NotifyDataChange(const std::string &eventId, const st return static_cast(status); } -std::pair> CloudServiceProxy::QueryStatistics(const std::string &id, - const std::string &bundleName, const std::string &storeId) +std::pair> CloudServiceProxy::QueryStatistics( + const std::string &id, const std::string &bundleName, const std::string &storeId) { MessageParcel reply; int32_t status = IPC_SEND(TRANS_QUERY_STATISTICS, reply, id, bundleName, storeId); if (status != SUCCESS) { - LOG_ERROR("status:0x%{public}x bundleName:%{public}.6s storeId:%{public}.6s", status, id.c_str(), - storeId.c_str()); + LOG_ERROR( + "status:0x%{public}x bundleName:%{public}.6s storeId:%{public}.6s", status, id.c_str(), storeId.c_str()); } std::map infos; ITypesUtil::Unmarshal(reply, infos); return { status, infos }; } -int32_t CloudServiceProxy::Share( - const std::string &sharingRes, const Participants &participants, Results &results) +int32_t CloudServiceProxy::Share(const std::string &sharingRes, const Participants &participants, Results &results) { MessageParcel reply; int32_t status = IPC_SEND(TRANS_SHARE, reply, sharingRes, participants); if (status != SUCCESS) { - LOG_ERROR("status:0x%{public}x sharingRes:%{public}.6s participants:%{public}zu", - status, sharingRes.c_str(), participants.size()); + LOG_ERROR("status:0x%{public}x sharingRes:%{public}.6s participants:%{public}zu", status, sharingRes.c_str(), + participants.size()); } ITypesUtil::Unmarshal(reply, results); return static_cast(status); } -int32_t CloudServiceProxy::Unshare( - const std::string &sharingRes, const Participants &participants, Results &results) +int32_t CloudServiceProxy::Unshare(const std::string &sharingRes, const Participants &participants, Results &results) { MessageParcel reply; int32_t status = IPC_SEND(TRANS_UNSHARE, reply, sharingRes, participants); if (status != SUCCESS) { - LOG_ERROR("status:0x%{public}x sharingRes:%{public}.6s participants:%{public}zu", - status, sharingRes.c_str(), participants.size()); + LOG_ERROR("status:0x%{public}x sharingRes:%{public}.6s participants:%{public}zu", status, sharingRes.c_str(), + participants.size()); } ITypesUtil::Unmarshal(reply, results); return static_cast(status); @@ -196,8 +194,8 @@ int32_t CloudServiceProxy::ChangePrivilege( MessageParcel reply; int32_t status = IPC_SEND(TRANS_CHANGE_PRIVILEGE, reply, sharingRes, participants); if (status != SUCCESS) { - LOG_ERROR("status:0x%{public}x sharingRes:%{public}.6s participants:%{public}zu", - status, sharingRes.c_str(), participants.size()); + LOG_ERROR("status:0x%{public}x sharingRes:%{public}.6s participants:%{public}zu", status, sharingRes.c_str(), + participants.size()); } ITypesUtil::Unmarshal(reply, results); return static_cast(status); @@ -214,8 +212,7 @@ int32_t CloudServiceProxy::Query(const std::string &sharingRes, QueryResults &re return static_cast(status); } -int32_t CloudServiceProxy::QueryByInvitation( - const std::string &invitation, QueryResults &results) +int32_t CloudServiceProxy::QueryByInvitation(const std::string &invitation, QueryResults &results) { MessageParcel reply; int32_t status = IPC_SEND(TRANS_QUERY_BY_INVITATION, reply, invitation); @@ -226,8 +223,8 @@ int32_t CloudServiceProxy::QueryByInvitation( return static_cast(status); } -int32_t CloudServiceProxy::ConfirmInvitation(const std::string &invitation, - int32_t confirmation, std::tuple &result) +int32_t CloudServiceProxy::ConfirmInvitation( + const std::string &invitation, int32_t confirmation, std::tuple &result) { MessageParcel reply; int32_t status = IPC_SEND(TRANS_CONFIRM_INVITATION, reply, invitation, confirmation); @@ -238,8 +235,8 @@ int32_t CloudServiceProxy::ConfirmInvitation(const std::string &invitation, return static_cast(status); } -int32_t CloudServiceProxy::ChangeConfirmation(const std::string &sharingRes, - int32_t confirmation, std::pair &result) +int32_t CloudServiceProxy::ChangeConfirmation( + const std::string &sharingRes, int32_t confirmation, std::pair &result) { MessageParcel reply; int32_t status = IPC_SEND(TRANS_CHANGE_CONFIRMATION, reply, sharingRes, confirmation); @@ -274,4 +271,4 @@ std::pair CloudServiceProxy::QueryLastSyncInfo( ITypesUtil::Unmarshal(reply, results); return { status, results }; } -} // namespace OHOS::CloudData \ No newline at end of file +} // namespace OHOS::CloudData diff --git a/relational_store/frameworks/native/cloud_data/src/cloud_types_util.cpp b/relational_store/frameworks/native/cloud_data/src/cloud_types_util.cpp index 083ac7ad30f3055b95bb604512287de2bbeebf02..0b72056e5ccb77092ba8592bda35662aa1dcd1ac 100644 --- a/relational_store/frameworks/native/cloud_data/src/cloud_types_util.cpp +++ b/relational_store/frameworks/native/cloud_data/src/cloud_types_util.cpp @@ -19,29 +19,26 @@ namespace OHOS::ITypesUtil { template<> bool Marshalling(const Participant &input, MessageParcel &data) { - return ITypesUtil::Marshal( - data, input.identity, input.role, input.state, input.privilege, input.attachInfo); + return ITypesUtil::Marshal(data, input.identity, input.role, input.state, input.privilege, input.attachInfo); } template<> bool Unmarshalling(Participant &output, MessageParcel &data) { - return ITypesUtil::Unmarshal( - data, output.identity, output.role, output.state, output.privilege, output.attachInfo); + return ITypesUtil::Unmarshal(data, output.identity, output.role, output.state, output.privilege, output.attachInfo); } template<> bool Marshalling(const Privilege &input, MessageParcel &data) { - return ITypesUtil::Marshal(data, input.writable, input.readable, - input.creatable, input.deletable, input.shareable); + return ITypesUtil::Marshal(data, input.writable, input.readable, input.creatable, input.deletable, input.shareable); } template<> bool Unmarshalling(Privilege &output, MessageParcel &data) { - return ITypesUtil::Unmarshal(data, output.writable, output.readable, - output.creatable, output.deletable, output.shareable); + return ITypesUtil::Unmarshal( + data, output.writable, output.readable, output.creatable, output.deletable, output.shareable); } template<> @@ -71,8 +68,7 @@ template<> bool Unmarshalling(Confirmation &output, MessageParcel &data) { int32_t result; - if (!data.ReadInt32(result) || result < Confirmation::CFM_NIL || - result >= Confirmation::CFM_BUTT) { + if (!data.ReadInt32(result) || result < Confirmation::CFM_NIL || result >= Confirmation::CFM_BUTT) { return false; } output = static_cast(result); @@ -142,8 +138,8 @@ bool Marshalling(const Strategy &input, MessageParcel &data) template<> bool Marshalling(const CommonAsset &input, MessageParcel &data) { - return ITypesUtil::Marshal(data, input.name, input.uri, input.path, input.createTime, - input.modifyTime, input.size, input.status, input.hash); + return ITypesUtil::Marshal(data, input.name, input.uri, input.path, input.createTime, input.modifyTime, input.size, + input.status, input.hash); } template<> diff --git a/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp b/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp index 75489df29fcd7140b575628a1ad8c8cc4df7a6a2..bc436cbbc0861f0977a0763ae978c754bd3b268a 100644 --- a/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp +++ b/relational_store/frameworks/native/dataability/src/data_ability_predicates.cpp @@ -106,7 +106,7 @@ bool DataAbilityPredicates::Marshalling(OHOS::Parcel &parcel) const /** * Read from Parcel object. */ -DataAbilityPredicates* DataAbilityPredicates::Unmarshalling(OHOS::Parcel &parcel) +DataAbilityPredicates *DataAbilityPredicates::Unmarshalling(OHOS::Parcel &parcel) { result = true; return new DataAbilityPredicates(&parcel); @@ -134,4 +134,4 @@ void DataAbilityPredicates::MarshallingStringList(std::vector list, DataAbilityPredicates::~DataAbilityPredicates() {} } // namespace NativeRdb -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set.cpp b/relational_store/frameworks/native/dataability/src/ishared_result_set.cpp index 3491f69573ffb6a3c740e9da3ba4e5a5ce9658bf..48098b9bab66a278ba693a49af400b870f7251db 100644 --- a/relational_store/frameworks/native/dataability/src/ishared_result_set.cpp +++ b/relational_store/frameworks/native/dataability/src/ishared_result_set.cpp @@ -21,8 +21,8 @@ std::shared_ptr ISharedResultSet::ReadFromParcel(MessageParc return consumerCreator_(parcel); } -sptr ISharedResultSet::WriteToParcel(std::shared_ptr resultSet, - MessageParcel &parcel) +sptr ISharedResultSet::WriteToParcel( + std::shared_ptr resultSet, MessageParcel &parcel) { return providerCreator_(std::move(resultSet), parcel); } diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.cpp b/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.cpp index 8d572ed23142632bbf5d70eb45b0dacc74c21c87..45e70bf4228988191a475372340807b7db7b6b97 100644 --- a/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.cpp +++ b/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.cpp @@ -45,7 +45,7 @@ std::shared_ptr ISharedResultSetProxy::CreateProxy(MessagePa AppDataFwk::SharedBlock::ReadMessageParcel(parcel, block); result->SetBlock(block); } - return std::shared_ptr(result.GetRefPtr(), [keep = result] (AbsSharedResultSet *) {}); + return std::shared_ptr(result.GetRefPtr(), [keep = result](AbsSharedResultSet *) {}); } int ISharedResultSetProxy::GetRowCount(int &count) @@ -59,8 +59,8 @@ int ISharedResultSetProxy::GetRowCount(int &count) request.WriteInterfaceToken(GetDescriptor()); MessageParcel reply; MessageOption msgOption; - int errCode = Remote()->SendRequest( - static_cast(ResultSetCode::FUNC_GET_ROW_COUNT), request, reply, msgOption); + int errCode = + Remote()->SendRequest(static_cast(ResultSetCode::FUNC_GET_ROW_COUNT), request, reply, msgOption); if (errCode != 0) { LOG_ERROR("GetRowCount IPC Error %{public}x", errCode); return -errCode; @@ -119,17 +119,17 @@ std::pair> ISharedResultSetProxy::GetColumnNames() static_cast(ResultSetCode::FUNC_GET_ALL_COLUMN_NAMES), request, reply, msgOption); if (errCode != 0) { LOG_ERROR("GetAllColumnNames IPC Error %{public}x", errCode); - return {-errCode, {}}; + return { -errCode, {} }; } errCode = reply.ReadInt32(); if (errCode != E_OK) { LOG_ERROR("GetAllColumnNames Reply Error %{public}d", errCode); - return {errCode, {}}; + return { errCode, {} }; } std::vector colNames; if (!reply.ReadStringVector(&colNames)) { - return {E_INVALID_PARCEL, {}}; + return { E_INVALID_PARCEL, {} }; } - return {errCode, std::move(colNames)}; + return { errCode, std::move(colNames) }; } -} // namespace OHOS::NativeRdb \ No newline at end of file +} // namespace OHOS::NativeRdb diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.h b/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.h index dc1dae85b7e464ce29d92db509fb868323840f1b..fcf28af96cd1004c6f936c55a85078da91564f17 100644 --- a/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.h +++ b/relational_store/frameworks/native/dataability/src/ishared_result_set_proxy.h @@ -17,8 +17,8 @@ #define DATAABILITY_I_SHARED_RESULT_SET_PROXY_H #include -#include "ishared_result_set.h" #include "iremote_proxy.h" +#include "ishared_result_set.h" #include "rdb_errno.h" namespace OHOS::NativeRdb { @@ -38,5 +38,5 @@ private: static BrokerDelegator delegator_; int32_t rowCount_ = -1; }; -} +} // namespace OHOS::NativeRdb #endif // DATAABILITY_I_SHARED_RESULT_SET_PROXY_H diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.cpp b/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.cpp index 85ae11e3f9a857d0ec2f11ccd34b9e266c233430..23a5c5d488a46819084b9d2fde4ba39d25001dfd 100644 --- a/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.cpp +++ b/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.cpp @@ -23,12 +23,12 @@ namespace OHOS::NativeRdb { using namespace OHOS::Rdb; -std::function(std::shared_ptr, - MessageParcel &)> ISharedResultSet::providerCreator_ = ISharedResultSetStub::CreateStub; +std::function(std::shared_ptr, MessageParcel &)> + ISharedResultSet::providerCreator_ = ISharedResultSetStub::CreateStub; constexpr ISharedResultSetStub::Handler ISharedResultSetStub::handlers[static_cast(ResultSetCode::FUNC_BUTT)]; -sptr ISharedResultSetStub::CreateStub(std::shared_ptr result, - OHOS::MessageParcel &parcel) +sptr ISharedResultSetStub::CreateStub( + std::shared_ptr result, OHOS::MessageParcel &parcel) { sptr stub = new (std::nothrow) ISharedResultSetStub(result); if (stub == nullptr) { @@ -55,8 +55,8 @@ ISharedResultSetStub::~ISharedResultSetStub() { } -int ISharedResultSetStub::OnRemoteRequest(uint32_t code, OHOS::MessageParcel &data, - OHOS::MessageParcel &reply, OHOS::MessageOption &option) +int ISharedResultSetStub::OnRemoteRequest( + uint32_t code, OHOS::MessageParcel &data, OHOS::MessageParcel &reply, OHOS::MessageOption &option) { if (GetDescriptor() != data.ReadInterfaceToken()) { LOG_ERROR("IPC descriptor is not equal."); diff --git a/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.h b/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.h index ace86d935ed8078eb802815a5d71c0c13d31623a..e0a484ee9d30c5f3250bb142492aa7377f7293c6 100644 --- a/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.h +++ b/relational_store/frameworks/native/dataability/src/ishared_result_set_stub.h @@ -17,9 +17,10 @@ #define DATAABILITY_I_SHARED_RESULT_SET_STUB_H #include #include -#include "safe_block_queue.h" -#include "ishared_result_set.h" + #include "iremote_stub.h" +#include "ishared_result_set.h" +#include "safe_block_queue.h" namespace OHOS::NativeRdb { using ResultSetCode = OHOS::DistributedRdb::RelationalStore::IResultSetInterfaceCode; @@ -39,9 +40,9 @@ protected: int HandleCloseRequest(MessageParcel &data, MessageParcel &reply); private: - using Handler = int(ISharedResultSetStub::*)(MessageParcel &request, MessageParcel &reply); + using Handler = int (ISharedResultSetStub::*)(MessageParcel &request, MessageParcel &reply); std::shared_ptr resultSet_; - static constexpr Handler handlers[static_cast(ResultSetCode::FUNC_BUTT)] { + static constexpr Handler handlers[static_cast(ResultSetCode::FUNC_BUTT)]{ &ISharedResultSetStub::HandleGetRowCountRequest, &ISharedResultSetStub::HandleGetColumnNamesRequest, &ISharedResultSetStub::HandleOnGoRequest, diff --git a/relational_store/frameworks/native/dataability/src/predicates_utils.cpp b/relational_store/frameworks/native/dataability/src/predicates_utils.cpp index 22f042997b9733bcc9e8e0d892764cb10f394da1..b96184394b929be95c5ceceb43321d45857e3295 100644 --- a/relational_store/frameworks/native/dataability/src/predicates_utils.cpp +++ b/relational_store/frameworks/native/dataability/src/predicates_utils.cpp @@ -36,8 +36,8 @@ void PredicatesUtils::SetWhereClauseAndArgs( /** * Set the param of whereClause and bindArgs of the specified Predicates. */ -void PredicatesUtils::SetWhereClauseAndArgs(AbsPredicates *predicates, const std::string &whereClause, - const std::vector &bindArgs) +void PredicatesUtils::SetWhereClauseAndArgs( + AbsPredicates *predicates, const std::string &whereClause, const std::vector &bindArgs) { predicates->SetWhereClause(whereClause); predicates->SetBindArgs(bindArgs); diff --git a/relational_store/frameworks/native/dfx/include/rdb_fault_hiview_reporter.h b/relational_store/frameworks/native/dfx/include/rdb_fault_hiview_reporter.h index f572251a6fb44a0635ee17e29216e3a028bae400..47a12e8c54d515fd41dd586180026d4c7017cf89 100644 --- a/relational_store/frameworks/native/dfx/include/rdb_fault_hiview_reporter.h +++ b/relational_store/frameworks/native/dfx/include/rdb_fault_hiview_reporter.h @@ -16,12 +16,13 @@ #ifndef DISTRIBUTEDDATAMGR_RDB_FAULT_HIVIEW_REPORTER_H #define DISTRIBUTEDDATAMGR_RDB_FAULT_HIVIEW_REPORTER_H -#include #include -#include #include #include +#include +#include + #include "connection.h" #include "rdb_store_config.h" #include "rdb_types.h" diff --git a/relational_store/frameworks/native/dfx/include/rdb_radar_reporter.h b/relational_store/frameworks/native/dfx/include/rdb_radar_reporter.h index dcf93e3abcde8a6e31de5ae822c12146ad22a1ac..c2612dc876c4502175594b99450bb073ad197376 100644 --- a/relational_store/frameworks/native/dfx/include/rdb_radar_reporter.h +++ b/relational_store/frameworks/native/dfx/include/rdb_radar_reporter.h @@ -16,8 +16,8 @@ #ifndef DISTRIBUTEDDATAMGR_RDB_RADAR_REPORTER_H #define DISTRIBUTEDDATAMGR_RDB_RADAR_REPORTER_H -#include #include +#include namespace OHOS::NativeRdb { enum Scene : int { @@ -52,7 +52,7 @@ public: private: int errCode_{ 0 }; Scene scene_; - const char* funcName_; + const char *funcName_; std::string bundleName_; static std::string hostPkg_; diff --git a/relational_store/frameworks/native/dfx/src/rdb_fault_hiview_reporter.cpp b/relational_store/frameworks/native/dfx/src/rdb_fault_hiview_reporter.cpp index 168dbdef718cb9e3ddedbbe8745db7ef69c80415..ffa2caa9bdace40d8d1252fca0ffce7541cd4f52 100644 --- a/relational_store/frameworks/native/dfx/src/rdb_fault_hiview_reporter.cpp +++ b/relational_store/frameworks/native/dfx/src/rdb_fault_hiview_reporter.cpp @@ -16,23 +16,24 @@ #include "rdb_fault_hiview_reporter.h" -#include -#include - -#include #include #include -#include + +#include #include +#include #include +#include +#include + +#include "accesstoken_kit.h" #include "connection.h" #include "hisysevent_c.h" +#include "ipc_skeleton.h" #include "logger.h" #include "rdb_errno.h" #include "sqlite_global_config.h" #include "sqlite_utils.h" -#include "ipc_skeleton.h" -#include "accesstoken_kit.h" namespace OHOS::NativeRdb { using namespace OHOS::Rdb; @@ -52,8 +53,7 @@ void RdbFaultHiViewReporter::ReportFault(const RdbCorruptedEvent &eventInfo) RdbCorruptedEvent eventInfoAppend = eventInfo; eventInfoAppend.appendix += Format(eventInfoAppend.debugInfos, ""); LOG_WARN("corrupted %{public}s errCode:0x%{public}x [%{public}s]", - SqliteUtils::Anonymous(eventInfoAppend.storeName).c_str(), - eventInfoAppend.errorCode, + SqliteUtils::Anonymous(eventInfoAppend.storeName).c_str(), eventInfoAppend.errorCode, eventInfoAppend.appendix.c_str()); Report(eventInfoAppend); CreateCorruptedFlag(eventInfo.path); @@ -108,12 +108,7 @@ std::string RdbFaultHiViewReporter::GetFileStatInfo(const DebugInfo &debugInfo) if (debugInfo.inode_ != debugInfo.oldInode_ && debugInfo.oldInode_ != 0) { oss << "<>0x" << std::hex << debugInfo.oldInode_; } - auto tokenId = IPCSkeleton::GetCallingTokenID(); - NativeTokenInfo tokenInfo; - AccessTokenKit::GetNativeTokenInfo(tokenId, tokenInfo); oss << " mode:0" << std::oct << (debugInfo.mode_ & permission) << " size:" << std::dec << debugInfo.size_ - << " uid:" << std::dec << debugInfo.uid_ << " gid:" << std::dec << debugInfo.gid_ - << " process:" << tokenInfo.processName << " atim:" << GetTimeWithMilliseconds(debugInfo.atime_.sec_, debugInfo.atime_.nsec_) << " mtim:" << GetTimeWithMilliseconds(debugInfo.mtime_.sec_, debugInfo.mtime_.nsec_) << " ctim:" << GetTimeWithMilliseconds(debugInfo.ctime_.sec_, debugInfo.ctime_.nsec_); @@ -172,8 +167,8 @@ std::string RdbFaultHiViewReporter::GetTimeWithMilliseconds(time_t sec, int64_t return oss.str(); } -RdbCorruptedEvent RdbFaultHiViewReporter::Create(const RdbStoreConfig &config, int32_t errCode, - const std::string &appendix) +RdbCorruptedEvent RdbFaultHiViewReporter::Create( + const RdbStoreConfig &config, int32_t errCode, const std::string &appendix) { RdbCorruptedEvent eventInfo; eventInfo.bundleName = config.GetBundleName(); @@ -233,9 +228,12 @@ std::string RdbFaultHiViewReporter::GetBundleName(const RdbCorruptedEvent &event return eventInfo.bundleName; } auto tokenId = IPCSkeleton::GetCallingTokenID(); - NativeTokenInfo tokenInfo; - if (AccessTokenKit::GetNativeTokenInfo(tokenId, tokenInfo) == 0) { - return tokenInfo.processName; + auto tokenType = AccessTokenKit::GetTokenTypeFlag(tokenId); + if ((tokenType == TOKEN_NATIVE) || (tokenType == TOKEN_SHELL)) { + NativeTokenInfo tokenInfo; + if (AccessTokenKit::GetNativeTokenInfo(tokenId, tokenInfo) == 0) { + return tokenInfo.processName; + } } return SqliteUtils::Anonymous(eventInfo.storeName); } @@ -252,8 +250,8 @@ std::string RdbFaultHiViewReporter::Format(const std::map &debugs, - const std::string &header) +std::string RdbFaultHiViewReporter::FormatBrief( + const std::map &debugs, const std::string &header) { if (debugs.empty()) { return ""; diff --git a/relational_store/frameworks/native/dfx/src/rdb_radar_reporter.cpp b/relational_store/frameworks/native/dfx/src/rdb_radar_reporter.cpp index cde821359d255100912876a969fe19a14e62b372..8e872841d37618cdd32183f40f1e4fa12b4923d6 100644 --- a/relational_store/frameworks/native/dfx/src/rdb_radar_reporter.cpp +++ b/relational_store/frameworks/native/dfx/src/rdb_radar_reporter.cpp @@ -14,19 +14,20 @@ */ #include "rdb_radar_reporter.h" -#include "rdb_errno.h" -#include "ipc_skeleton.h" + #include "accesstoken_kit.h" #include "hisysevent_c.h" +#include "ipc_skeleton.h" +#include "rdb_errno.h" namespace OHOS::NativeRdb { using namespace Security::AccessToken; -static constexpr const char* ORG_PKG_VALUE = "distributeddata"; -static constexpr const char* EVENT_NAME = "DISTRIBUTED_RDB_BEHAVIOR"; -static constexpr const char* UNKNOW = "unknow"; -static constexpr const char* DISTRIBUTED_DATAMGR = "DISTDATAMGR"; +static constexpr const char *ORG_PKG_VALUE = "distributeddata"; +static constexpr const char *EVENT_NAME = "DISTRIBUTED_RDB_BEHAVIOR"; +static constexpr const char *UNKNOW = "unknow"; +static constexpr const char *DISTRIBUTED_DATAMGR = "DISTDATAMGR"; std::string RdbRadar::hostPkg_{ "" }; std::mutex RdbRadar::mutex_; @@ -45,7 +46,7 @@ RdbRadar::~RdbRadar() LocalReport(scene_, funcName_, STATE_FINISH, errCode_); } -RdbRadar& RdbRadar::operator=(int errCode) +RdbRadar &RdbRadar::operator=(int errCode) { errCode_ = errCode; return *this; @@ -56,7 +57,7 @@ RdbRadar::operator int() const return errCode_; } -void RdbRadar::LocalReport(int bizSence, const char* funcName, int state, int errCode) +void RdbRadar::LocalReport(int bizSence, const char *funcName, int state, int errCode) { int stageRes = static_cast(StageRes::RES_SUCCESS); if (errCode != E_OK) { @@ -79,8 +80,8 @@ void RdbRadar::LocalReport(int bizSence, const char* funcName, int state, int er {.name = "HOST_PKG", .t = HISYSEVENT_STRING, .v = { .s = hostPkgPtr }, .arraySize = 0, }, }; - OH_HiSysEvent_Write(DISTRIBUTED_DATAMGR, EVENT_NAME, - HISYSEVENT_BEHAVIOR, params, sizeof(params) / sizeof(params[0])); + OH_HiSysEvent_Write( + DISTRIBUTED_DATAMGR, EVENT_NAME, HISYSEVENT_BEHAVIOR, params, sizeof(params) / sizeof(params[0])); return; } @@ -102,4 +103,4 @@ std::string RdbRadar::GetHostPkgInfo() } return hostPkg_; } -} \ No newline at end of file +} // namespace OHOS::NativeRdb diff --git a/relational_store/frameworks/native/rdb/include/connection.h b/relational_store/frameworks/native/rdb/include/connection.h index 7cb1291a626136a3ee2b4e2702dc85c7eb1c0862..2da6c5b94a2e186d5dd8109bb0d3a10561131da9 100644 --- a/relational_store/frameworks/native/rdb/include/connection.h +++ b/relational_store/frameworks/native/rdb/include/connection.h @@ -66,14 +66,14 @@ public: virtual int32_t GetMaxVariable() const = 0; virtual int32_t GetJournalMode() = 0; virtual int32_t ClearCache() = 0; - virtual int32_t Subscribe(const std::string &event, - const std::shared_ptr &observer) = 0; - virtual int32_t Unsubscribe(const std::string &event, - const std::shared_ptr &observer) = 0; - virtual int32_t Backup(const std::string &databasePath, const std::vector &destEncryptKey, - bool isAsync, SlaveStatus &slaveStatus) = 0; - virtual int32_t Restore(const std::string &databasePath, const std::vector &destEncryptKey, + virtual int32_t Subscribe( + const std::string &event, const std::shared_ptr &observer) = 0; + virtual int32_t Unsubscribe( + const std::string &event, const std::shared_ptr &observer) = 0; + virtual int32_t Backup(const std::string &databasePath, const std::vector &destEncryptKey, bool isAsync, SlaveStatus &slaveStatus) = 0; + virtual int32_t Restore( + const std::string &databasePath, const std::vector &destEncryptKey, SlaveStatus &slaveStatus) = 0; virtual ExchangeStrategy GenerateExchangeStrategy(const SlaveStatus &status) = 0; private: diff --git a/relational_store/frameworks/native/rdb/include/connection_pool.h b/relational_store/frameworks/native/rdb/include/connection_pool.h index 231627df2a01f6e174174f26f7df473cfd56ba63..9e82a7313bcab2b80980e213f63b59207ff4aae8 100644 --- a/relational_store/frameworks/native/rdb/include/connection_pool.h +++ b/relational_store/frameworks/native/rdb/include/connection_pool.h @@ -40,8 +40,8 @@ public: static constexpr std::chrono::milliseconds INVALID_TIME = std::chrono::milliseconds(0); static std::shared_ptr Create(const RdbStoreConfig &config, int &errCode); ~ConnectionPool(); - static std::pair> HandleDataCorruption - (const RdbStoreConfig &storeConfig, int &errCode); + static std::pair> HandleDataCorruption( + const RdbStoreConfig &storeConfig, int &errCode); std::pair> CreateTransConn(bool limited = true); SharedConn AcquireConnection(bool isReadOnly); SharedConn Acquire(bool isReadOnly, std::chrono::milliseconds ms = INVALID_TIME); @@ -96,8 +96,8 @@ private: std::mutex mutex_; std::condition_variable cond_; Creator creator_ = nullptr; - std::pair> Initialize(Creator creator, int32_t max, int32_t timeout, - bool disable, bool acquire = false); + std::pair> Initialize( + Creator creator, int32_t max, int32_t timeout, bool disable, bool acquire = false); int32_t ConfigLocale(const std::string &locale); std::shared_ptr Acquire(std::chrono::milliseconds milliS); std::list> AcquireAll(std::chrono::milliseconds milliS); diff --git a/relational_store/frameworks/native/rdb/include/delay_notify.h b/relational_store/frameworks/native/rdb/include/delay_notify.h index f26f0e073a4c44cab1a8c469bfaaa14e50390e4e..52d9aa7f95ad2d362f834cbc29da66b52f66917f 100644 --- a/relational_store/frameworks/native/rdb/include/delay_notify.h +++ b/relational_store/frameworks/native/rdb/include/delay_notify.h @@ -17,12 +17,13 @@ #define NATIVE_RDB_DELAY_NOTIFY_H #include #include -#include -#include #include +#include #include -#include "rdb_types.h" +#include + #include "executor_pool.h" +#include "rdb_types.h" namespace OHOS::NativeRdb { class DelayNotify { public: @@ -36,6 +37,7 @@ public: void SetAutoSyncInterval(uint32_t autoSyncInterval); void Pause(); void Resume(); + private: static constexpr uint32_t AUTO_SYNC_INTERVAL = 200; static constexpr uint32_t MAX_NOTIFY_INTERVAL = 5000; @@ -61,9 +63,10 @@ class PauseDelayNotify { public: explicit PauseDelayNotify(std::shared_ptr delayNotifier); ~PauseDelayNotify(); + private: static constexpr uint32_t AUTO_SYNC_MAX_INTERVAL = 3000; std::shared_ptr delayNotifier_; }; -} +} // namespace OHOS::NativeRdb #endif // NATIVE_RDB_DELAY_NOTIFY_H \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/include/grd_api_manager.h b/relational_store/frameworks/native/rdb/include/grd_api_manager.h index 8fcb4c071fd3c41831b19ebf468c66185ee6879a..ed7b9d0558f3393445e689644ce050c8fff9b8b3 100644 --- a/relational_store/frameworks/native/rdb/include/grd_api_manager.h +++ b/relational_store/frameworks/native/rdb/include/grd_api_manager.h @@ -53,11 +53,11 @@ typedef int32_t (*DBSqlColInt)(GRD_SqlStmt *stmt, uint32_t idx); typedef int64_t (*DBSqlColInt64)(GRD_SqlStmt *stmt, uint32_t idx); typedef double (*DBSqlColDouble)(GRD_SqlStmt *stmt, uint32_t idx); typedef const float *(*DBSqlColumnFloatVector)(GRD_SqlStmt *stmt, uint32_t idx, uint32_t *dim); -typedef int32_t (*DBBackup) (GRD_DB *db, const char *backupDbFile, GRD_CipherInfoT *cipherInfo); -typedef int32_t (*DBRestore) (const char *dbFile, const char *backupDbFile, GRD_CipherInfoT *cipherInfo); -typedef int32_t (*DBReKey) (const char *dbFile, const char *configStr, GRD_CipherInfoT *cipherInfo); -typedef GRD_DbValueT (*DBGetConfig) (GRD_DB *db, GRD_ConfigTypeE type); -typedef int32_t (*DBSetConfig) (GRD_DB *db, GRD_ConfigTypeE type, GRD_DbValueT value); +typedef int32_t (*DBBackup)(GRD_DB *db, const char *backupDbFile, GRD_CipherInfoT *cipherInfo); +typedef int32_t (*DBRestore)(const char *dbFile, const char *backupDbFile, GRD_CipherInfoT *cipherInfo); +typedef int32_t (*DBReKey)(const char *dbFile, const char *configStr, GRD_CipherInfoT *cipherInfo); +typedef GRD_DbValueT (*DBGetConfig)(GRD_DB *db, GRD_ConfigTypeE type); +typedef int32_t (*DBSetConfig)(GRD_DB *db, GRD_ConfigTypeE type, GRD_DbValueT value); struct GRD_APIInfo { DBOpen DBOpenApi = nullptr; diff --git a/relational_store/frameworks/native/rdb/include/irdb_service.h b/relational_store/frameworks/native/rdb/include/irdb_service.h index 35b30c87ac9893a9a3d2e9d9c35575a849d7bb8f..88682d63373ccbde85e516946a5acb3a972b7c25 100644 --- a/relational_store/frameworks/native/rdb/include/irdb_service.h +++ b/relational_store/frameworks/native/rdb/include/irdb_service.h @@ -18,9 +18,9 @@ #include +#include "distributeddata_relational_store_ipc_interface_code.h" #include "iremote_broker.h" #include "rdb_service.h" -#include "distributeddata_relational_store_ipc_interface_code.h" namespace OHOS::DistributedRdb { class IRdbService : public RdbService, public IRemoteBroker { @@ -36,4 +36,3 @@ public: }; } // namespace OHOS::DistributedRdb #endif - diff --git a/relational_store/frameworks/native/rdb/include/raw_data_parser.h b/relational_store/frameworks/native/rdb/include/raw_data_parser.h index 2f6badddce9261d5e47b8a3ff743c65967ae4dcd..23e4fa7c391ad0f3f186893ea64759b2999273df 100644 --- a/relational_store/frameworks/native/rdb/include/raw_data_parser.h +++ b/relational_store/frameworks/native/rdb/include/raw_data_parser.h @@ -77,6 +77,6 @@ bool RawDataParser::Convert(T input, std::variant &output) { return Get(std::move(input), output); } -} +} // namespace OHOS::NativeRdb #endif // OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_NATIVE_RDB_PARSER_H diff --git a/relational_store/frameworks/native/rdb/include/rd_connection.h b/relational_store/frameworks/native/rdb/include/rd_connection.h index c58dc51d4ba352a66c3d2315b87dea5bc034cca0..cc245395e1fca79526eb2dc8d1e4d420a5692be4 100644 --- a/relational_store/frameworks/native/rdb/include/rd_connection.h +++ b/relational_store/frameworks/native/rdb/include/rd_connection.h @@ -16,13 +16,13 @@ #ifndef NATIVE_RDB_RD_CONNECTION_H #define NATIVE_RDB_RD_CONNECTION_H -#include #include +#include #include +#include "connection.h" #include "rd_utils.h" #include "rdb_common.h" -#include "connection.h" #include "rdb_store_config.h" #include "value_object.h" @@ -32,34 +32,34 @@ namespace NativeRdb { class RdConnection : public Connection { public: - static std::pair> Create(const RdbStoreConfig& config, bool isWrite); - static int32_t Repair(const RdbStoreConfig& config); - static int32_t Delete(const RdbStoreConfig& config); + static std::pair> Create(const RdbStoreConfig &config, bool isWrite); + static int32_t Repair(const RdbStoreConfig &config); + static int32_t Delete(const RdbStoreConfig &config); RdConnection(const RdbStoreConfig &config, bool isWriteConnection); ~RdConnection(); int32_t OnInitialize() override; - std::pair CreateStatement(const std::string& sql, SConn conn) override; + std::pair CreateStatement(const std::string &sql, SConn conn) override; int32_t GetDBType() const override; bool IsWriter() const override; - int32_t ReSetKey(const RdbStoreConfig& config) override; + int32_t ReSetKey(const RdbStoreConfig &config) override; int32_t TryCheckPoint(bool timeout) override; int32_t LimitWalSize() override; - int32_t ConfigLocale(const std::string& localeStr) override; - int32_t CleanDirtyData(const std::string& table, uint64_t cursor) override; - int32_t SubscribeTableChanges(const Notifier& notifier) override; + int32_t ConfigLocale(const std::string &localeStr) override; + int32_t CleanDirtyData(const std::string &table, uint64_t cursor) override; + int32_t SubscribeTableChanges(const Notifier ¬ifier) override; int32_t GetMaxVariable() const override; int32_t GetJournalMode() override; int32_t ClearCache() override; - int32_t Subscribe(const std::string& event, - const std::shared_ptr& observer) override; - int32_t Unsubscribe(const std::string& event, - const std::shared_ptr& observer) override; - int32_t Backup(const std::string &databasePath, const std::vector &destEncryptKey, - bool isAsync, SlaveStatus &slaveStatus) override; + int32_t Subscribe( + const std::string &event, const std::shared_ptr &observer) override; + int32_t Unsubscribe( + const std::string &event, const std::shared_ptr &observer) override; + int32_t Backup(const std::string &databasePath, const std::vector &destEncryptKey, bool isAsync, + SlaveStatus &slaveStatus) override; int32_t Restore(const std::string &databasePath, const std::vector &destEncryptKey, SlaveStatus &slaveStatus) override; ExchangeStrategy GenerateExchangeStrategy(const SlaveStatus &status) override; - + private: static constexpr int MAX_VARIABLE_NUM = 500; static constexpr const char *GRD_OPEN_CONFIG_STR = @@ -67,7 +67,7 @@ private: "\"sharedModeEnable\":1, \"metaInfoBak\":1, \"maxConnNum\":500"; static constexpr uint32_t NO_ITER = 0; static constexpr uint32_t ITER_V1 = 5000; - static constexpr uint32_t ITERS[] = {NO_ITER, ITER_V1}; + static constexpr uint32_t ITERS[] = { NO_ITER, ITER_V1 }; static constexpr uint32_t ITERS_COUNT = sizeof(ITERS) / sizeof(ITERS[0]); static const int32_t regCreator_; static const int32_t regRepairer_; diff --git a/relational_store/frameworks/native/rdb/include/rd_statement.h b/relational_store/frameworks/native/rdb/include/rd_statement.h index e802c915c5b204567d87c98c5d72e20ec680283b..795f6a8255ac2c0443e1b5ccdae4203d433ecfd4 100644 --- a/relational_store/frameworks/native/rdb/include/rd_statement.h +++ b/relational_store/frameworks/native/rdb/include/rd_statement.h @@ -20,11 +20,11 @@ #include #include "connection.h" +#include "rd_connection.h" #include "rd_utils.h" +#include "rdb_store_config.h" #include "statement.h" #include "value_object.h" -#include "rd_connection.h" -#include "rdb_store_config.h" namespace OHOS { namespace NativeRdb { @@ -33,14 +33,14 @@ public: RdStatement(); ~RdStatement(); int Finalize() override; - int32_t Prepare(const std::string& sql) override; - int32_t Bind(const std::vector& args) override; + int32_t Prepare(const std::string &sql) override; + int32_t Bind(const std::vector &args) override; std::pair Count() override; int32_t Step() override; int32_t Reset() override; - int32_t Execute(const std::vector& args) override; - int32_t Execute(const std::vector>& args) override; - std::pair ExecuteForValue(const std::vector& args) override; + int32_t Execute(const std::vector &args) override; + int32_t Execute(const std::vector> &args) override; + std::pair ExecuteForValue(const std::vector &args) override; int32_t Changes() const override; int64_t LastInsertRowId() const override; int32_t GetColumnCount() const override; @@ -50,13 +50,13 @@ public: std::pair GetColumn(int32_t index) const override; bool ReadOnly() const override; bool SupportBlockInfo() const override; - int32_t FillBlockInfo(SharedBlockInfo* info) const override; + int32_t FillBlockInfo(SharedBlockInfo *info) const override; void GetProperties(); private: friend class RdConnection; int Prepare(GRD_DB *db, const std::string &sql); - int32_t Bind(const std::vector>& args); + int32_t Bind(const std::vector> &args); int InnerBindBlobTypeArgs(const ValueObject &bindArg, uint32_t index) const; int IsValid(int index) const; @@ -75,4 +75,4 @@ private: }; } // namespace NativeRdb } // namespace OHOS -#endif // NATIVE_RDB_RD_STATEMENT_H \ No newline at end of file +#endif // NATIVE_RDB_RD_STATEMENT_H diff --git a/relational_store/frameworks/native/rdb/include/rd_utils.h b/relational_store/frameworks/native/rdb/include/rd_utils.h index a31d54c4911da780b796a7ed75446e6248afdc7c..49b4b8d16e6c93d4c2957998aa47a83db8c6c775 100644 --- a/relational_store/frameworks/native/rdb/include/rd_utils.h +++ b/relational_store/frameworks/native/rdb/include/rd_utils.h @@ -18,7 +18,9 @@ #include #include + #include + #include "grd_type_export.h" #include "rdb_errno.h" #include "remote_result_set.h" diff --git a/relational_store/frameworks/native/rdb/include/rdb_local_db_observer.h b/relational_store/frameworks/native/rdb/include/rdb_local_db_observer.h index 42cd14985a6c580b7d545d8864abf4ab86c3331c..e6b57426ed2f6bf6e722ddc225cb52752b84d273 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_local_db_observer.h +++ b/relational_store/frameworks/native/rdb/include/rdb_local_db_observer.h @@ -17,6 +17,7 @@ #define NATIVE_RDB_LOCAL_DB_OBSERVER_H #include + #include "rdb_types.h" #include "store_observer.h" diff --git a/relational_store/frameworks/native/rdb/include/rdb_manager_impl.h b/relational_store/frameworks/native/rdb/include/rdb_manager_impl.h index 7791ae1551793a38f8774ee2c949159345d5d7e4..dd0ee95a872920fc257851909ffa4a2037af2c24 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_manager_impl.h +++ b/relational_store/frameworks/native/rdb/include/rdb_manager_impl.h @@ -20,12 +20,12 @@ #include #include -#include "refbase.h" +#include "concurrent_map.h" +#include "irdb_service.h" #include "iremote_object.h" #include "iremote_proxy.h" -#include "concurrent_map.h" #include "rdb_types.h" -#include "irdb_service.h" +#include "refbase.h" namespace OHOS::DistributedRdb { class RdbService; @@ -51,8 +51,9 @@ public: owner_->OnRemoteDied(); } } + private: - RdbManagerImpl* owner_; + RdbManagerImpl *owner_; }; private: diff --git a/relational_store/frameworks/native/rdb/include/rdb_platform.h b/relational_store/frameworks/native/rdb/include/rdb_platform.h index 5bb5d03665d44fe6d43a8dd4790c4a82ec356872..a3aab2b1fdad529730ac6ce9340cc792f69739ad 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_platform.h +++ b/relational_store/frameworks/native/rdb/include/rdb_platform.h @@ -16,9 +16,11 @@ #ifndef DISTRIBUTEDDATAMGR_NATIVERDB_RDB_PLATFORM_H #define DISTRIBUTEDDATAMGR_NATIVERDB_RDB_PLATFORM_H +#include + #include #include -#include + #include "unistd.h" #ifdef WINDOWS_PLATFORM #include diff --git a/relational_store/frameworks/native/rdb/include/rdb_security_manager.h b/relational_store/frameworks/native/rdb/include/rdb_security_manager.h index 0bdad7d9d246b8ec51d44db17777d407e32f36fd..bf6bb1a47842cb63a027ea1af7c7025caa7c6743 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_security_manager.h +++ b/relational_store/frameworks/native/rdb/include/rdb_security_manager.h @@ -31,8 +31,8 @@ namespace OHOS::NativeRdb { struct RdbSecretKeyData { uint8_t distributed = 0; - time_t timeValue {}; - std::vector secretKey {}; + time_t timeValue{}; + std::vector secretKey{}; RdbSecretKeyData() = default; ~RdbSecretKeyData() { @@ -110,7 +110,7 @@ private: RdbPassword LoadSecretKeyFromFile(const std::string &keyFile); bool LoadSecretKeyFromDisk(const std::string &keyPath, RdbSecretKeyData &keyData); bool IsKeyFileEmpty(const std::string &keyFile); - static bool IsKeyExpired(const time_t &createTime) ; + static bool IsKeyExpired(const time_t &createTime); int32_t HksLoopUpdate(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData); int32_t HksEncryptThreeStage(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, @@ -134,7 +134,7 @@ private: static constexpr uint8_t UNDISTRIBUTED = 0; static constexpr uint8_t DISTRIBUTED = 1; - std::vector rootKeyAlias_ {}; + std::vector rootKeyAlias_{}; std::vector nonce_; std::vector aad_; std::mutex mutex_; diff --git a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h index c6080aa1007829a6a94e21958a6ba3d044227922..a84d99d82e36545cb69f709b63841ef73b9e15af 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h +++ b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h @@ -16,12 +16,14 @@ #ifndef DISTRIBUTED_RDB_RDB_SERVICE_PROXY_H #define DISTRIBUTED_RDB_RDB_SERVICE_PROXY_H +#include + #include #include -#include + +#include "concurrent_map.h" #include "irdb_service.h" #include "rdb_notifier_stub.h" -#include "concurrent_map.h" namespace OHOS::DistributedRdb { class RdbServiceProxy : public IRemoteProxy { @@ -32,9 +34,9 @@ public: SubscribeOption subscribeOption{ SubscribeMode::REMOTE }; }; using Observers = ConcurrentMap>; - explicit RdbServiceProxy(const sptr& object); + explicit RdbServiceProxy(const sptr &object); - std::string ObtainDistributedTableName(const std::string& device, const std::string& table) override; + std::string ObtainDistributedTableName(const std::string &device, const std::string &table) override; int32_t InitNotifier(const RdbSyncerParam ¶m); @@ -43,14 +45,13 @@ public: int32_t SetDistributedTables(const RdbSyncerParam ¶m, const std::vector &tables, const std::vector &references, bool isRebuild, int32_t type = DISTRIBUTED_DEVICE) override; - int32_t Sync(const RdbSyncerParam& param, const Option& option, - const PredicatesMemo& predicates, const AsyncDetail &async) override; + int32_t Sync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, + const AsyncDetail &async) override; - int32_t Subscribe(const RdbSyncerParam& param, const SubscribeOption& option, - RdbStoreObserver *observer) override; + int32_t Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, RdbStoreObserver *observer) override; - int32_t UnSubscribe(const RdbSyncerParam& param, const SubscribeOption& option, - RdbStoreObserver *observer) override; + int32_t UnSubscribe( + const RdbSyncerParam ¶m, const SubscribeOption &option, RdbStoreObserver *observer) override; int32_t RegisterAutoSyncCallback( const RdbSyncerParam ¶m, std::shared_ptr observer) override; @@ -71,20 +72,20 @@ public: int32_t Delete(const RdbSyncerParam ¶m) override; - int32_t NotifyDataChange(const RdbSyncerParam& param, const RdbChangedData &clientChangedData, + int32_t NotifyDataChange(const RdbSyncerParam ¶m, const RdbChangedData &clientChangedData, const RdbNotifyConfig &rdbNotifyConfig) override; - int32_t SetSearchable(const RdbSyncerParam& param, bool isSearchable) override; + int32_t SetSearchable(const RdbSyncerParam ¶m, bool isSearchable) override; std::pair> QuerySharingResource(const RdbSyncerParam ¶m, const PredicatesMemo &predicates, const std::vector &columns) override; - int32_t Disable(const RdbSyncerParam& param) override; - int32_t Enable(const RdbSyncerParam& param) override; - int32_t GetPassword(const RdbSyncerParam& param, std::vector &key) override; + int32_t Disable(const RdbSyncerParam ¶m) override; + int32_t Enable(const RdbSyncerParam ¶m) override; + int32_t GetPassword(const RdbSyncerParam ¶m, std::vector &key) override; - std::pair LockCloudContainer(const RdbSyncerParam& param) override; + std::pair LockCloudContainer(const RdbSyncerParam ¶m) override; - int32_t UnlockCloudContainer(const RdbSyncerParam& param) override; + int32_t UnlockCloudContainer(const RdbSyncerParam ¶m) override; int32_t GetDebugInfo(const RdbSyncerParam ¶m, std::map &debugInfo) override; @@ -95,20 +96,20 @@ private: using PrimaryFields = RdbStoreObserver::PrimaryFields; using SyncCallbacks = ConcurrentMap; using SyncObservers = ConcurrentMap>>; - std::pair DoSync(const RdbSyncerParam ¶m, const Option &option, - const PredicatesMemo &predicates); + std::pair DoSync( + const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates); int32_t DoAsync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates); - int32_t DoSync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, - const AsyncDetail &async); + int32_t DoSync( + const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, const AsyncDetail &async); - int32_t DoAsync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, - const AsyncDetail &async); + int32_t DoAsync( + const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, const AsyncDetail &async); - int32_t DoSubscribe(const RdbSyncerParam& param, const SubscribeOption &option); + int32_t DoSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option); - int32_t DoUnSubscribe(const RdbSyncerParam& param, const SubscribeOption &option); + int32_t DoUnSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option); int32_t DoRegister(const RdbSyncerParam ¶m); @@ -122,9 +123,9 @@ private: void OnDataChange(const Origin &origin, const PrimaryFields &primaries, ChangeInfo &&changeInfo); - static std::string RemoveSuffix(const std::string& name); + static std::string RemoveSuffix(const std::string &name); - std::atomic seqNum_ {}; + std::atomic seqNum_{}; Observers observers_; SyncCallbacks syncCallbacks_; SyncObservers syncObservers_; diff --git a/relational_store/frameworks/native/rdb/include/rdb_sql_statistic.h b/relational_store/frameworks/native/rdb/include/rdb_sql_statistic.h index 46252cf66289a197f3a4f32e69decddf6249faf0..c5926b7e589d7d80351f416ffcd74b996ff88d38 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_sql_statistic.h +++ b/relational_store/frameworks/native/rdb/include/rdb_sql_statistic.h @@ -26,7 +26,7 @@ namespace OHOS { template class ConcurrentMap; namespace DistributedRdb { -class SqlStatistic { +class SqlStatistic { public: enum Step : int32_t { STEP_TOTAL, @@ -55,6 +55,6 @@ private: std::chrono::steady_clock::time_point time_; std::shared_ptr execInfo_; }; -} -} +} // namespace DistributedRdb +} // namespace OHOS #endif // OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_NATIVE_RDB_SQL_STATISTIC_H 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 9bc0137b22641c94362c5568439d15ae3b7afdd5..45fba2d2f72996ed5320dec8c88b64118691f605 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h @@ -44,8 +44,8 @@ namespace OHOS::NativeRdb { class DelayNotify; class RdbStoreLocalObserver { public: - explicit RdbStoreLocalObserver(DistributedRdb::RdbStoreObserver *observer) : observer_(observer){}; - virtual ~RdbStoreLocalObserver(){}; + explicit RdbStoreLocalObserver(DistributedRdb::RdbStoreObserver *observer) : observer_(observer) {}; + virtual ~RdbStoreLocalObserver() {}; void OnChange() { observer_->OnChange(); @@ -61,8 +61,8 @@ private: class RdbStoreLocalSharedObserver : public AAFwk::DataAbilityObserverStub { public: - explicit RdbStoreLocalSharedObserver(DistributedRdb::RdbStoreObserver *observer) : observer_(observer){}; - virtual ~RdbStoreLocalSharedObserver(){}; + explicit RdbStoreLocalSharedObserver(DistributedRdb::RdbStoreObserver *observer) : observer_(observer) {}; + virtual ~RdbStoreLocalSharedObserver() {}; void OnChange() override { observer_->OnChange(); @@ -82,16 +82,16 @@ public: RdbStoreImpl(const RdbStoreConfig &config, int &errCode); ~RdbStoreImpl() override; std::pair Insert(const std::string &table, const Row &row, Resolution resolution) override; - std::pair BatchInsert(const std::string& table, const ValuesBuckets& values) override; + std::pair BatchInsert(const std::string &table, const ValuesBuckets &values) override; std::pair Update(const std::string &table, const Row &row, const std::string &where, const Values &args, Resolution resolution) override; int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, const Values &args) override; std::shared_ptr QuerySql(const std::string &sql, const Values &args) override; std::shared_ptr QueryByStep(const std::string &sql, const Values &args) override; - std::shared_ptr RemoteQuery(const std::string &device, const AbsRdbPredicates &predicates, - const Fields &columns, int &errCode) override; - std::pair> QuerySharingResource(const AbsRdbPredicates &predicates, - const Fields &columns) override; + std::shared_ptr RemoteQuery( + const std::string &device, const AbsRdbPredicates &predicates, const Fields &columns, int &errCode) override; + std::pair> QuerySharingResource( + const AbsRdbPredicates &predicates, const Fields &columns) override; int ExecuteSql(const std::string &sql, const Values &args) override; std::pair Execute(const std::string &sql, const Values &args, int64_t trxId) override; int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, const Values &args) override; @@ -130,12 +130,12 @@ public: int UnregisterAutoSyncCallback(std::shared_ptr observer) override; int Notify(const std::string &event) override; int SetSearchable(bool isSearchable) override; - ModifyTime GetModifyTime(const std::string &table, const std::string &columnName, - std::vector &keys) override; + ModifyTime GetModifyTime( + const std::string &table, const std::string &columnName, std::vector &keys) override; int GetRebuilt(RebuiltType &rebuilt) override; int CleanDirtyData(const std::string &table, uint64_t cursor) override; - std::pair Attach(const RdbStoreConfig &config, const std::string &attachName, - int32_t waitTime) override; + std::pair Attach( + const RdbStoreConfig &config, const std::string &attachName, int32_t waitTime) override; std::pair Detach(const std::string &attachName, int32_t waitTime) override; int ModifyLockStatus(const AbsRdbPredicates &predicates, bool isLock) override; int32_t GetDbType() const override; @@ -178,16 +178,16 @@ private: void InitSyncerParam(const RdbStoreConfig &config, bool created); int ExecuteByTrxId(const std::string &sql, int64_t trxId, bool closeConnAfterExecute = false, const std::vector &bindArgs = {}); - std::pair HandleDifferentSqlTypes(std::shared_ptr statement, - const std::string &sql, const ValueObject &object, int sqlType); + std::pair HandleDifferentSqlTypes( + std::shared_ptr statement, const std::string &sql, const ValueObject &object, int sqlType); int CheckAttach(const std::string &sql); std::pair BeginExecuteSql(const std::string &sql); int GetDataBasePath(const std::string &databasePath, std::string &backupFilePath); void DoCloudSync(const std::string &table); - static int InnerSync(const RdbParam ¶m, const Options &option, const Memo &predicates, - const AsyncDetail &async); - int InnerBackup(const std::string &databasePath, - const std::vector &destEncryptKey = std::vector()); + static int InnerSync( + const RdbParam ¶m, const Options &option, const Memo &predicates, const AsyncDetail &async); + int InnerBackup( + const std::string &databasePath, const std::vector &destEncryptKey = std::vector()); ModifyTime GetModifyTimeByRowId(const std::string &logTable, std::vector &keys); Uri GetUri(const std::string &event); int SubscribeLocal(const SubscribeOption &option, RdbStoreObserver *observer); @@ -203,14 +203,14 @@ private: int RegisterDataChangeCallback(); void InitDelayNotifier(); std::pair> CreateWritableConn(); - std::vector CreateBackupBindArgs(const std::string &databasePath, - const std::vector &destEncryptKey); + std::vector CreateBackupBindArgs( + const std::string &databasePath, const std::vector &destEncryptKey); std::pair GetStatement(const std::string &sql, std::shared_ptr conn) const; std::pair GetStatement(const std::string &sql, bool read = false) const; int AttachInner(const RdbStoreConfig &config, const std::string &attachName, const std::string &dbPath, const std::vector &key, int32_t waitTime); - int SetDefaultEncryptSql(const std::shared_ptr &statement, std::string sql, - const RdbStoreConfig &config); + int SetDefaultEncryptSql( + const std::shared_ptr &statement, std::string sql, const RdbStoreConfig &config); int SetDefaultEncryptAlgo(const ConnectionPool::SharedConn &conn, const RdbStoreConfig &config); int GetHashKeyForLockRow(const AbsRdbPredicates &predicates, std::vector> &hashKeys); int GetSlaveName(const std::string &dbName, std::string &backupFilePath); diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_manager.h b/relational_store/frameworks/native/rdb/include/rdb_store_manager.h index 66153395177c56d1fcbd43dc7dd993fe3ce45910..aacb49afe9f33dbb3c5abe2d2c508797913cc30b 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_manager.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_manager.h @@ -55,7 +55,6 @@ private: static constexpr uint32_t BUCKET_MAX_SIZE = 4; static const bool regCollector_; - std::string bundleName_; std::mutex mutex_; std::map> storeCache_; LRUBucket configCache_; diff --git a/relational_store/frameworks/native/rdb/include/rdb_types_util.h b/relational_store/frameworks/native/rdb/include/rdb_types_util.h index d49df89ffe7a14d1abd2b92e09614708d4760696..fc3ce4e98cd73ae596003071d136e2e3cd407873 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_types_util.h +++ b/relational_store/frameworks/native/rdb/include/rdb_types_util.h @@ -126,5 +126,5 @@ template<> API_EXPORT bool Marshalling(const DebugInfo &input, MessageParcel &data); template<> API_EXPORT bool Unmarshalling(DebugInfo &output, MessageParcel &data); -} +} // namespace OHOS::ITypesUtil #endif // DISTRIBUTED_RDB_RDB_TYPES_UTIL_H diff --git a/relational_store/frameworks/native/rdb/include/share_block.h b/relational_store/frameworks/native/rdb/include/share_block.h index 50a44314188d876fcf073e3c481cab3f5e5b69be..278f9ae393e5cbe53bcd3229a3c44121ec57944c 100644 --- a/relational_store/frameworks/native/rdb/include/share_block.h +++ b/relational_store/frameworks/native/rdb/include/share_block.h @@ -16,10 +16,12 @@ #ifndef NATIVE_RDB_SHARE_BLOCK_H #define NATIVE_RDB_SHARE_BLOCK_H -#include "shared_block.h" #include + #include +#include "shared_block.h" + namespace OHOS { namespace NativeRdb { #ifdef __cplusplus @@ -43,7 +45,7 @@ struct SharedBlockInfo { bool isFull; bool hasException; - SharedBlockInfo(AppDataFwk::SharedBlock* sharedBlock) : sharedBlock(sharedBlock) + SharedBlockInfo(AppDataFwk::SharedBlock *sharedBlock) : sharedBlock(sharedBlock) { startPos = 0; addedRows = 0; @@ -68,18 +70,18 @@ int SeriPutOther(void *pCtx, int addedRows, int column); int ClearSharedBlock(AppDataFwk::SharedBlock *sharedBlock); int SharedBlockSetColumnNum(AppDataFwk::SharedBlock *sharedBlock, int columnNum); int FillSharedBlockOpt(SharedBlockInfo *info, sqlite3_stmt *stmt); -FillOneRowResult FillOneRowOfString(AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, - int addedRows, int pos); -FillOneRowResult FillOneRowOfLong(AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, - int addedRows, int pos); -FillOneRowResult FillOneRowOfFloat(AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, - int addedRows, int pos); -FillOneRowResult FillOneRowOfBlob(AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, - int addedRows, int pos); -FillOneRowResult FillOneRowOfNull(AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, - int addedRows, int pos); -FillOneRowResult FillOneRow(AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int numColumns, - int startPos, int addedRows); +FillOneRowResult FillOneRowOfString( + AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, int addedRows, int pos); +FillOneRowResult FillOneRowOfLong( + AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, int addedRows, int pos); +FillOneRowResult FillOneRowOfFloat( + AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, int addedRows, int pos); +FillOneRowResult FillOneRowOfBlob( + AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, int addedRows, int pos); +FillOneRowResult FillOneRowOfNull( + AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int startPos, int addedRows, int pos); +FillOneRowResult FillOneRow( + AppDataFwk::SharedBlock *sharedBlock, sqlite3_stmt *statement, int numColumns, int startPos, int addedRows); void FillRow(SharedBlockInfo *info, sqlite3_stmt *stmt); int FillSharedBlock(SharedBlockInfo *info, sqlite3_stmt *stmt); bool ResetStatement(SharedBlockInfo *info, sqlite3_stmt *stmt); diff --git a/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h b/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h index 465729b2f9463439656d7f16f961874233520e46..651c9ab0b8971851ee86e348df62f3d685c176c8 100644 --- a/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h +++ b/relational_store/frameworks/native/rdb/include/shared_block_serializer_info.h @@ -61,6 +61,7 @@ public: { return astartPos; } + private: AppDataFwk::SharedBlock *sharedBlock_; sqlite3_stmt *statement_ = nullptr; diff --git a/relational_store/frameworks/native/rdb/include/sqlite_connection.h b/relational_store/frameworks/native/rdb/include/sqlite_connection.h index 7ac63b1f0095d5b7748fecbc562f60b0cae46654..e80e4824b1b77a9bcbe70d684f105cddfece8b97 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_connection.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_connection.h @@ -61,19 +61,19 @@ public: int GetMaxVariable() const override; int32_t GetDBType() const override; int32_t ClearCache() override; - int32_t Subscribe(const std::string &event, - const std::shared_ptr &observer) override; - int32_t Unsubscribe(const std::string &event, - const std::shared_ptr &observer) override; - int32_t Backup(const std::string &databasePath, const std::vector &destEncryptKey, - bool isAsync, SlaveStatus &slaveStatus) override; + int32_t Subscribe( + const std::string &event, const std::shared_ptr &observer) override; + int32_t Unsubscribe( + const std::string &event, const std::shared_ptr &observer) override; + int32_t Backup(const std::string &databasePath, const std::vector &destEncryptKey, bool isAsync, + SlaveStatus &slaveStatus) override; int32_t Restore(const std::string &databasePath, const std::vector &destEncryptKey, SlaveStatus &slaveStatus) override; ExchangeStrategy GenerateExchangeStrategy(const SlaveStatus &status) override; protected: - std::pair ExecuteForValue(const std::string &sql, - const std::vector &bindArgs = std::vector()); + std::pair ExecuteForValue( + const std::string &sql, const std::vector &bindArgs = std::vector()); int ExecuteSql(const std::string &sql, const std::vector &bindArgs = std::vector()); private: @@ -107,44 +107,38 @@ private: int RegDefaultFunctions(sqlite3 *dbHandle); static void MergeAssets(sqlite3_context *ctx, int argc, sqlite3_value **argv); static void MergeAsset(sqlite3_context *ctx, int argc, sqlite3_value **argv); - static void CompAssets(std::map &oldAssets, - std::map &newAssets); + static void CompAssets( + std::map &oldAssets, std::map &newAssets); static void MergeAsset(ValueObject::Asset &oldAsset, ValueObject::Asset &newAsset); int SetCustomFunctions(const RdbStoreConfig &config); int SetCustomScalarFunction(const std::string &functionName, int argc, ScalarFunction *function); - int32_t UnsubscribeLocalDetail(const std::string &event, - const std::shared_ptr &observer); + int32_t UnsubscribeLocalDetail( + const std::string &event, const std::shared_ptr &observer); int32_t UnsubscribeLocalDetailAll(const std::string &event); int32_t OpenDatabase(const std::string &dbPath, int openFileFlags); int LoadExtension(const RdbStoreConfig &config, sqlite3 *dbHandle); RdbStoreConfig GetSlaveRdbStoreConfig(const RdbStoreConfig &rdbConfig); - std::pair> CreateSlaveConnection(const RdbStoreConfig &config, - SlaveOpenPolicy slaveOpenPolicy); + std::pair> CreateSlaveConnection( + const RdbStoreConfig &config, SlaveOpenPolicy slaveOpenPolicy); int ExchangeSlaverToMaster(bool isRestore, bool verifyDb, SlaveStatus &status); int ExchangeVerify(bool isRestore); int SqliteNativeBackup(bool isRestore, SlaveStatus &curStatus); int VeritySlaveIntegrity(); bool IsDbVersionBelowSlave(); - static std::pair> InnerCreate(const RdbStoreConfig &config, - bool isWrite); + static std::pair> InnerCreate( + const RdbStoreConfig &config, bool isWrite); static int CopyDb(const RdbStoreConfig &config, const std::string &srcPath, const std::string &destPath); - static constexpr SqliteConnection::Suffix FILE_SUFFIXES[] = { - {"", "DB"}, - {"-shm", "SHM"}, - {"-wal", "WAL"}, - {"-journal", "JOURNAL"}, - {"-slaveFailure", nullptr}, - {"-syncInterrupt", nullptr}, - {".corruptedflg", nullptr} - }; + static constexpr SqliteConnection::Suffix FILE_SUFFIXES[] = { { "", "DB" }, { "-shm", "SHM" }, { "-wal", "WAL" }, + { "-journal", "JOURNAL" }, { "-slaveFailure", nullptr }, { "-syncInterrupt", nullptr }, + { ".corruptedflg", nullptr } }; static constexpr const char *MERGE_ASSETS_FUNC = "merge_assets"; static constexpr const char *MERGE_ASSET_FUNC = "merge_asset"; - static constexpr int CHECKPOINT_TIME = 1000; + static constexpr int CHECKPOINT_TIME = 500; static constexpr int DEFAULT_BUSY_TIMEOUT_MS = 2000; static constexpr int BACKUP_PAGES_PRE_STEP = 12800; // 1024 * 4 * 12800 == 50m static constexpr int BACKUP_PRE_WAIT_TIME = 10; - static constexpr ssize_t SLAVE_WAL_SIZE_LIMIT = 2147483647; // 2147483647 = 2g - 1 + static constexpr ssize_t SLAVE_WAL_SIZE_LIMIT = 2147483647; // 2147483647 = 2g - 1 static constexpr ssize_t SLAVE_INTEGRITY_CHECK_LIMIT = 524288000; // 524288000 == 1024 * 1024 * 500 static constexpr uint32_t NO_ITER = 0; static constexpr uint32_t DB_INDEX = 0; 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 373b46273a3fdef4ab4cf20538ca819268bfeee5..2395f2c5d2646945d70200202bba59c3a9c21101 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_global_config.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_global_config.h @@ -25,15 +25,15 @@ namespace NativeRdb { class GlobalExpr { public: - static constexpr bool CALLBACK_LOG_SWITCH = true; /* Sqlite callback log switch */ - static constexpr int SOFT_HEAP_LIMIT = 8 * 1024 * 1024; /* 8MB */ - static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ - static constexpr int DB_JOURNAL_SIZE = 1024 * 1024; /* default file size : 1M */ + static constexpr bool CALLBACK_LOG_SWITCH = true; /* Sqlite callback log switch */ + static constexpr int SOFT_HEAP_LIMIT = 8 * 1024 * 1024; /* 8MB */ + static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ + static constexpr int DB_JOURNAL_SIZE = 1024 * 1024; /* default file size : 1M */ static constexpr ssize_t DB_WAL_SIZE_LIMIT_MIN = 20 * 1024 * 1024; /* default wal file maximum size : 20M */ - static constexpr ssize_t DB_WAL_WARNING_SIZE = 256 * 1024 * 1024; /* default wal file maximum size : 256M */ - static constexpr ssize_t DB_WAL_DEFAULT_SIZE = 0x20000000; /* default wal file size 512M */ - static constexpr ssize_t DB_WAL_SIZE_LIMIT_MAX = 0x7FFFFFFF; /* default wal file maximum size : 2G - 1 */ - static constexpr int WAL_AUTO_CHECKPOINT = 100; /* 100 pages */ + static constexpr ssize_t DB_WAL_WARNING_SIZE = 256 * 1024 * 1024; /* default wal file maximum size : 256M */ + static constexpr ssize_t DB_WAL_DEFAULT_SIZE = 0x20000000; /* default wal file size 512M */ + static constexpr ssize_t DB_WAL_SIZE_LIMIT_MAX = 0x7FFFFFFF; /* default wal file maximum size : 2G - 1 */ + static constexpr int WAL_AUTO_CHECKPOINT = 100; /* 100 pages */ static constexpr int APP_DEFAULT_UMASK = 0002; static constexpr int SQLITE_MAX_COLUMN = 2000; static constexpr char ATTACH_BACKUP_SQL[] = "ATTACH ? AS backup KEY ?"; diff --git a/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h b/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h index c6109bb4cc2e00eb6d69500f15d361901365bd86..ca4900b4f2c0611f9f34541506128f0a899de807 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_shared_result_set.h @@ -13,16 +13,15 @@ * limitations under the License. */ - #ifndef NATIVE_RDB_SQLITE_SHARED_RESULT_SET_H #define NATIVE_RDB_SQLITE_SHARED_RESULT_SET_H +#include #include #include #include #include #include -#include #include "abs_shared_result_set.h" #include "connection.h" @@ -53,7 +52,7 @@ private: int InitRowCount(); std::pair, int> PrepareStep(); int32_t FillBlock(int requiredPos); - int32_t ExecuteForSharedBlock(AppDataFwk::SharedBlock* block, int start, int required); + int32_t ExecuteForSharedBlock(AppDataFwk::SharedBlock *block, int start, int required); private: // The specified value is -1 when there is no data diff --git a/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h b/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h index 104e6b87e676430207ba3b79183411620c9f2fde..e11d96bd6814d660bd2e53eda2625a55697734a3 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_sql_builder.h @@ -36,8 +36,8 @@ public: ConflictResolution conflictResolution); static int BuildQueryString(bool distinct, const std::string &table, const std::string &joinClause, const std::vector &columns, const std::string &whereClause, const std::string &groupBy, - const std::string &indexName, const std::string &orderBy, const int &limit, - const int &offset, std::string &outSql); + const std::string &indexName, const std::string &orderBy, const int &limit, const int &offset, + std::string &outSql); static std::string BuildSqlStringFromPredicates(const std::string &index, const std::string &joinClause, const std::string &whereClause, const std::string &group, const std::string &order, int limit, int offset); static std::string BuildQueryString(const AbsRdbPredicates &predicates, const std::vector &columns); @@ -51,11 +51,12 @@ public: static BatchRefSqls GenerateSqls(const std::string &table, const ValuesBuckets &buckets, int limit); static void UpdateAssetStatus(const ValueObject &value, int32_t status); + private: - static BatchRefSqls MakeExecuteSqls(const std::string &sql, const std::vector &args, int fieldSize, - int limit); - static void AppendClause(std::string &builder, const std::string &name, - const std::string &clause, const std::string &table = ""); + static BatchRefSqls MakeExecuteSqls( + const std::string &sql, const std::vector &args, int fieldSize, int limit); + static void AppendClause( + std::string &builder, const std::string &name, const std::string &clause, const std::string &table = ""); static void AppendColumns( std::string &builder, const std::vector &columns, const std::string &table = ""); diff --git a/relational_store/frameworks/native/rdb/include/sqlite_statement.h b/relational_store/frameworks/native/rdb/include/sqlite_statement.h index 92d2f8b7823a7ec157a4d267058c80eedd834ff1..dfc353baeda3a5013e044b47c0d661d3ffee934d 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_statement.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_statement.h @@ -19,11 +19,11 @@ #include #include +#include "rdb_store_config.h" #include "share_block.h" #include "sqlite3sym.h" #include "statement.h" #include "value_object.h" -#include "rdb_store_config.h" namespace OHOS { namespace NativeRdb { @@ -56,8 +56,8 @@ public: bool ReadOnly() const override; bool SupportBlockInfo() const override; int32_t FillBlockInfo(SharedBlockInfo *info) const override; - int ModifyLockStatus(const std::string &table, const std::vector> &hashKeys, - bool isLock) override; + int ModifyLockStatus( + const std::string &table, const std::vector> &hashKeys, bool isLock) override; private: friend class SqliteConnection; diff --git a/relational_store/frameworks/native/rdb/include/sqlite_utils.h b/relational_store/frameworks/native/rdb/include/sqlite_utils.h index cfa7cf8e97e470832c1fb34a2f888fb306495c90..3158a555721b3892bb778ac506a52409cec62c1f 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_utils.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_utils.h @@ -18,6 +18,7 @@ #include #include +#include #include "sqlite3sym.h" @@ -42,9 +43,9 @@ public: static constexpr int DISABLE_LOAD_EXTENSION = 0; static constexpr int ENABLE_LOAD_EXTENSION = 1; static constexpr int MAX_LOAD_EXTENSION_COUNT = 16; - static constexpr const char* REP = "#_"; - static constexpr const char* SLAVE_FAILURE = "-slaveFailure"; - static constexpr const char* SLAVE_INTERRUPT = "-syncInterrupt"; + static constexpr const char *REP = "#_"; + static constexpr const char *SLAVE_FAILURE = "-slaveFailure"; + static constexpr const char *SLAVE_INTERRUPT = "-syncInterrupt"; static int GetSqlStatementType(const std::string &sql); static bool IsSupportSqlForExecute(int sqlType); @@ -60,7 +61,7 @@ public: static std::string AnonySql(const std::string &sql); static ssize_t GetFileSize(const std::string &fileName); static bool IsSlaveDbName(const std::string &fileName); - static std::string GetSlavePath(const std::string& name); + static std::string GetSlavePath(const std::string &name); static int SetSlaveInvalid(const std::string &dbPath); static int SetSlaveInterrupted(const std::string &dbPath); static bool IsSlaveInvalid(const std::string &dbPath); @@ -94,11 +95,17 @@ private: { "UPD", SqliteUtils::STATEMENT_UPDATE } }; static constexpr size_t TYPE_SIZE = sizeof(SQL_TYPE_MAP) / sizeof(SqlType); - static constexpr const char* ON_CONFLICT_CLAUSE[CONFLICT_CLAUSE_COUNT] = { "", " OR ROLLBACK", " OR ABORT", + static constexpr const char *ON_CONFLICT_CLAUSE[CONFLICT_CLAUSE_COUNT] = { "", " OR ROLLBACK", " OR ABORT", " OR FAIL", " OR IGNORE", " OR REPLACE" }; static std::string GetAnonymousName(const std::string& fileName); static std::string AnonyDigits(const std::string& fileName); + static bool IsSpecialChar(char c); + static std::vector SplitString(const std::string &input); + static std::string ReplaceMultipleSpaces(const std::string &str); + static std::string AnonyWord(const std::string &word); + static bool Find(const std::string &word, const char *const array[], uint32_t length); + static std::string AnonySqlString(const std::string &input, const char *const array[], uint32_t length); }; } // namespace NativeRdb diff --git a/relational_store/frameworks/native/rdb/include/statement.h b/relational_store/frameworks/native/rdb/include/statement.h index d5d25653616bcbd463b9375c3eacd8886708fa58..d766fb6fee794d0b4f0884ddb54bc7121fd16690 100644 --- a/relational_store/frameworks/native/rdb/include/statement.h +++ b/relational_store/frameworks/native/rdb/include/statement.h @@ -53,8 +53,8 @@ public: virtual bool ReadOnly() const = 0; virtual bool SupportBlockInfo() const = 0; virtual int32_t FillBlockInfo(SharedBlockInfo *info) const = 0; - virtual int ModifyLockStatus(const std::string &table, const std::vector> &hashKeys, - bool isLock) + virtual int ModifyLockStatus( + const std::string &table, const std::vector> &hashKeys, bool isLock) { return 0; } diff --git a/relational_store/frameworks/native/rdb/include/string_utils.h b/relational_store/frameworks/native/rdb/include/string_utils.h index d07479121312ad3ba263fa718eddfececadbf7b7..8012f97d6358135e12bd02d693943f596568bdc9 100644 --- a/relational_store/frameworks/native/rdb/include/string_utils.h +++ b/relational_store/frameworks/native/rdb/include/string_utils.h @@ -28,8 +28,8 @@ public: const std::string &function, const std::string &separator, const std::vector &array); static std::vector Split(const std::string &str, const std::string &delim); - static std::string ExtractFilePath(const std::string& fileFullName); - static std::string ExtractFileName(const std::string& fileFullName); + static std::string ExtractFilePath(const std::string &fileFullName); + static std::string ExtractFileName(const std::string &fileFullName); static bool IsEmpty(std::string source) { return (source.empty()); diff --git a/relational_store/frameworks/native/rdb/include/transaction_impl.h b/relational_store/frameworks/native/rdb/include/transaction_impl.h index ce06928fe1ac7c035184d2227e8a89a667a922d5..c078659fecbf817c42dd84941295611a2487c13d 100644 --- a/relational_store/frameworks/native/rdb/include/transaction_impl.h +++ b/relational_store/frameworks/native/rdb/include/transaction_impl.h @@ -15,8 +15,8 @@ #ifndef NATIVE_RDB_TRANSACTION_IMPL_H #define NATIVE_RDB_TRANSACTION_IMPL_H -#include #include +#include #include #include "connection.h" @@ -36,12 +36,12 @@ public: std::pair Insert(const std::string &table, const Row &row, Resolution resolution) override; std::pair BatchInsert(const std::string &table, const Rows &rows) override; std::pair BatchInsert(const std::string &table, const RefRows &rows) override; - std::pair Update(const std::string &table, const Row &row, const std::string &where, - const Values &args, Resolution resolution) override; - std::pair Update(const Row &row, const AbsRdbPredicates &predicates, - Resolution resolution) override; - std::pair Delete(const std::string &table, const std::string &whereClause, - const Values &args) override; + std::pair Update(const std::string &table, const Row &row, const std::string &where, const Values &args, + Resolution resolution) override; + std::pair Update( + const Row &row, const AbsRdbPredicates &predicates, Resolution resolution) override; + std::pair Delete( + const std::string &table, const std::string &whereClause, const Values &args) override; std::pair Delete(const AbsRdbPredicates &predicates) override; std::shared_ptr QueryByStep(const std::string &sql, const Values &args) override; std::shared_ptr QueryByStep(const AbsRdbPredicates &predicates, const Fields &columns) override; @@ -68,5 +68,5 @@ private: static constexpr char ROLLBACK_SQL[] = "ROLLBACK;"; static constexpr const char *BEGIN_SQLS[] = { "BEGIN DEFERRED;", "BEGIN IMMEDIATE;", "BEGIN EXCLUSIVE;" }; }; -} +} // namespace OHOS::NativeRdb #endif diff --git a/relational_store/frameworks/native/rdb/mock/include/acl.h b/relational_store/frameworks/native/rdb/mock/include/acl.h index 6f7d9e20821a2d00873afb4879093904619b1222..66b5c52fe3c48e353c381cd985d350803a48fb28 100644 --- a/relational_store/frameworks/native/rdb/mock/include/acl.h +++ b/relational_store/frameworks/native/rdb/mock/include/acl.h @@ -17,6 +17,7 @@ #define OHOS_DISTRIBUTED_DATA_DATABASE_UTILS_ACL_H #include + #include namespace OHOS { namespace DATABASE_UTILS { @@ -40,7 +41,7 @@ public: return 0; } }; -} // DATABASE_UTILS +} // namespace DATABASE_UTILS } // namespace OHOS #endif // OHOS_DISTRIBUTED_DATA_DATABASE_UTILS_ACL_H \ 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 57a963f2773aab664e64c500d5bb14f2834bdc4f..8719b59b2dda4aab4cd31f9b794c9a480302e3f6 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 @@ -37,7 +37,7 @@ public: RdbStoreImpl(const RdbStoreConfig &config, int &errCode); ~RdbStoreImpl() override; std::pair Insert(const std::string &table, const Row &row, Resolution resolution) override; - std::pair BatchInsert(const std::string& table, const ValuesBuckets& values) override; + std::pair BatchInsert(const std::string &table, const ValuesBuckets &values) override; std::pair Update(const std::string &table, const Row &row, const std::string &where, const Values &args, Resolution resolution) override; int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, const Values &args) override; @@ -68,8 +68,8 @@ public: int Restore(const std::string &backupPath, const std::vector &newKey) override; int Count(int64_t &outValue, const AbsRdbPredicates &predicates) override; int GetRebuilt(RebuiltType &rebuilt) override; - std::pair Attach(const RdbStoreConfig &config, const std::string &attachName, - int32_t waitTime) override; + std::pair Attach( + const RdbStoreConfig &config, const std::string &attachName, int32_t waitTime) override; std::pair Detach(const std::string &attachName, int32_t waitTime) override; int InterruptBackup() override; int32_t GetBackupStatus() const override; @@ -101,23 +101,23 @@ private: void InitSyncerParam(const RdbStoreConfig &config, bool created); int ExecuteByTrxId(const std::string &sql, int64_t trxId, bool closeConnAfterExecute = false, const std::vector &bindArgs = {}); - std::pair HandleDifferentSqlTypes(std::shared_ptr statement, - const std::string &sql, const ValueObject &object, int sqlType); + std::pair HandleDifferentSqlTypes( + std::shared_ptr statement, const std::string &sql, const ValueObject &object, int sqlType); int CheckAttach(const std::string &sql); std::pair BeginExecuteSql(const std::string &sql); int GetDataBasePath(const std::string &databasePath, std::string &backupFilePath); void DoCloudSync(const std::string &table); - int InnerBackup(const std::string& databasePath, - const std::vector& destEncryptKey = std::vector()); + int InnerBackup( + const std::string &databasePath, const std::vector &destEncryptKey = std::vector()); std::pair> CreateWritableConn(); - std::vector CreateBackupBindArgs(const std::string &databasePath, - const std::vector &destEncryptKey); - std::pair GetStatement(const std::string& sql, std::shared_ptr conn) const; - std::pair GetStatement(const std::string& sql, bool read = false) const; + std::vector CreateBackupBindArgs( + const std::string &databasePath, const std::vector &destEncryptKey); + std::pair GetStatement(const std::string &sql, std::shared_ptr conn) const; + std::pair GetStatement(const std::string &sql, bool read = false) const; int AttachInner(const RdbStoreConfig &config, const std::string &attachName, const std::string &dbPath, const std::vector &key, int32_t waitTime); - int SetDefaultEncryptSql(const std::shared_ptr &statement, std::string sql, - const RdbStoreConfig &config); + int SetDefaultEncryptSql( + const std::shared_ptr &statement, std::string sql, const RdbStoreConfig &config); int SetDefaultEncryptAlgo(const ConnectionPool::SharedConn &conn, const RdbStoreConfig &config); int GetSlaveName(const std::string &dbName, std::string &backupFilePath); bool TryGetMasterSlaveBackupPath(const std::string &srcPath, std::string &destPath, bool isRestore = false); diff --git a/relational_store/frameworks/native/rdb/mock/include/task_executor.h b/relational_store/frameworks/native/rdb/mock/include/task_executor.h index ebd6b51aa3b637b2fae74b5b88585da74444acb4..41deb916828a4393167c3ea53df62bf3d172952f 100644 --- a/relational_store/frameworks/native/rdb/mock/include/task_executor.h +++ b/relational_store/frameworks/native/rdb/mock/include/task_executor.h @@ -15,8 +15,8 @@ #ifndef DISTRIBUTED_NATIVE_RDB_TASK_EXECUTOR_H #define DISTRIBUTED_NATIVE_RDB_TASK_EXECUTOR_H #include -#include #include +#include namespace OHOS::NativeRdb { class TaskExecutor { public: diff --git a/relational_store/frameworks/native/rdb/mock/include/traits.h b/relational_store/frameworks/native/rdb/mock/include/traits.h index 4da630e861af361f2644eed361eccbef3fffac53..e641afd851e67c34ad1706c07f7c62f774e01e14 100644 --- a/relational_store/frameworks/native/rdb/mock/include/traits.h +++ b/relational_store/frameworks/native/rdb/mock/include/traits.h @@ -89,7 +89,7 @@ inline constexpr size_t variant_index_of_v = decltype(variant_index_test(std::de template std::enable_if_t, T *> get_if(std::variant *input) { -return std::get_if(input); + return std::get_if(input); } template @@ -101,16 +101,16 @@ std::enable_if_t, const T *> get_if(const std::variant ? convertible_index_of_v : 0> constexpr std::enable_if_t && convertible_in_v, -std::add_pointer_t>>> + std::add_pointer_t>>> get_if(std::variant *input) { -return std::get_if(input); + return std::get_if(input); } template ? convertible_index_of_v : 0> constexpr std::enable_if_t && convertible_in_v, -std::add_pointer_t>>> + std::add_pointer_t>>> get_if(const std::variant *input) { return std::get_if(input); @@ -119,8 +119,8 @@ get_if(const std::variant *input) template std::enable_if_t && !convertible_in_v, T *> get_if(std::variant *input) { -(void)input; -return nullptr; + (void)input; + return nullptr; } template diff --git a/relational_store/frameworks/native/rdb/mock/src/rdb_fault_hiview_reporter.cpp b/relational_store/frameworks/native/rdb/mock/src/rdb_fault_hiview_reporter.cpp index fc52d9c3eeeb14f2d04e4f6a4b467d68f3615a3d..8ec363bd7d791e159fe24cdd5c951f6528257bce 100644 --- a/relational_store/frameworks/native/rdb/mock/src/rdb_fault_hiview_reporter.cpp +++ b/relational_store/frameworks/native/rdb/mock/src/rdb_fault_hiview_reporter.cpp @@ -59,8 +59,8 @@ std::string RdbFaultHiViewReporter::GetTimeWithMilliseconds(time_t sec, int64_t (void)nsec; return ""; } -RdbCorruptedEvent RdbFaultHiViewReporter::Create(const RdbStoreConfig &config, int32_t errCode, - const std::string &appendix) +RdbCorruptedEvent RdbFaultHiViewReporter::Create( + const RdbStoreConfig &config, int32_t errCode, const std::string &appendix) { RdbCorruptedEvent eventInfo; return eventInfo; @@ -90,8 +90,8 @@ std::string RdbFaultHiViewReporter::Format(const std::map &debugs, - const std::string &header) +std::string RdbFaultHiViewReporter::FormatBrief( + const std::map &debugs, const std::string &header) { (void)debugs; (void)header; diff --git a/relational_store/frameworks/native/rdb/mock/src/rdb_radar_reporter.cpp b/relational_store/frameworks/native/rdb/mock/src/rdb_radar_reporter.cpp index fe87ca494fda9267a20e656bf7d1c043a7be1921..f6504da75da02043a457637396f8f2c252f16c56 100644 --- a/relational_store/frameworks/native/rdb/mock/src/rdb_radar_reporter.cpp +++ b/relational_store/frameworks/native/rdb/mock/src/rdb_radar_reporter.cpp @@ -14,6 +14,7 @@ */ #include "rdb_radar_reporter.h" + #include "rdb_errno.h" namespace OHOS::NativeRdb { @@ -30,7 +31,7 @@ RdbRadar::~RdbRadar() { } -RdbRadar& RdbRadar::operator=(int errCode) +RdbRadar &RdbRadar::operator=(int errCode) { errCode_ = errCode; return *this; @@ -41,7 +42,7 @@ RdbRadar::operator int() const return errCode_; } -void RdbRadar::LocalReport(int bizSence, const char* funcName, int state, int errCode) +void RdbRadar::LocalReport(int bizSence, const char *funcName, int state, int errCode) { (void)scene_; (void)funcName_; @@ -51,4 +52,4 @@ std::string RdbRadar::GetHostPkgInfo() { return ""; } -} \ No newline at end of file +} // namespace OHOS::NativeRdb \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/mock/src/task_executor.cpp b/relational_store/frameworks/native/rdb/mock/src/task_executor.cpp index 3249537fb462b5b9a84ef63aa7619ceaa84eadb1..f0f6e7cc3e27025421df76fda7179a6128d2abad 100644 --- a/relational_store/frameworks/native/rdb/mock/src/task_executor.cpp +++ b/relational_store/frameworks/native/rdb/mock/src/task_executor.cpp @@ -16,7 +16,7 @@ #include "task_executor.h" namespace OHOS::NativeRdb { -TaskExecutor::TaskExecutor():pool_(nullptr) +TaskExecutor::TaskExecutor() : pool_(nullptr) { } diff --git a/relational_store/frameworks/native/rdb/src/connection_pool.cpp b/relational_store/frameworks/native/rdb/src/connection_pool.cpp index a1a6e564300b3b9104bb6c4b2b30552ded5588ed..b672efb62256f1ce761f98a12c9574c48a80555c 100644 --- a/relational_store/frameworks/native/rdb/src/connection_pool.cpp +++ b/relational_store/frameworks/native/rdb/src/connection_pool.cpp @@ -83,6 +83,9 @@ std::pair> ConnPool::HandleDataCorr } else if (storeConfig.GetAllowRebuild()) { Connection::Delete(storeConfig); rebuiltType = RebuiltType::REBUILT; + } else if (storeConfig.IsEncrypt() && storeConfig.GetEncryptKey().empty()) { + errCode = E_INVALID_SECRET_KEY; + return result; } else { errCode = E_SQLITE_CORRUPT; return result; @@ -301,7 +304,8 @@ void ConnPool::ReleaseNode(std::shared_ptr node, bool reuse) } auto now = steady_clock::now(); - auto timeout = now > (failedTime_.load() + minutes(CHECK_POINT_INTERVAL)) || now < failedTime_.load(); + auto timeout = now > (failedTime_.load() + minutes(CHECK_POINT_INTERVAL)) || now < failedTime_.load() || + failedTime_.load() == steady_clock::time_point(); auto transCount = transCount_ + isInTransaction_; auto remainCount = reuse ? transCount : transCount - 1; auto errCode = node->Unused(remainCount, timeout); diff --git a/relational_store/frameworks/native/rdb/src/rdb_notifier_stub.cpp b/relational_store/frameworks/native/rdb/src/rdb_notifier_stub.cpp index 56467e66254011ab65d0e1328ae33cdac2c2d40a..8c5c1a1f20d7aba7ddcabe58dcfb73daf2c10140 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_notifier_stub.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_notifier_stub.cpp @@ -52,7 +52,7 @@ int RdbNotifierStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Message return RDB_ERROR; } - if (code >= 0 && code < static_cast(NotifierIFCode::RDB_NOTIFIER_CMD_MAX)) { + if (code < static_cast(NotifierIFCode::RDB_NOTIFIER_CMD_MAX)) { return (this->*HANDLES[code])(data, reply); } 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 a5503baf240ea0f243f6bd4d2f71cafd3a04b880..2628b48b72a2f1210c2f5cb1b39170f3fb4cb7c3 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp @@ -307,6 +307,10 @@ int RdbStoreImpl::SetDistributedTables( } int32_t errorCode = service->SetDistributedTables( syncerParam_, tables, distributedConfig.references, distributedConfig.isRebuild, type); + if (type == DistributedRdb::DISTRIBUTED_DEVICE) { + int SYNC_DATA_INDEX = 500; + Reportor::Report(Reportor::Create(config_, SYNC_DATA_INDEX, "RdbDeviceToDeviceDataSync")); + } if (errorCode != E_OK) { LOG_ERROR("Fail to set distributed tables, error=%{public}d", errorCode); return errorCode; @@ -892,8 +896,10 @@ RdbStoreImpl::RdbStoreImpl(const RdbStoreConfig &config, int &errCode) path_ = (config.GetRoleType() != OWNER) ? config.GetVisitorDir() : config.GetPath(); bool created = access(path_.c_str(), F_OK) != 0; connectionPool_ = ConnectionPool::Create(config_, errCode); - if (connectionPool_ == nullptr && errCode == E_SQLITE_CORRUPT && !isReadOnly_) { - LOG_ERROR("database corrupt, %{public}s, %{public}s", SqliteUtils::Anonymous(name_).c_str(), + if (connectionPool_ == nullptr && (errCode == E_SQLITE_CORRUPT || errCode == E_INVALID_SECRET_KEY) && + !isReadOnly_) { + LOG_ERROR("database corrupt, errCode:0x%{public}x, %{public}s, %{public}s", errCode, + SqliteUtils::Anonymous(name_).c_str(), Reportor::FormatBrief(Connection::Collect(config_), "master").c_str()); #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) RdbParam param; diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp index 8ec1f12b6cc33bff3eca5b01c156d333741a7206..09f742a14f0d664fbf2ad4d73a9632a78d61dee4 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp @@ -88,24 +88,22 @@ std::shared_ptr RdbStoreManager::GetRdbStore( const RdbStoreConfig &config, int &errCode, int version, RdbOpenCallback &openCallback) { // TOD this lock should only work on storeCache_, add one more lock for connectionpool + errCode = E_OK; std::lock_guard lock(mutex_); - auto path = config.GetRoleType() != OWNER ? config.GetVisitorDir() : config.GetPath(); - bundleName_ = config.GetBundleName(); - std::shared_ptr rdbStore = GetStoreFromCache(config, path); - if (rdbStore != nullptr) { - return rdbStore; + if (config.GetRoleType() == VISITOR_WRITE && !IsPermitted(GetSyncParam(config))) { + errCode = E_ERROR; + return nullptr; } RdbStoreConfig modifyConfig = config; + auto path = config.GetRoleType() != OWNER ? config.GetVisitorDir() : config.GetPath(); if (modifyConfig.GetRoleType() == OWNER && IsConfigInvalidChanged(path, modifyConfig)) { errCode = E_CONFIG_INVALID_CHANGE; return nullptr; } - - if (modifyConfig.GetRoleType() == VISITOR_WRITE && !IsPermitted(GetSyncParam(config))) { - errCode = E_PERMISSION_DENIED; - return nullptr; + std::shared_ptr rdbStore = GetStoreFromCache(modifyConfig, path); + if (rdbStore != nullptr) { + return rdbStore; } - rdbStore = std::make_shared(modifyConfig, errCode); if (errCode != E_OK && modifyConfig != config) { LOG_WARN("Failed to GetRdbStore using modifyConfig. path:%{public}s, rc=%{public}d", @@ -138,31 +136,25 @@ std::shared_ptr RdbStoreManager::GetRdbStore( bool RdbStoreManager::IsConfigInvalidChanged(const std::string &path, RdbStoreConfig &config) { - Param param = GetSyncParam(config); - Param tempParam; if (config.GetBundleName().empty()) { LOG_WARN("Config has no bundleName, path: %{public}s", SqliteUtils::Anonymous(path).c_str()); return false; } - if (!configCache_.Get(path, tempParam)) { + Param lastParam; + if (!configCache_.Get(path, lastParam) && GetParamFromService(lastParam) != E_OK) { LOG_WARN("Not found config cache, path: %{public}s", SqliteUtils::Anonymous(path).c_str()); - tempParam = param; - if (GetParamFromService(tempParam) == E_OK) { - configCache_.Set(path, tempParam); - } else { - return false; - }; + return false; }; - bool isLevelInvalidChange = (tempParam.level_ > param.level_); - bool isEncryptInvalidChange = (tempParam.isEncrypt_ != param.isEncrypt_); - bool isAreaInvalidChange = (tempParam.area_ != param.area_); + bool isLevelInvalidChange = (static_cast(config.GetSecurityLevel()) > lastParam.level_); + bool isEncryptInvalidChange = (config.IsEncrypt() != lastParam.isEncrypt_); + bool isAreaInvalidChange = (config.GetArea() != lastParam.area_); if (isLevelInvalidChange || isEncryptInvalidChange || isAreaInvalidChange) { LOG_WARN("Store config invalid change, storePath %{public}s, securitylevel: %{public}d -> %{public}d, " "area: %{public}d -> %{public}d, isEncrypt: %{public}d -> %{public}d", - SqliteUtils::Anonymous(path).c_str(), tempParam.level_, param.level_, tempParam.area_, param.area_, - tempParam.isEncrypt_, param.isEncrypt_); + SqliteUtils::Anonymous(path).c_str(), lastParam.level_, static_cast(config.GetSecurityLevel()), + lastParam.area_, config.GetArea(), lastParam.isEncrypt_, config.IsEncrypt()); if (isEncryptInvalidChange) { - config.SetEncryptStatus(tempParam.isEncrypt_); + config.SetEncryptStatus(lastParam.isEncrypt_); } } return false; @@ -201,11 +193,7 @@ int32_t RdbStoreManager::GetParamFromService(DistributedRdb::RdbSyncerParam &par return E_ERROR; } err = service->BeforeOpen(param); - if (err != DistributedRdb::RDB_OK && err != DistributedRdb::RDB_NO_META) { - LOG_ERROR("BeforeOpen failed, err is %{public}d.", err); - return E_ERROR; - } - return E_OK; + return err != DistributedRdb::RDB_OK ? E_ERROR : E_OK; #endif return E_ERROR; } @@ -302,7 +290,6 @@ bool RdbStoreManager::Delete(const std::string &path) if (!tokens.empty()) { DistributedRdb::RdbSyncerParam param; param.storeName_ = *tokens.rbegin(); - param.bundleName_ = bundleName_; auto [err, service] = DistributedRdb::RdbManagerImpl::GetInstance().GetRdbService(param); if (err != E_OK || service == nullptr) { LOG_DEBUG("GetRdbService failed, err is %{public}d.", err); diff --git a/relational_store/frameworks/native/rdb/src/security_policy.cpp b/relational_store/frameworks/native/rdb/src/security_policy.cpp index 71cb60fbd8d557044939b0b06ccf346287779473..2a2e304038c09daf04e7110c483068a4ed994c70 100644 --- a/relational_store/frameworks/native/rdb/src/security_policy.cpp +++ b/relational_store/frameworks/native/rdb/src/security_policy.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace NativeRdb { using namespace OHOS::Rdb; +using namespace FileManagement::ModuleSecurityLabel; std::string SecurityPolicy::GetSecurityLevelValue(SecurityLevel securityLevel) { switch (securityLevel) { @@ -41,17 +42,14 @@ std::string SecurityPolicy::GetSecurityLevelValue(SecurityLevel securityLevel) std::string SecurityPolicy::GetFileSecurityLevel(const std::string &filePath) { - return FileManagement::ModuleSecurityLabel::SecurityLabel::GetSecurityLabel(filePath); + return SecurityLabel::GetSecurityLabel(filePath); } int SecurityPolicy::SetSecurityLabel(const RdbStoreConfig &config) { if (config.GetStorageMode() != StorageMode::MODE_MEMORY && config.GetSecurityLevel() != SecurityLevel::LAST) { auto toSetLevel = GetSecurityLevelValue(config.GetSecurityLevel()); - auto errCode = - FileManagement::ModuleSecurityLabel::SecurityLabel::SetSecurityLabel(config.GetPath(), toSetLevel) - ? E_OK - : E_CONFIG_INVALID_CHANGE; + auto errCode = SecurityLabel::SetSecurityLabel(config.GetPath(), toSetLevel) ? E_OK : E_CONFIG_INVALID_CHANGE; if (errCode != E_OK) { auto currentLevel = GetFileSecurityLevel(config.GetPath()); LOG_ERROR("storeName:%{public}s SetSecurityLabel failed. Set security level from %{public}s to %{public}s," diff --git a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp index a5455c66f5b8a090dc7dc86b1b140e5c427f3067..631b0313c83261570b24aa987028d06003af066a 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_connection.cpp @@ -651,7 +651,7 @@ int SqliteConnection::SetEncrypt(const RdbStoreConfig &config) int SqliteConnection::SetEncryptKey(const std::vector &key, const RdbStoreConfig &config) { if (key.empty()) { - return E_INVALID_ARGS; + return E_INVALID_SECRET_KEY; } auto errCode = sqlite3_key(dbHandle_, static_cast(key.data()), static_cast(key.size())); diff --git a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp index 2eaa63c45cf7a9c010df34ee133bd0d7a6ef6af7..f9af140b4ccd9c0b5b7f41192bcac4e37acdf4a0 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp @@ -206,8 +206,6 @@ int SqliteStatement::Prepare(const std::string &sql) if (errCode != E_OK) { LOG_WARN("slave prepare Error:%{public}d", errCode); SqliteUtils::SetSlaveInvalid(config_->GetPath()); - RdbStoreConfig slaveConfig(SqliteUtils::GetSlavePath(config_->GetPath())); - Reportor::ReportFault(Reportor::Create(slaveConfig, errCode, "ErrorType: slavePrepareErr")); } } return E_OK; @@ -249,8 +247,6 @@ int SqliteStatement::Bind(const std::vector &args) if (errCode != E_OK) { LOG_ERROR("slave bind error:%{public}d", errCode); SqliteUtils::SetSlaveInvalid(config_->GetPath()); - RdbStoreConfig slaveConfig(SqliteUtils::GetSlavePath(config_->GetPath())); - Reportor::Report(Reportor::Create(slaveConfig, errCode, "ErrorType: slaveBindErr")); } } return E_OK; @@ -391,8 +387,6 @@ int32_t SqliteStatement::Execute(const std::vectorGetPath()); - RdbStoreConfig slaveConfig(SqliteUtils::GetSlavePath(config_->GetPath())); - Reportor::Report(Reportor::Create(slaveConfig, errCode, "ErrorType: slaveExecErr")); } } return E_OK; diff --git a/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp b/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp index 87c345860d18d8b648af429ca35dcf68518859b4..c7d02545feebecfec3c504d2d6ac373beeef7b55 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_utils.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -44,19 +45,15 @@ constexpr int32_t FILE_PATH_MINI_SIZE = 6; constexpr int32_t AREA_MINI_SIZE = 4; constexpr int32_t AREA_OFFSET_SIZE = 5; constexpr int32_t PRE_OFFSET_SIZE = 1; -constexpr int32_t CREATE_DATABASE_SIZE = 15; -constexpr int32_t SQL_TYPE_SIZE = 3; constexpr int32_t MIN_ANONYMIZE_LENGTH = 2; constexpr int32_t MAX_ANONYMIZE_LENGTH = 4; -constexpr int32_t OTHER_SIZE = 6; -constexpr int32_t START_SIZE = 0; -const std::vector SELECT_ARRAY = { "AS", "GROUPBY", "GROUP", "BY", "LIMIT", "COUNT", "AVERAGE", "SELECT", - "FROM", "WHERE", "DISTRICT" }; -const std::vector INSERT_ARRAY = { "INSERT", "INTO", "VALUES" }; -const std::vector UPDATE_ARRAY = { "UPDATE", "SET", "WHERE", "AND", "OR" }; -const std::vector DELETE_ARRAY = { "DELETE", "FROM", "WHERE" }; -const std::vector DROP_ARRAY = { "DROP", "TABLE", "IF", "EXISTS", "DATABASE" }; -const std::vector PRAGMA_ARRAY = { "PRAGMA" }; + +constexpr const char *SQL_ARRAY[] = { "AS", "GROUPBY", "GROUP", "BY", "LIMIT", "COUNT", "AVERAGE", "SELECT", "FROM", + "WHERE", "DISTRICT", "INSERT", "INTO", "VALUES", "CREATE", "TABLE", "DATABASE", "VIEW", "INDEX", "TRIGGER", + "PROCEDURE", "IF", "NOT", "EXISTS", "INT", "PRIMARY", "KEY", "TEXT", "BLOB", "REAL", "ASSET", "ASSETS", "NULL", + "INTEGER", "UNLIMITED", "UNION", "UPDATE", "SET", "WHERE", "AND", "OR", "DELETE", "FROM", "DROP", "PRAGMA", + "ALTER", "ADD", "COLUMN", "MODIFY" }; +constexpr const uint32_t SQL_ARRAY_LENGTH = 49; constexpr SqliteUtils::SqlType SqliteUtils::SQL_TYPE_MAP[]; constexpr const char *SqliteUtils::ON_CONFLICT_CLAUSE[]; @@ -252,17 +249,17 @@ std::string SqliteUtils::Anonymous(const std::string &srcFile) return srcFile.substr(0, pre + PRE_OFFSET_SIZE) + "***" + path + fileName; } -bool IsSpecialChar(char c) +bool SqliteUtils::IsSpecialChar(char c) { return (c == ' ' || c == '.' || c == ',' || c == '!' || c == '?' || c == ':' || c == '(' || c == ')' || c == ';'); } -std::vector SplitString(const std::string &input) +std::vector SqliteUtils::SplitString(const std::string &input) { std::vector result; std::string word; for (char c : input) { - if (!IsSpecialChar(c)) { + if (!SqliteUtils::IsSpecialChar(c)) { word += c; } else { if (!word.empty()) { @@ -278,7 +275,7 @@ std::vector SplitString(const std::string &input) return result; } -std::string ReplaceMultipleSpaces(const std::string &str) +std::string SqliteUtils::ReplaceMultipleSpaces(const std::string &str) { std::string result = str; if (result.empty()) { @@ -290,7 +287,7 @@ std::string ReplaceMultipleSpaces(const std::string &str) return std::regex_replace(result, std::regex(" +"), " "); } -std::string AnonyWord(const std::string &word) +std::string SqliteUtils::AnonyWord(const std::string &word) { std::string anonyWord = word; if (word.size() == 1 && std::isdigit(word[0])) { @@ -306,205 +303,39 @@ std::string AnonyWord(const std::string &word) return anonyWord; } -std::string AnonyString(const std::string &input) +bool SqliteUtils::Find(const std::string &word, const char *const array[], uint32_t length) { - std::vector words = SplitString(input); - std::string result; - for (const std::string &word : words) { - std::string anonyWord = AnonyWord(word); - result += anonyWord; + for (uint32_t i = 0; i < length; i++) { + if (word == array[i]) { + return true; + } } - return result; + return false; } -std::string AnonySqlString(const std::string &input, const std::vector &array) +std::string SqliteUtils::AnonySqlString(const std::string &input, const char *const array[], uint32_t length) { - std::vector words = SplitString(input); + std::vector words = SqliteUtils::SplitString(input); std::string result; for (const std::string &word : words) { + if (word.empty() || word.find_first_of("\r\n") != std::string::npos) { + continue; + } std::string anonyWord = word; std::string upperWord = SqliteUtils::StrToUpper(word); - if (std::find(array.begin(), array.end(), upperWord) == array.end()) { - anonyWord = AnonyWord(anonyWord); + bool found = Find(upperWord, array, length); + if (!found) { + anonyWord = SqliteUtils::AnonyWord(anonyWord); } result += anonyWord; } return result; } -std::string AnonyCreateTable(std::string &str) -{ - size_t lastSpacePos; - if (!str.empty() && str.back() == ' ') { - str = str.substr(0, str.length() - 1); - } - lastSpacePos = str.find_last_of(' '); - if (lastSpacePos != std::string::npos) { - str.replace(lastSpacePos + 1, str.length() - lastSpacePos, - AnonyString(str.substr(lastSpacePos + 1, str.length() - lastSpacePos))); - } - return str; -} - -std::string AnonyCreateColumn(std::string &str) -{ - std::vector tokens; - std::string delimiter = ","; - size_t pos = 0; - - while ((pos = str.find(delimiter)) != std::string::npos) { - std::string token = str.substr(0, pos); - tokens.push_back(token); - str.erase(0, pos + delimiter.length()); - } - tokens.push_back(str); - std::string result; - for (const auto &token : tokens) { - std::string repToken = ReplaceMultipleSpaces(token); - size_t spacePos = repToken.find(' '); - if (spacePos != std::string::npos) { - std::string replacedToken = AnonyString(repToken.substr(0, spacePos)) + repToken.substr(spacePos); - if (!result.empty()) { - result += ", "; - } - result += replacedToken; - } - } - return result; -} - -std::string MaskedCreateSql(const std::string &sql) -{ - auto pre = sql.find("("); - auto end = sql.rfind(")"); - auto table = sql.substr(0, pre); - auto column = sql.substr(pre, end - pre); - table = AnonyCreateTable(table); - column = AnonyCreateColumn(column); - return table + " " + column + ")"; -} - -std::string AnonyAlterDrop(const std::smatch &match, const std::string &sql) -{ - std::string columns = match[1].str(); - std::string table = match[2].str(); - std::string maskedSql = std::regex_replace(sql, - std::regex("ALTER\\s+TABLE\\s+(.*)\\s+DROP COLUMN\\s+([^\\s;]+)", std::regex_constants::icase), - "ALTER TABLE " + AnonyString(columns) + " DROP COLUMN " + AnonyString(table)); - return maskedSql; -} - -std::string AnonyAlterAdd(const std::smatch &match, const std::string &sql) -{ - std::string columns = match[1].str(); - std::string table = match[2].str(); - std::string maskedSql = std::regex_replace(sql, - std::regex("ALTER\\s+TABLE\\s+(.*)\\s+ADD COLUMN\\s+([^\\s;]+)", std::regex_constants::icase), - "ALTER TABLE " + AnonyString(columns) + " ADD COLUMN " + AnonyString(table)); - return maskedSql; -} - -std::string AnonySelectSql(const std::string &sql, const std::string &array) -{ - return AnonySqlString(sql, SELECT_ARRAY); -} - -std::string AnonyInsertSql(const std::string &sql, const std::string &array) -{ - return AnonySqlString(sql, INSERT_ARRAY); -} - -std::string AnonyUpdateSql(const std::string &sql, const std::string &array) -{ - return AnonySqlString(sql, UPDATE_ARRAY); -} - -std::string AnonyDeleteSql(const std::string &sql, const std::string &array) -{ - return AnonySqlString(sql, DELETE_ARRAY); -} - -std::string AnonyCreateSql(const std::string &replaceSql) -{ - std::regex createDatabaseRegex("CREATE\\s+DATABASE\\s+([^\\s;]+)", std::regex_constants::icase); - std::regex createTableRegex("CREATE\\s+TABLE\\s+([^\\s;]+)", std::regex_constants::icase); - std::smatch match; - if (std::regex_search(replaceSql, match, createDatabaseRegex)) { - std::string maskedSql = - replaceSql.substr(START_SIZE, CREATE_DATABASE_SIZE) + AnonyString(replaceSql.substr(CREATE_DATABASE_SIZE)); - return maskedSql; - } else if (std::regex_search(replaceSql, match, createTableRegex)) { - std::string maskedSql = MaskedCreateSql(replaceSql); - return maskedSql; - } - return replaceSql; -} - -std::string AnonyDropSql(const std::string &sql, const std::string &array) -{ - return AnonySqlString(sql, DROP_ARRAY); -} - -std::string AnonyPragmaSql(const std::string &sql, const std::string &array) -{ - return AnonySqlString(sql, PRAGMA_ARRAY); -} - -std::string AnonyAlterSql(const std::string &replaceSql) -{ - std::regex alterDropRegex("ALTER\\s+TABLE\\s+(.*)\\s+DROP COLUMN\\s+([^\\s;]+)", std::regex_constants::icase); - std::regex alterAddRegex("ALTER\\s+TABLE\\s+(.*)\\s+ADD COLUMN\\s+([^\\s;]+)", std::regex_constants::icase); - std::smatch match; - if (std::regex_search(replaceSql, match, alterDropRegex)) { - return AnonyAlterDrop(match, replaceSql); - } else if (std::regex_search(replaceSql, match, alterAddRegex)) { - return AnonyAlterAdd(match, replaceSql); - } - return replaceSql; -} - - std::string SqliteUtils::AnonySql(const std::string &sql) { - std::string replaceSql = ReplaceMultipleSpaces(sql); - std::string sqlType; - if (replaceSql.size() > SQL_TYPE_SIZE) { - sqlType = StrToUpper(replaceSql.substr(START_SIZE, SQL_TYPE_SIZE)); - } else { - return replaceSql; - } - std::smatch match; - if (sqlType == "SEL") { - return AnonySqlString(replaceSql, SELECT_ARRAY); - } - if (sqlType == "INS") { - return AnonySqlString(replaceSql, INSERT_ARRAY); - } - if (sqlType == "UPD") { - return AnonySqlString(replaceSql, UPDATE_ARRAY); - } - if (sqlType == "DEL") { - return AnonySqlString(replaceSql, DELETE_ARRAY); - } - if (sqlType == "CRE") { - return AnonyCreateSql(replaceSql); - } - if (sqlType == "DRO") { - return AnonySqlString(replaceSql, DROP_ARRAY); - } - if (sqlType == "PRA") { - return AnonySqlString(replaceSql, PRAGMA_ARRAY); - } - if (sqlType == "ALT") { - return AnonyAlterSql(replaceSql); - } - - if (replaceSql.length() > OTHER_SIZE) { - std::string maskedSql = replaceSql.substr(START_SIZE, OTHER_SIZE) + AnonyString(replaceSql.substr(OTHER_SIZE)); - return maskedSql; - } - - return replaceSql; + std::string replaceSql = SqliteUtils::ReplaceMultipleSpaces(sql); + return SqliteUtils::AnonySqlString(replaceSql, SQL_ARRAY, SQL_ARRAY_LENGTH); } ssize_t SqliteUtils::GetFileSize(const std::string &fileName) diff --git a/relational_store/frameworks/native/rdb_data_ability_adapter/src/result_set_utils.cpp b/relational_store/frameworks/native/rdb_data_ability_adapter/src/result_set_utils.cpp index b9aef63ea3e44614e9d2c83c4acf2309dccc77ae..a300c38feefdfc96afa348c541031bb11633b073 100644 --- a/relational_store/frameworks/native/rdb_data_ability_adapter/src/result_set_utils.cpp +++ b/relational_store/frameworks/native/rdb_data_ability_adapter/src/result_set_utils.cpp @@ -106,6 +106,6 @@ std::pair> ResultSetUtils::GetColumnNames() { std::vector names; auto errCode = resultSet_->GetAllColumnNames(names); - return {errCode, std::move(names)}; -} + return { errCode, std::move(names) }; } +} // namespace OHOS::RdbDataAbilityAdapter diff --git a/relational_store/frameworks/native/rdb_device_manager_adapter/include/rdb_device_manager_adapter.h b/relational_store/frameworks/native/rdb_device_manager_adapter/include/rdb_device_manager_adapter.h index 984d1193c4221fc7f630bda726d6e6db7ea9b0fe..7d0929e4a66bd4cea204f9bb5a1c8507c37502e0 100644 --- a/relational_store/frameworks/native/rdb_device_manager_adapter/include/rdb_device_manager_adapter.h +++ b/relational_store/frameworks/native/rdb_device_manager_adapter/include/rdb_device_manager_adapter.h @@ -42,6 +42,6 @@ public: ~InitDeviceManagerCallback() {}; void OnRemoteDied() override {}; }; -} // namespace DeviceManagerAdaptor -} // namespace OHOS +} // namespace DeviceManagerAdaptor +} // namespace OHOS #endif // RDB_DEVICE_MANAGER_ADAPTER_H diff --git a/relational_store/frameworks/native/rdb_device_manager_adapter/src/rdb_device_manager_adapter.cpp b/relational_store/frameworks/native/rdb_device_manager_adapter/src/rdb_device_manager_adapter.cpp index 87731eb2b3c49d7c9d2db9535df1ae72784ba730..801ed84b983c4468b2397047ea34f1429bb86969 100644 --- a/relational_store/frameworks/native/rdb_device_manager_adapter/src/rdb_device_manager_adapter.cpp +++ b/relational_store/frameworks/native/rdb_device_manager_adapter/src/rdb_device_manager_adapter.cpp @@ -33,7 +33,7 @@ RdbDeviceManagerAdaptor::~RdbDeviceManagerAdaptor() UnInit(); } -RdbDeviceManagerAdaptor& RdbDeviceManagerAdaptor::GetInstance(const std::string &packageName) +RdbDeviceManagerAdaptor &RdbDeviceManagerAdaptor::GetInstance(const std::string &packageName) { static RdbDeviceManagerAdaptor instance(packageName); return instance; diff --git a/relational_store/interfaces/inner_api/appdatafwk/include/multi_platform_endian.h b/relational_store/interfaces/inner_api/appdatafwk/include/multi_platform_endian.h index f62c5e973535128b5162b3a2214e0352a78e9abc..1ccedf8816f14e020415078053663d463689f858 100644 --- a/relational_store/interfaces/inner_api/appdatafwk/include/multi_platform_endian.h +++ b/relational_store/interfaces/inner_api/appdatafwk/include/multi_platform_endian.h @@ -17,6 +17,7 @@ #define MULTI_PLATFORM_EDIAN #include + #include "rdb_visibility.h" namespace OHOS { class API_EXPORT Endian final { diff --git a/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h b/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h index ed889b9f19e8a2b5d62b75301a2a9cb2233b6341..edae9b8132cb9690cc91162fbdb9f13aa5f5ab7f 100644 --- a/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h +++ b/relational_store/interfaces/inner_api/appdatafwk/include/shared_block.h @@ -16,14 +16,15 @@ #ifndef SHARED_BLOCK_H #define SHARED_BLOCK_H -#include +#include +#include #include -#include + #include "message_parcel.h" #include "parcel.h" -#include "securec.h" #include "rdb_visibility.h" +#include "securec.h" namespace OHOS { namespace AppDataFwk { @@ -374,10 +375,11 @@ private: inline int PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type); - static int CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, - SharedBlock *&outSharedBlock); + static int CreateSharedBlock( + const std::string &name, size_t size, sptr ashmem, SharedBlock *&outSharedBlock); - inline void *OffsetToPtr(uint32_t offset, uint32_t bufferSize = 0) { + inline void *OffsetToPtr(uint32_t offset, uint32_t bufferSize = 0) + { uint32_t safeOffset = offset; if (safeOffset + bufferSize > mSize) { return nullptr; diff --git a/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h b/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h index d3d65c850ba3382369cb534da831fd34c01829e8..1351c79556543f0ea40dc35716d20905028320c6 100644 --- a/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h +++ b/relational_store/interfaces/inner_api/cloud_data/include/cloud_service.h @@ -15,11 +15,13 @@ #ifndef OHOS_DISTRIBUTED_DATA_CLOUD_CLOUD_SERVICE_H #define OHOS_DISTRIBUTED_DATA_CLOUD_CLOUD_SERVICE_H -#include #include + +#include #include #include #include + #include "cloud_types.h" #include "common_types.h" #include "rdb_types.h" @@ -100,9 +102,9 @@ public: virtual int32_t Clean(const std::string &id, const std::map &actions) = 0; virtual int32_t NotifyDataChange(const std::string &id, const std::string &bundleName) = 0; virtual int32_t NotifyDataChange(const std::string &eventId, const std::string &extraData, int32_t userId) = 0; - virtual std::pair> QueryStatistics(const std::string &id, - const std::string &bundleName, const std::string &storeId) = 0; - virtual int32_t SetGlobalCloudStrategy(Strategy strategy, const std::vector& values) = 0; + virtual std::pair> QueryStatistics( + const std::string &id, const std::string &bundleName, const std::string &storeId) = 0; + virtual int32_t SetGlobalCloudStrategy(Strategy strategy, const std::vector &values) = 0; virtual std::pair> AllocResourceAndShare(const std::string &storeId, const DistributedRdb::PredicatesMemo &predicates, const std::vector &columns, @@ -116,10 +118,10 @@ public: virtual int32_t QueryByInvitation(const std::string &invitation, QueryResults &results) = 0; virtual int32_t ConfirmInvitation(const std::string &invitation, int32_t confirmation, std::tuple &result) = 0; - virtual int32_t ChangeConfirmation(const std::string &sharingRes, - int32_t confirmation, std::pair &result) = 0; + virtual int32_t ChangeConfirmation( + const std::string &sharingRes, int32_t confirmation, std::pair &result) = 0; - virtual int32_t SetCloudStrategy(Strategy strategy, const std::vector& values) = 0; + virtual int32_t SetCloudStrategy(Strategy strategy, const std::vector &values) = 0; virtual std::pair QueryLastSyncInfo( const std::string &id, const std::string &bundleName, const std::string &storeId) = 0; diff --git a/relational_store/interfaces/inner_api/cloud_data/include/cloud_types.h b/relational_store/interfaces/inner_api/cloud_data/include/cloud_types.h index cfceb52219fed0b95bdc63b7a09456b05992fc12..ee58798c00c8675d1dc4067b5f83916d6df0718c 100644 --- a/relational_store/interfaces/inner_api/cloud_data/include/cloud_types.h +++ b/relational_store/interfaces/inner_api/cloud_data/include/cloud_types.h @@ -16,10 +16,10 @@ #ifndef OHOS_DISTRIBUTED_DATA_CLOUD_CLOUD_TYPES_H #define OHOS_DISTRIBUTED_DATA_CLOUD_CLOUD_TYPES_H +#include #include #include #include -#include namespace OHOS::CloudData { enum Role : int32_t { diff --git a/relational_store/interfaces/inner_api/common_type/include/common_types.h b/relational_store/interfaces/inner_api/common_type/include/common_types.h index f7fbc7c98f91d63ee3e47088ba3af8041df47b0f..fd512f5527ab699ad1d55d8dd5cc7bba9626ce91 100644 --- a/relational_store/interfaces/inner_api/common_type/include/common_types.h +++ b/relational_store/interfaces/inner_api/common_type/include/common_types.h @@ -49,5 +49,5 @@ using Asset = AssetValue; using Assets = std::vector; using Value = std::variant; using ValuesBucket = std::map; -} +} // namespace OHOS::CommonType #endif // OHOS_COMMON_TYPES_H diff --git a/relational_store/interfaces/inner_api/dataability/include/ishared_result_set.h b/relational_store/interfaces/inner_api/dataability/include/ishared_result_set.h index 23e3941c97b08308cef0acbbdee26ba7004b90ac..224be7fe66198ac79e3cf7d80184bb6822d06f78 100644 --- a/relational_store/interfaces/inner_api/dataability/include/ishared_result_set.h +++ b/relational_store/interfaces/inner_api/dataability/include/ishared_result_set.h @@ -16,9 +16,10 @@ #ifndef DATAABILITY_I_SHARED_RESULT_SET_H #define DATAABILITY_I_SHARED_RESULT_SET_H #include -#include "iremote_broker.h" + #include "abs_shared_result_set.h" #include "distributeddata_relational_store_ipc_interface_code.h" +#include "iremote_broker.h" namespace OHOS::NativeRdb { class API_EXPORT ISharedResultSet : public AbsSharedResultSet, public IRemoteBroker { public: @@ -26,7 +27,7 @@ public: API_EXPORT static std::shared_ptr ReadFromParcel(MessageParcel &parcel); API_EXPORT static sptr WriteToParcel( std::shared_ptr resultSet, MessageParcel &parcel); - + private: static std::function(MessageParcel &parcel)> consumerCreator_; static std::function(std::shared_ptr, MessageParcel &)> providerCreator_; diff --git a/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h b/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h index 02d9f7d554b9b7e4c2065f55b04d50f86f7fb71f..84e994620e5369dc2666b8d5837a6b51c92d2b8d 100644 --- a/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h +++ b/relational_store/interfaces/inner_api/dataability/include/predicates_utils.h @@ -13,7 +13,6 @@ * limitations under the License. */ - #ifndef NATIVE_RDB_PREDICATES_UTILS_H #define NATIVE_RDB_PREDICATES_UTILS_H @@ -45,14 +44,14 @@ public: */ [[deprecated("Use SetWhereClauseAndArgs(AbsPredicates *, const std::string &," " const std::vector &) instead.")]] - API_EXPORT static void SetWhereClauseAndArgs(AbsPredicates *predicates, const std::string &whereClause, - const std::vector &whereArgs); + API_EXPORT static void SetWhereClauseAndArgs( + AbsPredicates *predicates, const std::string &whereClause, const std::vector &whereArgs); /** * @brief Set the parameter of whereClause and bindArgs of the specified Predicates. */ - API_EXPORT static void SetWhereClauseAndArgs(AbsPredicates *predicates, const std::string &whereClause, - const std::vector &bindArgs); + API_EXPORT static void SetWhereClauseAndArgs( + AbsPredicates *predicates, const std::string &whereClause, const std::vector &bindArgs); /** * @brief Sets parameters of the specified Predicates including distinct, index, group, order, limit and offset. diff --git a/relational_store/interfaces/inner_api/rdb/BUILD.gn b/relational_store/interfaces/inner_api/rdb/BUILD.gn index 927bd2f60836b5ae7ee416f607e0024320e84443..cd53a4a93a285d854a04a7903f09837c24d72345 100644 --- a/relational_store/interfaces/inner_api/rdb/BUILD.gn +++ b/relational_store/interfaces/inner_api/rdb/BUILD.gn @@ -164,6 +164,8 @@ if (is_ohos && !build_ohos_sdk) { "hisysevent:libhisysevent", "hitrace:hitrace_meter", "huks:libhukssdk", + "icu:shared_icui18n", + "icu:shared_icuuc", "ipc:ipc_core", "kv_store:database_utils", "kv_store:distributeddb", diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h b/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h index 2d0f494f7c97d02cb3b05a28a474b6a0ea77e20f..104f3c07aa5849167261dde8e38c83902208f9d9 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_predicates.h @@ -104,6 +104,7 @@ public: [[deprecated("Use NotIn(const std::string &, const std::vector &) instead.")]] API_EXPORT virtual AbsPredicates *NotIn(const std::string &field, const std::vector &values); API_EXPORT virtual AbsPredicates *NotIn(const std::string &field, const std::vector &values); + private: static constexpr const char *LOG_ORIGIN_FIELD = "#_flag"; @@ -128,8 +129,8 @@ private: } std::string RemoveQuotes(const std::string &source) const; void CheckIsNeedAnd(); - void AppendWhereClauseWithInOrNotIn(const std::string &methodName, const std::string &field, - const std::vector &replaceValues); + void AppendWhereClauseWithInOrNotIn( + const std::string &methodName, const std::string &field, const std::vector &replaceValues); }; } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h b/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h index 859964b57b8892ff88ad632ee4dceb82aba60f8c..b99b5c99a81f12c5eb121c98a9c2305c4e936c02 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_rdb_predicates.h @@ -13,7 +13,6 @@ * limitations under the License. */ - #ifndef NATIVE_RDB_ABSRDBPREDICATES_H #define NATIVE_RDB_ABSRDBPREDICATES_H @@ -74,7 +73,7 @@ public: * * @return Returns the self. */ - API_EXPORT AbsRdbPredicates *InDevices(std::vector& devices); + API_EXPORT AbsRdbPredicates *InDevices(std::vector &devices); /** * @brief Specify all remote devices which connect to local device when syncing distributed database. @@ -95,7 +94,7 @@ public: * * @return Returns the self. */ - API_EXPORT AbsRdbPredicates* EqualTo(const std::string &field, const ValueObject &value) override; + API_EXPORT AbsRdbPredicates *EqualTo(const std::string &field, const ValueObject &value) override; /** * @brief Restricts the value of the field to be not equal to the specified value to the remote AbsRdbPredicates. @@ -107,21 +106,21 @@ public: * * @return Returns the self. */ - API_EXPORT AbsRdbPredicates* NotEqualTo(const std::string &field, const ValueObject &value) override; + API_EXPORT AbsRdbPredicates *NotEqualTo(const std::string &field, const ValueObject &value) override; /** * @brief Adds an and condition to the remote AbsRdbPredicates. * * This method is similar to or of the SQL statement. */ - API_EXPORT AbsRdbPredicates* And() override; + API_EXPORT AbsRdbPredicates *And() override; /** * @brief Adds an or condition to the remote AbsRdbPredicates. * * This method is similar to or of the SQL statement. */ - API_EXPORT AbsRdbPredicates* Or() override; + API_EXPORT AbsRdbPredicates *Or() override; /** * @brief Adds an left bracket condition to the remote AbsRdbPredicates. @@ -248,7 +247,7 @@ public: * * @param field Indicates the column name for sorting the return list. */ - API_EXPORT AbsRdbPredicates* OrderByAsc(const std::string &field) override; + API_EXPORT AbsRdbPredicates *OrderByAsc(const std::string &field) override; /** * @brief Restricts the descending order of the return list. When there are several orders, @@ -256,12 +255,12 @@ public: * * @param field Indicates the column name for sorting the return list. */ - API_EXPORT AbsRdbPredicates* OrderByDesc(const std::string &field) override; + API_EXPORT AbsRdbPredicates *OrderByDesc(const std::string &field) override; /** * @brief Get predicates of remote device. */ - API_EXPORT const DistributedRdb::PredicatesMemo & GetDistributedPredicates() const; + API_EXPORT const DistributedRdb::PredicatesMemo &GetDistributedPredicates() const; /** * @brief Initialize relevant parameters of the union table. diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h b/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h index 98f7df3f37a344edb297942896bf5ad7d1a8d062..4abff006cf27d27bfbc0141bffdbaaadb69b9842 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h @@ -16,11 +16,11 @@ #ifndef NATIVE_RDB_ABS_RESULT_SET_H #define NATIVE_RDB_ABS_RESULT_SET_H +#include #include +#include #include #include -#include -#include #include "result_set.h" #include "value_object.h" @@ -330,7 +330,7 @@ protected: }; private: - Mtx* mutex_ = nullptr; + Mtx *mutex_ = nullptr; }; using Mutex = Lock; diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h b/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h index c055c7cf1d9afd622cb7b2350920603cb4218150..7a954abf3cb4f26aa38b824c3c7c5141ecd44055 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_shared_result_set.h @@ -140,6 +140,7 @@ protected: // The default position of the cursor static const int INIT_POS = -1; + private: int GetCustomerValue(int index, ValueObject &value, AppDataFwk::SharedBlock *block); int UpdateBlockPos(int position, int rowCnt); diff --git a/relational_store/interfaces/inner_api/rdb/include/asset_value.h b/relational_store/interfaces/inner_api/rdb/include/asset_value.h index 19b7df057b418da4a773bba7ba9a96c60e3bb75e..db5edad0346dee2b2c11902441080ecc878d3c78 100644 --- a/relational_store/interfaces/inner_api/rdb/include/asset_value.h +++ b/relational_store/interfaces/inner_api/rdb/include/asset_value.h @@ -70,5 +70,5 @@ struct AssetValue { return path < ref.path; } }; -} +} // namespace OHOS::NativeRdb #endif // OHOS_RELATIONAL_STORE_INNER_API_ASSET_VALUE_H diff --git a/relational_store/interfaces/inner_api/rdb/include/big_integer.h b/relational_store/interfaces/inner_api/rdb/include/big_integer.h index dc713d664e6471352871b1e76b86c3610c804e95..00ebe1c0ccf77d432ca45e0f38686e1d68f31d6d 100644 --- a/relational_store/interfaces/inner_api/rdb/include/big_integer.h +++ b/relational_store/interfaces/inner_api/rdb/include/big_integer.h @@ -15,8 +15,9 @@ #ifndef OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_INTERFACES_INNER_API_RDB_INCLUDE_BIG_INTEGER_H #define OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_INTERFACES_INNER_API_RDB_INCLUDE_BIG_INTEGER_H -#include #include + +#include #include #include "rdb_visibility.h" @@ -40,9 +41,10 @@ public: const uint64_t *TrueForm() const; std::vector Value() const; + private: int32_t sign_ = 0; std::vector value_; }; -} +} // namespace OHOS::NativeRdb #endif // OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_INTERFACES_INNER_API_RDB_INCLUDE_BIG_INTEGER_H diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_errno.h b/relational_store/interfaces/inner_api/rdb/include/rdb_errno.h index 68e7fcf6a5bf718b48311c40b0eff25e8fd28335..fe0a7b823e1c484716c5ad3bc763d4a0f6c95cd7 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_errno.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_errno.h @@ -406,9 +406,9 @@ static constexpr int E_SQLITE_SCHEMA = (E_BASE + 0x48); static constexpr int E_CANCEL = (E_BASE + 0x49); /** - * @brief Permission denied + * @brief The key parameter is invalid. */ -static constexpr int E_PERMISSION_DENIED = (E_BASE + 0x4a); +static constexpr int E_INVALID_SECRET_KEY = (E_BASE + 0x4a); /** * @brief Do not use except relational_store diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_helper.h b/relational_store/interfaces/inner_api/rdb/include/rdb_helper.h index d16645e073c18817dacb4158fecc1937526cda92..40e9ffd06a97170139a9c7eb509a96cb85d4814a 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_helper.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_helper.h @@ -58,7 +58,6 @@ public: * @brief Clear Cache. */ API_EXPORT static void ClearCache(); - }; } // namespace NativeRdb } // namespace OHOS diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_notifier.h b/relational_store/interfaces/inner_api/rdb/include/rdb_notifier.h index d31080f0e459babcc6298d49a5ddc3bb25158d12..5092c5030df303651ead183bb124fdba97faa9df 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_notifier.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_notifier.h @@ -15,15 +15,15 @@ #ifndef DISTRIBUTED_RDB_RDB_NOTIFIER_H #define DISTRIBUTED_RDB_RDB_NOTIFIER_H -#include "rdb_types.h" #include "distributeddata_relational_store_ipc_interface_code.h" +#include "rdb_types.h" namespace OHOS::DistributedRdb { class IRdbNotifier { public: using ChangeInfo = RdbStoreObserver::ChangeInfo; using PrimaryFields = std::map; virtual int32_t OnComplete(uint32_t seqNum, Details &&result) = 0; - virtual int32_t OnComplete(const std::string& storeName, Details &&result) = 0; + virtual int32_t OnComplete(const std::string &storeName, Details &&result) = 0; virtual int32_t OnChange(const Origin &origin, const PrimaryFields &primaries, ChangeInfo &&changeInfo) = 0; }; diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_service.h b/relational_store/interfaces/inner_api/rdb/include/rdb_service.h index 4a6ed38e19e8fdc060acda6723b88e21d0827f67..7643b92283198e62e92b79e858fdb0d91510ee9b 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_service.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_service.h @@ -19,10 +19,10 @@ #include #include -#include "result_set.h" -#include "rdb_types.h" -#include "rdb_notifier.h" #include "distributeddata_relational_store_ipc_interface_code.h" +#include "rdb_notifier.h" +#include "rdb_types.h" +#include "result_set.h" namespace OHOS { namespace DistributedRdb { @@ -40,18 +40,17 @@ public: virtual std::string ObtainDistributedTableName(const std::string &device, const std::string &table) = 0; - virtual int32_t SetDistributedTables( - const RdbSyncerParam ¶m, const std::vector &tables, + virtual int32_t SetDistributedTables(const RdbSyncerParam ¶m, const std::vector &tables, const std::vector &references, bool isRebuild, int32_t type = DISTRIBUTED_DEVICE) = 0; virtual int32_t Sync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, const AsyncDetail &async) = 0; - virtual int32_t Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - RdbStoreObserver *observer) = 0; + virtual int32_t Subscribe( + const RdbSyncerParam ¶m, const SubscribeOption &option, RdbStoreObserver *observer) = 0; - virtual int32_t UnSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, - RdbStoreObserver *observer) = 0; + virtual int32_t UnSubscribe( + const RdbSyncerParam ¶m, const SubscribeOption &option, RdbStoreObserver *observer) = 0; virtual int32_t RegisterAutoSyncCallback( const RdbSyncerParam ¶m, std::shared_ptr observer) = 0; @@ -77,7 +76,7 @@ public: virtual int32_t NotifyDataChange( const RdbSyncerParam ¶m, const RdbChangedData &rdbChangedData, const RdbNotifyConfig &rdbNotifyConfig) = 0; - virtual int32_t SetSearchable(const RdbSyncerParam& param, bool isSearchable) = 0; + virtual int32_t SetSearchable(const RdbSyncerParam ¶m, bool isSearchable) = 0; virtual int32_t Disable(const RdbSyncerParam ¶m) = 0; @@ -93,6 +92,6 @@ public: virtual int32_t VerifyPromiseInfo(const RdbSyncerParam ¶m) = 0; }; -} -} // namespace OHOS::DistributedRdb +} // namespace DistributedRdb +} // namespace OHOS #endif \ No newline at end of file diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_sql_utils.h b/relational_store/interfaces/inner_api/rdb/include/rdb_sql_utils.h index 7bb74cffc9e9fe76f6b060cb9aec182a537006aa..35f7b41ba7a6411cad898db29de7d3a8fbb1cd99 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_sql_utils.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_sql_utils.h @@ -29,8 +29,8 @@ public: /** * @brief get custom data base path. */ - static std::pair GetDefaultDatabasePath(const std::string &baseDir, - const std::string &name, const std::string &customDir = ""); + static std::pair GetDefaultDatabasePath( + const std::string &baseDir, const std::string &name, const std::string &customDir = ""); /** * @brief get default data base path. diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_store.h b/relational_store/interfaces/inner_api/rdb/include/rdb_store.h index b9fd988284c2d750b36e1b23f835c238254c139e..83232012f3d0c8273dd7645034746954064914ba 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_store.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_store.h @@ -16,8 +16,9 @@ #ifndef NATIVE_RDB_RDB_STORE_H #define NATIVE_RDB_RDB_STORE_H -#include #include + +#include #include #include @@ -122,8 +123,8 @@ public: class API_EXPORT ModifyTime { public: ModifyTime() = default; - API_EXPORT ModifyTime(std::shared_ptr result, std::map, PRIKey> hashKeys, - bool isFromRowId); + API_EXPORT ModifyTime( + std::shared_ptr result, std::map, PRIKey> hashKeys, bool isFromRowId); API_EXPORT operator std::map(); API_EXPORT operator std::shared_ptr(); API_EXPORT PRIKey GetOriginKey(const std::vector &hash); @@ -169,8 +170,8 @@ public: * @param resolution Indicates the {@link ConflictResolution} to insert data into the table. */ [[deprecated("Use Insert(const std::string &, const Row &, Resolution) instead.")]] - virtual int InsertWithConflictResolution(int64_t &outRowId, const std::string &table, const Row &row, - Resolution resolution = NO_ACTION); + virtual int InsertWithConflictResolution( + int64_t &outRowId, const std::string &table, const Row &row, Resolution resolution = NO_ACTION); /** * @brief Replaces a row of data into the target table. @@ -218,7 +219,7 @@ public: * @param args Indicates the where arguments. */ virtual int Update(int &changedRows, const std::string &table, const Row &row, const std::string &whereClause = "", - const Values &args = {}); + const Values &args = {}); /** * @brief Updates data in the database based on a a specified instance object of AbsRdbPredicates. @@ -239,8 +240,8 @@ public: * @param args Indicates the where arguments. */ [[deprecated("Use Update(int &, const std::string &, const Row &, const std::string &, const Values &) instead.")]] - virtual int Update(int &changedRows, const std::string &table, const Row &row, const std::string &whereClause, - const Olds &args); + virtual int Update( + int &changedRows, const std::string &table, const Row &row, const std::string &whereClause, const Olds &args); /** * @brief Updates data in the database based on a a specified instance object of RdbPredicates. @@ -278,8 +279,7 @@ public: * @param args Indicates the where arguments. */ [[deprecated("Use Delete(int &, const std::string &, const std::string &, const Values &) instead.")]] - virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, - const Olds &args); + virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause, const Olds &args); /** * @brief Deletes data from the database based on a specified instance object of AbsRdbPredicates. @@ -295,8 +295,8 @@ public: * @param whereClause Indicates the where clause. * @param args Indicates the where arguments. */ - virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause = "", - const Values &args = {}) = 0; + virtual int Delete( + int &deletedRows, const std::string &table, const std::string &whereClause = "", const Values &args = {}) = 0; /** * @brief Queries data in the database based on specified conditions. @@ -374,8 +374,8 @@ public: * @param predicates Indicates the specified query condition by the instance object of {@link AbsRdbPredicates}. * @param columns Indicates the columns to query. If the value is empty array, the query applies to all columns. */ - virtual std::shared_ptr RemoteQuery(const std::string &device, const AbsRdbPredicates &predicates, - const Fields &columns, int &errCode); + virtual std::shared_ptr RemoteQuery( + const std::string &device, const AbsRdbPredicates &predicates, const Fields &columns, int &errCode); /** * @brief Queries data in the database based on specified conditions. @@ -383,8 +383,8 @@ public: * @param predicates Indicates the specified query condition by the instance object of {@link AbsRdbPredicates}. * @param columns Indicates the columns to query. If the value is empty array, the query applies to all columns. */ - virtual std::pair> QuerySharingResource(const AbsRdbPredicates &predicates, - const Fields &columns); + virtual std::pair> QuerySharingResource( + const AbsRdbPredicates &predicates, const Fields &columns); /** * @brief Executes an SQL statement that contains specified parameters. @@ -583,22 +583,22 @@ public: /** * @brief Subscribe to event changes. */ - virtual int Subscribe(const SubscribeOption& option, RdbStoreObserver *observer); + virtual int Subscribe(const SubscribeOption &option, RdbStoreObserver *observer); /** * @brief UnSubscribe to event changes. */ - virtual int UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer); + virtual int UnSubscribe(const SubscribeOption &option, RdbStoreObserver *observer); /** * @brief SubscribeObserver to event changes. */ - virtual int SubscribeObserver(const SubscribeOption& option, const std::shared_ptr &observer); + virtual int SubscribeObserver(const SubscribeOption &option, const std::shared_ptr &observer); /** * @brief UnsubscribeObserver to event changes. */ - virtual int UnsubscribeObserver(const SubscribeOption& option, const std::shared_ptr &observer); + virtual int UnsubscribeObserver(const SubscribeOption &option, const std::shared_ptr &observer); /** * @brief Register message for auto sync operation. 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 bc6c26e407c3ade8018ac661e942be237c051f12..bc023157a29a5420682a110807c9f4dd38b92bb9 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 @@ -18,6 +18,7 @@ #include #include + #include "rdb_types.h" #include "rdb_visibility.h" @@ -198,7 +199,7 @@ using DistributedType = OHOS::DistributedRdb::RdbDistributedType; /** * @brief Use ScalarFunction replace std::function&)>. */ -using ScalarFunction = std::function&)>; +using ScalarFunction = std::function &)>; struct ScalarFunctionInfo { ScalarFunctionInfo(ScalarFunction function, int argc) : function_(function), argc_(argc) {} @@ -236,7 +237,7 @@ public: /** * @brief The constant indicates the database default page size. */ - static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ + static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ /** * @brief The constant indicates the database default journal size. @@ -415,7 +416,7 @@ public: /** * @brief Sets the module name for the object. */ - API_EXPORT void SetModuleName(const std::string& moduleName); + API_EXPORT void SetModuleName(const std::string &moduleName); /** * @brief Obtains the module name in this {@code StoreConfig} object. @@ -425,7 +426,7 @@ public: /** * @brief Sets the service name for the object. */ - API_EXPORT void SetServiceName(const std::string& serviceName); + API_EXPORT void SetServiceName(const std::string &serviceName); /** * @brief Sets the area for the object. @@ -612,7 +613,7 @@ public: this->securityLevel_ == config.securityLevel_ && this->journalSize_ == config.journalSize_ && this->pageSize_ == config.pageSize_ && this->dbType_ == config.dbType_ && this->customDir_ == config.customDir_ && this->pluginLibs_ == config.pluginLibs_ && - this->haMode_ == config.haMode_ && this->readOnly_ == config.readOnly_; + this->haMode_ == config.haMode_; } /** @@ -679,9 +680,9 @@ public: PromiseInfo GetPromiseInfo() const; void SetPromiseInfo(PromiseInfo promiseInfo); - + ssize_t GetCheckpointSize() const; - + ssize_t GetStartCheckpointSize() const; ssize_t GetWalLimitSize() const; @@ -689,7 +690,7 @@ public: void SetWalLimitSize(ssize_t size); int32_t GetHaMode() const; - + void SetHaMode(int32_t haMode); void SetScalarFunctions(const std::map functions); @@ -721,7 +722,7 @@ private: int32_t readConSize_ = 4; int32_t area_ = 0; int32_t writeTimeout_ = 2; // seconds - int32_t readTimeout_ = 1; // seconds + int32_t readTimeout_ = 1; // seconds int32_t dbType_ = DB_SQLITE; int32_t haMode_ = HAMode::SINGLE; SecurityLevel securityLevel_ = SecurityLevel::LAST; diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_types.h b/relational_store/interfaces/inner_api/rdb/include/rdb_types.h index c577b8ceb20a25340c465ee01371a0cb318a1b18..cfb74bcd458be8b128fd7fc9a5ca50a4b7ccbf6b 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_types.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_types.h @@ -19,10 +19,10 @@ #include #include #include +#include #include #include #include -#include namespace OHOS::DistributedRdb { enum RdbStatus { @@ -154,7 +154,7 @@ struct ProgressDetail { using Briefs = std::map; using Details = std::map; -using AsyncBrief = std::function; +using AsyncBrief = std::function; using AsyncDetail = std::function; using SyncResult = Briefs; @@ -198,13 +198,12 @@ struct RdbPredicateOperation { }; struct PredicatesMemo { - inline void AddOperation(const RdbPredicateOperator op, const std::string& field, - const std::string& value) + inline void AddOperation(const RdbPredicateOperator op, const std::string &field, const std::string &value) { operations_.push_back({ op, field, { value } }); } - inline void AddOperation(const RdbPredicateOperator op, const std::string& field, - const std::vector& values) + inline void AddOperation( + const RdbPredicateOperator op, const std::string &field, const std::vector &values) { operations_.push_back({ op, field, values }); } @@ -228,7 +227,7 @@ class DetailProgressObserver { public: virtual ~DetailProgressObserver() {}; - virtual void ProgressNotification(const Details& details) = 0; + virtual void ProgressNotification(const Details &details) = 0; }; enum SubscribeMode { @@ -288,8 +287,7 @@ public: virtual void OnChange() {}; }; -struct DropOption { -}; +struct DropOption {}; struct Field { static constexpr const char *CURSOR_FIELD = "#_cursor"; diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_visibility.h b/relational_store/interfaces/inner_api/rdb/include/rdb_visibility.h index 490ab6f7b57b840e874cdb151d4c8d080acffdd2..eb56306365305e4c7ef9a52293a28bc2c6374830 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_visibility.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_visibility.h @@ -17,7 +17,7 @@ #define NATIVE_RDB_RDB_VISIBILITY_H #ifndef API_EXPORT #if defined(__GNUC__) || defined(__clang__) -#define API_EXPORT __attribute__((visibility ("default"))) +#define API_EXPORT __attribute__((visibility("default"))) #else #define API_EXPORT #endif diff --git a/relational_store/interfaces/inner_api/rdb/include/remote_result_set.h b/relational_store/interfaces/inner_api/rdb/include/remote_result_set.h index ef84fdb1551431b8ed9313a9ffa69b434afd4602..da3268f0adde3021ce1826de0266cdbd50821add 100644 --- a/relational_store/interfaces/inner_api/rdb/include/remote_result_set.h +++ b/relational_store/interfaces/inner_api/rdb/include/remote_result_set.h @@ -18,6 +18,7 @@ #include #include + #include "rdb_visibility.h" namespace OHOS { diff --git a/relational_store/interfaces/inner_api/rdb/include/result_set.h b/relational_store/interfaces/inner_api/rdb/include/result_set.h index 2e3af70294d2cd4d8c03d05508b4ce8830b41cee..41b456002729da1949957f532c6a8f8113829aa9 100644 --- a/relational_store/interfaces/inner_api/rdb/include/result_set.h +++ b/relational_store/interfaces/inner_api/rdb/include/result_set.h @@ -16,12 +16,13 @@ #ifndef NATIVE_RDB_RESULT_SET_H #define NATIVE_RDB_RESULT_SET_H +#include #include #include -#include + +#include "rdb_errno.h" #include "remote_result_set.h" #include "value_object.h" -#include "rdb_errno.h" namespace OHOS { namespace NativeRdb { struct API_EXPORT RowEntity { diff --git a/relational_store/interfaces/inner_api/rdb/include/transaction.h b/relational_store/interfaces/inner_api/rdb/include/transaction.h index 409ab82854247563de1954966fef874c8b86dfd0..774dc645c7b80629b896ef355f07f0187924ee87 100644 --- a/relational_store/interfaces/inner_api/rdb/include/transaction.h +++ b/relational_store/interfaces/inner_api/rdb/include/transaction.h @@ -16,17 +16,17 @@ #ifndef NATIVE_RDB_TRANSACTION_H #define NATIVE_RDB_TRANSACTION_H +#include #include #include #include -#include #include "abs_rdb_predicates.h" -#include "result_set.h" #include "rdb_common.h" #include "rdb_errno.h" #include "rdb_types.h" #include "rdb_visibility.h" +#include "result_set.h" #include "values_bucket.h" #include "values_buckets.h" @@ -74,7 +74,7 @@ public: }; using Creator = std::function>( - int32_t type, std::shared_ptr connection, const std::string&)>; + int32_t type, std::shared_ptr connection, const std::string &)>; static std::pair> Create( int32_t type, std::shared_ptr connection, const std::string &name); @@ -93,8 +93,8 @@ public: * @param row Indicates the row of data {@link ValuesBucket} to be inserted into the table. * @param resolution Indicates the {@link ConflictResolution} to insert data into the table. */ - virtual std::pair Insert(const std::string &table, const Row &row, - Resolution resolution = NO_ACTION) = 0; + virtual std::pair Insert( + const std::string &table, const Row &row, Resolution resolution = NO_ACTION) = 0; /** * @brief Inserts a batch of data into the target table. @@ -122,7 +122,7 @@ public: * @param args Indicates the where arguments. */ virtual std::pair Update(const std::string &table, const Row &row, const std::string &where = "", - const Values &args = {}, Resolution resolution = NO_ACTION) = 0; + const Values &args = {}, Resolution resolution = NO_ACTION) = 0; /** * @brief Updates data in the database based on a a specified instance object of AbsRdbPredicates. @@ -131,8 +131,8 @@ public: * The key-value pairs are associated with column names of the database table. * @param predicates Indicates the specified update condition by the instance object of {@link AbsRdbPredicates}. */ - virtual std::pair Update(const Row &row, const AbsRdbPredicates &predicates, - Resolution resolution = NO_ACTION) = 0; + virtual std::pair Update( + const Row &row, const AbsRdbPredicates &predicates, Resolution resolution = NO_ACTION) = 0; /** * @brief Deletes data from the database based on specified conditions. @@ -141,8 +141,8 @@ public: * @param whereClause Indicates the where clause. * @param args Indicates the where arguments. */ - virtual std::pair Delete(const std::string &table, const std::string &whereClause = "", - const Values &args = {}) = 0; + virtual std::pair Delete( + const std::string &table, const std::string &whereClause = "", const Values &args = {}) = 0; /** * @brief Deletes data from the database based on a specified instance object of AbsRdbPredicates. @@ -179,5 +179,5 @@ public: private: static inline Creator creator_; }; -} +} // namespace OHOS::NativeRdb #endif diff --git a/relational_store/interfaces/inner_api/rdb/include/values_bucket.h b/relational_store/interfaces/inner_api/rdb/include/values_bucket.h index 5801327940339bcceedad841eca7f37441887bfa..f8250d763ee8edaa76bcc03f46ef0e793d4118ee 100644 --- a/relational_store/interfaces/inner_api/rdb/include/values_bucket.h +++ b/relational_store/interfaces/inner_api/rdb/include/values_bucket.h @@ -41,14 +41,14 @@ public: */ API_EXPORT ValuesBucket(std::map values); API_EXPORT ValuesBucket(const ValuesBucket &values); - API_EXPORT ValuesBucket &operator =(const ValuesBucket &values); + API_EXPORT ValuesBucket &operator=(const ValuesBucket &values); API_EXPORT ValuesBucket(ValuesBucket &&values) noexcept; - API_EXPORT ValuesBucket &operator =(ValuesBucket &&values) noexcept; + API_EXPORT ValuesBucket &operator=(ValuesBucket &&values) noexcept; /** * @brief Destructor. */ - API_EXPORT ~ValuesBucket(); + API_EXPORT ~ValuesBucket(); /** * @brief Put the string value to this {@code ValuesBucket} object for the given column name. diff --git a/relational_store/interfaces/inner_api/rdb/include/values_buckets.h b/relational_store/interfaces/inner_api/rdb/include/values_buckets.h index 5f99d6db7034c90f867c2ce973e6a5d6fafa54b4..e776b9fb6ebd2986524daa70e7128a394a8fbc9f 100644 --- a/relational_store/interfaces/inner_api/rdb/include/values_buckets.h +++ b/relational_store/interfaces/inner_api/rdb/include/values_buckets.h @@ -17,8 +17,8 @@ #define NATIVE_RDB_VALUES_BUCKETS_H #include -#include #include +#include #include "value_object.h" #include "values_bucket.h" 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 54f6b79c51cac3b0bdb38f69404c1db7901ca03f..fa1d035d053437b5f478d6d7207df7b1f977db59 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 @@ -16,10 +16,10 @@ #ifndef NATIVE_RDB_RDB_STORE_CONFIG_H #define NATIVE_RDB_RDB_STORE_CONFIG_H +#include +#include #include #include -#include -#include namespace OHOS::NativeRdb { enum class IntegrityCheck { @@ -105,7 +105,7 @@ enum EncryptAlgo : int32_t { }; -using ScalarFunction = std::function&)>; +using ScalarFunction = std::function &)>; struct ScalarFunctionInfo { ScalarFunctionInfo(ScalarFunction function, int argc) : function_(function), argc_(argc) {} @@ -133,7 +133,7 @@ public: ~CryptoParam(); bool IsValid() const; }; - static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ + static constexpr int DB_PAGE_SIZE = 4096; /* default page size : 4k */ static constexpr int DB_JOURNAL_SIZE = 1024 * 1024; /* default file size : 1M */ static constexpr char DB_DEFAULT_JOURNAL_MODE[] = "WAL"; static constexpr EncryptAlgo DB_DEFAULT_ENCRYPT_ALGO = AES_256_GCM; @@ -173,9 +173,9 @@ public: std::string GetBundleName() const; int SetDistributedType(DistributedType type); DistributedType GetDistributedType() const; - void SetModuleName(const std::string& moduleName); + void SetModuleName(const std::string &moduleName); std::string GetModuleName() const; - void SetServiceName(const std::string& serviceName); + void SetServiceName(const std::string &serviceName); void SetArea(int32_t area); int32_t GetArea() const; static std::string GetJournalModeValue(JournalMode journalMode); @@ -284,7 +284,7 @@ private: int32_t readConSize_ = 4; int32_t area_ = 0; int32_t writeTimeout_ = 2; // seconds - int32_t readTimeout_ = 1; // seconds + int32_t readTimeout_ = 1; // seconds int32_t dbType_ = DB_SQLITE; int32_t haMode_ = HAMode::SINGLE; SecurityLevel securityLevel_ = SecurityLevel::LAST; diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h b/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h index 41a89aa1c77a2561c9e77c107dd7c63d21b4a648..5aea40090ef2d7b0bfd1eac549a61e37dec05ddb 100644 --- a/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h +++ b/relational_store/interfaces/inner_api/rdb/mock/include/values_bucket.h @@ -37,9 +37,9 @@ public: */ ValuesBucket(std::map values); ValuesBucket(const ValuesBucket &values); - ValuesBucket &operator =(const ValuesBucket &values); + ValuesBucket &operator=(const ValuesBucket &values); ValuesBucket(ValuesBucket &&values) noexcept; - ValuesBucket &operator =(ValuesBucket &&values) noexcept; + ValuesBucket &operator=(ValuesBucket &&values) noexcept; /** * @brief Destructor. diff --git a/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/rdb_data_ability_utils.h b/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/rdb_data_ability_utils.h index 731101438414cc83be52cbd4026ebabb363ae8da..4703a9176e6c5430718fda6d1400146aa6bf9213 100644 --- a/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/rdb_data_ability_utils.h +++ b/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/rdb_data_ability_utils.h @@ -21,10 +21,10 @@ #include #include -#include "result_set.h" #include "data_ability_predicates.h" #include "datashare_predicates.h" #include "datashare_values_bucket.h" +#include "result_set.h" #include "values_bucket.h" namespace OHOS { @@ -83,8 +83,7 @@ public: /** * @brief Convert NDataShare::ResultSet to NativeRdb::AbsSharedResultSet. */ - API_EXPORT static std::shared_ptr ToAbsSharedResultSet( - std::shared_ptr resultSet); + API_EXPORT static std::shared_ptr ToAbsSharedResultSet(std::shared_ptr resultSet); private: RdbDataAbilityUtils(); @@ -93,4 +92,3 @@ private: } // namespace RdbDataAbilityAdapter } // namespace OHOS #endif // RDB_DATA_ABILITY_UTILS_H - diff --git a/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/result_set_utils.h b/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/result_set_utils.h index 7fce724d05ac729e4830e87b385fa7bf29b104c6..37b54326515e31a813597d48fe7a18d52c532e1a 100644 --- a/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/result_set_utils.h +++ b/relational_store/interfaces/inner_api/rdb_data_ability_adapter/include/result_set_utils.h @@ -17,12 +17,13 @@ #define OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_NATIVE_RDB_DATA_ABILITY_ADAPTER_SRC_RESULT_SET_UTILS_H #include -#include "basic/result_set.h" #include "abs_shared_result_set.h" +#include "basic/result_set.h" namespace OHOS::RdbDataAbilityAdapter { class ResultSetUtils : public NativeRdb::AbsSharedResultSet { using DSResultSet = DataShare::ResultSet; + public: ResultSetUtils(std::shared_ptr dbResultSet); int GetColumnCount(int &count) override; @@ -47,5 +48,5 @@ protected: private: std::shared_ptr resultSet_; }; -} +} // namespace OHOS::RdbDataAbilityAdapter #endif // OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_NATIVE_RDB_DATA_ABILITY_ADAPTER_SRC_RESULT_SET_UTILS_H diff --git a/relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h b/relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h index a5be3d76d6d2b93db775e0467a068f7d82f99e3b..5b09525e07035fe0dc1735e1a71694f3e81fb4a5 100644 --- a/relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h +++ b/relational_store/interfaces/inner_api/rdb_data_share_adapter/include/rdb_result_set_bridge.h @@ -16,8 +16,8 @@ #ifndef RDB_RESULT_SET_BRIDGE_H #define RDB_RESULT_SET_BRIDGE_H -#include "result_set.h" #include "rdb_errno.h" +#include "result_set.h" #include "result_set_bridge.h" #include "string.h" diff --git a/relational_store/interfaces/ndk/include/oh_cursor.h b/relational_store/interfaces/ndk/include/oh_cursor.h index c52211f000311021906a210cb00ab045305114df..7b6bb86de486de6e5b43892838091a6def91adb9 100644 --- a/relational_store/interfaces/ndk/include/oh_cursor.h +++ b/relational_store/interfaces/ndk/include/oh_cursor.h @@ -37,9 +37,11 @@ * @since 10 */ -#include -#include #include +#include + +#include + #include "data_asset.h" #ifdef __cplusplus extern "C" { diff --git a/relational_store/interfaces/ndk/include/oh_values_bucket.h b/relational_store/interfaces/ndk/include/oh_values_bucket.h index dba9feeef9c45c5223b8a3e2d3567009aadb2bda..932be9bc275886a2bd5390a39341fad6e9f701a9 100644 --- a/relational_store/interfaces/ndk/include/oh_values_bucket.h +++ b/relational_store/interfaces/ndk/include/oh_values_bucket.h @@ -38,6 +38,7 @@ */ #include + #include "data_asset.h" #ifdef __cplusplus extern "C" { diff --git a/relational_store/interfaces/ndk/include/relational_store.h b/relational_store/interfaces/ndk/include/relational_store.h index f1a6f5241af66ddbe297a919db2d77ac9aa417c2..da7f7f96736e26c2964b30c74ca3c4a803dfaa26 100644 --- a/relational_store/interfaces/ndk/include/relational_store.h +++ b/relational_store/interfaces/ndk/include/relational_store.h @@ -725,8 +725,8 @@ int OH_Rdb_SetDistributedTables(OH_Rdb_Store *store, const char *tables[], uint3 * @see OH_Cursor. * @since 11 */ -OH_Cursor *OH_Rdb_FindModifyTime(OH_Rdb_Store *store, const char *tableName, const char *columnName, - OH_VObject *values); +OH_Cursor *OH_Rdb_FindModifyTime( + OH_Rdb_Store *store, const char *tableName, const char *columnName, OH_VObject *values); /** * @brief Describes the change type. diff --git a/relational_store/interfaces/ndk/include/relational_store_error_code.h b/relational_store/interfaces/ndk/include/relational_store_error_code.h index 37ef03f44872dbf138cabb32db05c0ac6f0e8b6d..d1318ec3e59a0a2d01905bf7073070b032beb5c8 100644 --- a/relational_store/interfaces/ndk/include/relational_store_error_code.h +++ b/relational_store/interfaces/ndk/include/relational_store_error_code.h @@ -29,7 +29,6 @@ * @since 10 */ - /** * @file relational_store_error_code.h * @@ -306,7 +305,12 @@ typedef enum OH_Rdb_ErrCode { /** * @brief The error when the connection count is used up. */ - RDB_E_CON_OVER_LIMIT = (E_BASE + 48) + RDB_E_CON_OVER_LIMIT = (E_BASE + 48), + + /** + * @brief The key parameter is invalid. + */ + RDB_E_INVALID_SECRET_KEY = (E_BASE + 49) } OH_Rdb_ErrCode; #ifdef __cplusplus diff --git a/relational_store/interfaces/ndk/src/convertor_error_code.cpp b/relational_store/interfaces/ndk/src/convertor_error_code.cpp index ba45201c80469c8a45b4ceeec6a11751c17b385a..fed34adb35177f83eb531c22898a0ab303e8715e 100644 --- a/relational_store/interfaces/ndk/src/convertor_error_code.cpp +++ b/relational_store/interfaces/ndk/src/convertor_error_code.cpp @@ -14,9 +14,11 @@ */ #include "convertor_error_code.h" + #include -#include "relational_store_error_code.h" + #include "rdb_errno.h" +#include "relational_store_error_code.h" namespace OHOS::RdbNdk { @@ -67,7 +69,6 @@ static constexpr NdkErrorCode ERROR_CODE_MAP[] = { { OHOS::NativeRdb::E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY, RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY }, { OHOS::NativeRdb::E_STORE_SESSION_NO_CURRENT_TRANSACTION, RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION }, - { OHOS::NativeRdb::E_NOT_SUPPORT, RDB_E_NOT_SUPPORTED }, { OHOS::NativeRdb::E_INVALID_PARCEL, RDB_E_INVALID_PARCEL }, { OHOS::NativeRdb::E_QUERY_IN_EXECUTE, RDB_E_QUERY_IN_EXECUTE }, { OHOS::NativeRdb::E_SET_PERSIST_WAL, RDB_E_SET_PERSIST_WAL }, @@ -75,14 +76,14 @@ static constexpr NdkErrorCode ERROR_CODE_MAP[] = { { OHOS::NativeRdb::E_ARGS_READ_CON_OVERLOAD, RDB_E_ARGS_READ_CON_OVERLOAD }, { OHOS::NativeRdb::E_WAL_SIZE_OVER_LIMIT, RDB_E_WAL_SIZE_OVER_LIMIT }, { OHOS::NativeRdb::E_CON_OVER_LIMIT, RDB_E_CON_OVER_LIMIT }, + { OHOS::NativeRdb::E_INVALID_SECRET_KEY, RDB_E_INVALID_SECRET_KEY }, { OHOS::NativeRdb::E_NOT_SUPPORT, RDB_E_NOT_SUPPORTED }, }; int ConvertorErrorCode::NativeToNdk(int nativeErrCode) { auto errorCode = NdkErrorCode{ nativeErrCode, -1 }; - auto iter = std::lower_bound(ERROR_CODE_MAP, - ERROR_CODE_MAP + sizeof(ERROR_CODE_MAP) / sizeof(ERROR_CODE_MAP[0]), + auto iter = std::lower_bound(ERROR_CODE_MAP, ERROR_CODE_MAP + sizeof(ERROR_CODE_MAP) / sizeof(ERROR_CODE_MAP[0]), errorCode, [](const NdkErrorCode &errorCode1, const NdkErrorCode &errorCode2) { return errorCode1.nativeCode < errorCode2.nativeCode; }); @@ -92,4 +93,4 @@ int ConvertorErrorCode::NativeToNdk(int nativeErrCode) } return RDB_E_ERROR; } -} \ No newline at end of file +} // namespace OHOS::RdbNdk \ No newline at end of file diff --git a/relational_store/interfaces/ndk/src/modify_time_cursor.cpp b/relational_store/interfaces/ndk/src/modify_time_cursor.cpp index c1ef3563d7505773226d82a30da2e5bafbe34997..3e2dd460e6bbea075885bc77afa1867789c62cb5 100644 --- a/relational_store/interfaces/ndk/src/modify_time_cursor.cpp +++ b/relational_store/interfaces/ndk/src/modify_time_cursor.cpp @@ -14,6 +14,7 @@ */ #define LOG_TAG "ModifyTimeCursor" #include "modify_time_cursor.h" + #include "logger.h" #include "relational_store_error_code.h" #include "securec.h" diff --git a/relational_store/interfaces/ndk/src/modify_time_cursor.h b/relational_store/interfaces/ndk/src/modify_time_cursor.h index 1c52c7535ec6b2c9381d521327d09e328e993730..7722d7caa93f1adb488e428286a01b4d8addf546 100644 --- a/relational_store/interfaces/ndk/src/modify_time_cursor.h +++ b/relational_store/interfaces/ndk/src/modify_time_cursor.h @@ -15,8 +15,8 @@ #ifndef RELATIONAL_MODIFY_TIME_CURSOR_H #define RELATIONAL_MODIFY_TIME_CURSOR_H -#include "relational_cursor.h" #include "rdb_store.h" +#include "relational_cursor.h" #include "result_set.h" namespace OHOS::RdbNdk { class ModifyTimeCursor : public RelationalCursor { diff --git a/relational_store/interfaces/ndk/src/relational_asset.cpp b/relational_store/interfaces/ndk/src/relational_asset.cpp index 845ddbf6e8fba1efd92dc38a1047a614a539bd4c..89c18dca98405034bbd8431280a55c7214ea452c 100644 --- a/relational_store/interfaces/ndk/src/relational_asset.cpp +++ b/relational_store/interfaces/ndk/src/relational_asset.cpp @@ -15,10 +15,11 @@ #define LOG_TAG "RelationalAsset" #include "relational_asset.h" +#include + #include "logger.h" #include "relational_store_error_code.h" #include "securec.h" -#include using namespace OHOS::RdbNdk; constexpr int ASSET_TRANSFORM_BASE = 10; diff --git a/relational_store/interfaces/ndk/src/relational_cursor.cpp b/relational_store/interfaces/ndk/src/relational_cursor.cpp index b0e6baffbc285e47ee047e898f62045b0abf92d6..252b1600a5882954ac31c747e2a6d843783012f2 100644 --- a/relational_store/interfaces/ndk/src/relational_cursor.cpp +++ b/relational_store/interfaces/ndk/src/relational_cursor.cpp @@ -17,13 +17,13 @@ #include +#include "convertor_error_code.h" #include "logger.h" #include "oh_cursor.h" #include "rdb_errno.h" #include "relational_asset.h" #include "relational_store_error_code.h" #include "securec.h" -#include "convertor_error_code.h" namespace OHOS { namespace RdbNdk { @@ -153,7 +153,6 @@ int RelationalCursor::IsNull(OH_Cursor *cursor, int32_t columnIndex, bool *isNul return self->IsNull(columnIndex, isNull); } - int RelationalCursor::GetAssetsCount(OH_Cursor *cursor, int32_t columnIndex, uint32_t *count) { auto self = GetSelf(cursor); diff --git a/relational_store/interfaces/ndk/src/relational_cursor.h b/relational_store/interfaces/ndk/src/relational_cursor.h index 07a60f22c34f75bc99d6f81420397d8847732885..0d765e543b52d7923700b24a1bf9cac719fe4491 100644 --- a/relational_store/interfaces/ndk/src/relational_cursor.h +++ b/relational_store/interfaces/ndk/src/relational_cursor.h @@ -20,7 +20,6 @@ #include "oh_cursor.h" #include "result_set.h" -#include namespace OHOS { namespace RdbNdk { diff --git a/relational_store/interfaces/ndk/src/relational_predicates.cpp b/relational_store/interfaces/ndk/src/relational_predicates.cpp index 948fe7488b461980b0cd083bc9a21d0294b0d9e5..044c9a2cf330596f2585b9ab201237667ca8947d 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates.cpp +++ b/relational_store/interfaces/ndk/src/relational_predicates.cpp @@ -40,8 +40,7 @@ OH_Predicates *RelationalPredicate::EqualTo(OH_Predicates *predicates, const cha return self; } -OH_Predicates *RelationalPredicate::NotEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject) +OH_Predicates *RelationalPredicate::NotEqualTo(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); @@ -149,8 +148,7 @@ OH_Predicates *RelationalPredicate::Between(OH_Predicates *predicates, const cha return self; } -OH_Predicates *RelationalPredicate::NotBetween(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject) +OH_Predicates *RelationalPredicate::NotBetween(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); @@ -167,8 +165,7 @@ OH_Predicates *RelationalPredicate::NotBetween(OH_Predicates *predicates, const return self; } -OH_Predicates *RelationalPredicate::GreaterThan(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject) +OH_Predicates *RelationalPredicate::GreaterThan(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); @@ -182,8 +179,7 @@ OH_Predicates *RelationalPredicate::GreaterThan(OH_Predicates *predicates, const return self; } -OH_Predicates *RelationalPredicate::LessThan(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject) +OH_Predicates *RelationalPredicate::LessThan(OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); @@ -197,8 +193,8 @@ OH_Predicates *RelationalPredicate::LessThan(OH_Predicates *predicates, const ch return self; } -OH_Predicates *RelationalPredicate::GreaterThanOrEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject) +OH_Predicates *RelationalPredicate::GreaterThanOrEqualTo( + OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); @@ -211,8 +207,8 @@ OH_Predicates *RelationalPredicate::GreaterThanOrEqualTo(OH_Predicates *predicat } return self; } -OH_Predicates *RelationalPredicate::LessThanOrEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject) +OH_Predicates *RelationalPredicate::LessThanOrEqualTo( + OH_Predicates *predicates, const char *field, OH_VObject *valueObject) { auto self = GetSelf(predicates); auto selfObjects = RelationalPredicatesObjects::GetSelf(valueObject); @@ -371,7 +367,7 @@ OHOS::NativeRdb::RdbPredicates &RelationalPredicate::Get() return predicates_; } -RelationalPredicate* RelationalPredicate::GetSelf(OH_Predicates *predicates) +RelationalPredicate *RelationalPredicate::GetSelf(OH_Predicates *predicates) { if (predicates == nullptr || predicates->id != OHOS::RdbNdk::RDB_PREDICATES_CID) { LOG_ERROR("cursor invalid. is null %{public}d", (predicates == nullptr)); diff --git a/relational_store/interfaces/ndk/src/relational_predicates.h b/relational_store/interfaces/ndk/src/relational_predicates.h index d298207508fde8755e69895739c05d311f5250d8..6c6a1e67722cd50cefc7b6c0f51c005832baed9f 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates.h +++ b/relational_store/interfaces/ndk/src/relational_predicates.h @@ -16,8 +16,8 @@ #ifndef RELATIONAL_PREDICATES_IMPL_H #define RELATIONAL_PREDICATES_IMPL_H -#include "rdb_predicates.h" #include "oh_predicates.h" +#include "rdb_predicates.h" namespace OHOS { namespace RdbNdk { @@ -27,6 +27,7 @@ public: explicit RelationalPredicate(const char *table); static RelationalPredicate *GetSelf(OH_Predicates *predicates); OHOS::NativeRdb::RdbPredicates &Get(); + private: static OH_Predicates *EqualTo(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); static OH_Predicates *NotEqualTo(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); @@ -41,10 +42,8 @@ private: static OH_Predicates *NotBetween(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); static OH_Predicates *GreaterThan(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); static OH_Predicates *LessThan(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); - static OH_Predicates *GreaterThanOrEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject); - static OH_Predicates *LessThanOrEqualTo(OH_Predicates *predicates, const char *field, - OH_VObject *valueObject); + static OH_Predicates *GreaterThanOrEqualTo(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); + static OH_Predicates *LessThanOrEqualTo(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); static OH_Predicates *OrderBy(OH_Predicates *predicates, const char *field, OH_OrderType type); static OH_Predicates *Distinct(OH_Predicates *predicates); static OH_Predicates *Limit(OH_Predicates *predicates, unsigned int value); @@ -54,8 +53,7 @@ private: static OH_Predicates *NotIn(OH_Predicates *predicates, const char *field, OH_VObject *valueObject); static OH_Predicates *Clear(OH_Predicates *predicates); static int Destroy(OH_Predicates *predicates); - static bool GetObjects(OH_Predicates *predicates, OH_VObject *valueObject, - std::vector &values); + static bool GetObjects(OH_Predicates *predicates, OH_VObject *valueObject, std::vector &values); OHOS::NativeRdb::RdbPredicates predicates_; }; } // namespace RdbNdk diff --git a/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp b/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp index a1ef3a91cdb290e5d85fd845ad04fa310b1e8e35..378c363bd461230734a79f899fef7f24164061e3 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp +++ b/relational_store/interfaces/ndk/src/relational_predicates_objects.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ #define LOG_TAG "RelationalPredicatesObjects" +#include "relational_predicates_objects.h" + #include "logger.h" #include "oh_value_object.h" #include "relational_store_error_code.h" -#include "relational_predicates_objects.h" namespace OHOS { namespace RdbNdk { diff --git a/relational_store/interfaces/ndk/src/relational_predicates_objects.h b/relational_store/interfaces/ndk/src/relational_predicates_objects.h index 9d0c342e987befedd29ce102d82f3ab651a5824b..0cf0090d78a0bdacb56db4fad81abd60488dfb62 100644 --- a/relational_store/interfaces/ndk/src/relational_predicates_objects.h +++ b/relational_store/interfaces/ndk/src/relational_predicates_objects.h @@ -30,6 +30,7 @@ public: RelationalPredicatesObjects(); static RelationalPredicatesObjects *GetSelf(OH_VObject *objects); std::vector &Get(); + private: static int PutInt64(OH_VObject *objects, int64_t *value, uint32_t count); static int PutDouble(OH_VObject *objects, double *value, uint32_t count); diff --git a/relational_store/interfaces/ndk/src/relational_store.cpp b/relational_store/interfaces/ndk/src/relational_store.cpp index e500aa718ec432d38d5e854cbb6b727dba1d2635..f09882f0ce2dd9b753ff6b865418c07e24c3841c 100644 --- a/relational_store/interfaces/ndk/src/relational_store.cpp +++ b/relational_store/interfaces/ndk/src/relational_store.cpp @@ -42,7 +42,7 @@ constexpr int RDB_CONFIG_SIZE_V0 = 41; constexpr int RDB_CONFIG_SIZE_V1 = 45; constexpr int RDB_CONFIG_V2_MAGIC_CODE = 0xDBCF2ADE; -static int g_supportDbTypes[] = {RDB_SQLITE, RDB_CAYLEY}; +static int g_supportDbTypes[] = { RDB_SQLITE, RDB_CAYLEY }; struct OH_Rdb_ConfigV2 { int magicNum = RDB_CONFIG_V2_MAGIC_CODE; @@ -64,8 +64,8 @@ OH_Rdb_ConfigV2 *OH_Rdb_CreateConfig() int OH_Rdb_DestroyConfig(OH_Rdb_ConfigV2 *config) { if (config == nullptr || (config->magicNum != RDB_CONFIG_V2_MAGIC_CODE)) { - LOG_ERROR("config is null %{public}d or magic num not valid %{public}x when destroy.", - (config == nullptr), (config == nullptr ? 0 : config->magicNum)); + LOG_ERROR("config is null %{public}d or magic num not valid %{public}x when destroy.", (config == nullptr), + (config == nullptr ? 0 : config->magicNum)); return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; } delete config; @@ -77,8 +77,8 @@ int OH_Rdb_SetDatabaseDir(OH_Rdb_ConfigV2 *config, const char *dataBaseDir) { if (config == nullptr || dataBaseDir == nullptr || (config->magicNum != RDB_CONFIG_V2_MAGIC_CODE)) { LOG_ERROR("config is null %{public}d or dataBaseDir %{public}d magic num not valid %{public}x " - "when Set DataBaseDir.", (config == nullptr), (dataBaseDir == nullptr), - (config == nullptr ? 0 : config->magicNum)); + "when Set DataBaseDir.", + (config == nullptr), (dataBaseDir == nullptr), (config == nullptr ? 0 : config->magicNum)); return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; } config->dataBaseDir = std::string(dataBaseDir); @@ -89,8 +89,8 @@ int OH_Rdb_SetStoreName(OH_Rdb_ConfigV2 *config, const char *storeName) { if (config == nullptr || storeName == nullptr || (config->magicNum != RDB_CONFIG_V2_MAGIC_CODE)) { LOG_ERROR("config is null %{public}d or storeName %{public}d or magic num not ok" - "%{public}x When set storeName.", (config == nullptr), (storeName == nullptr), - (config == nullptr ? 0 : config->magicNum)); + "%{public}x When set storeName.", + (config == nullptr), (storeName == nullptr), (config == nullptr ? 0 : config->magicNum)); return OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; } config->storeName = std::string(storeName); @@ -314,13 +314,13 @@ static OHOS::NativeRdb::RdbStoreConfig GetRdbStoreConfig(const OH_Rdb_ConfigV2 * { if (config->magicNum != RDB_CONFIG_V2_MAGIC_CODE || (OHOS::NativeRdb::SecurityLevel(config->securityLevel) < OHOS::NativeRdb::SecurityLevel::S1 || - OHOS::NativeRdb::SecurityLevel(config->securityLevel) >= OHOS::NativeRdb::SecurityLevel::LAST) || + OHOS::NativeRdb::SecurityLevel(config->securityLevel) >= OHOS::NativeRdb::SecurityLevel::LAST) || (config->area < RDB_SECURITY_AREA_EL1 || config->area > RDB_SECURITY_AREA_EL5) || (config->dbType < RDB_SQLITE || config->dbType > RDB_CAYLEY)) { *errCode = OH_Rdb_ErrCode::RDB_E_INVALID_ARGS; LOG_ERROR("Config magic number is not valid %{public}x or securityLevel %{public}d area %{public}d" - "dbType %{public}d ret %{public}d", config->magicNum, config->securityLevel, config->area, config->dbType, - *errCode); + "dbType %{public}d ret %{public}d", + config->magicNum, config->securityLevel, config->area, config->dbType, *errCode); return OHOS::NativeRdb::RdbStoreConfig(""); } std::string realPath = @@ -345,7 +345,7 @@ OH_Rdb_Store *OH_Rdb_GetOrOpen(const OH_Rdb_Config *config, int *errCode) if (config == nullptr || config->selfSize > RDB_CONFIG_SIZE_V1 || errCode == nullptr) { LOG_ERROR("Parameters set error:config is NULL ? %{public}d and config size is %{public}zu or " "errCode is NULL ? %{public}d ", - (config == nullptr), sizeof(OH_Rdb_Config), (errCode == nullptr)); + (config == nullptr), sizeof(OH_Rdb_Config), (errCode == nullptr)); return nullptr; } @@ -382,8 +382,8 @@ OH_Rdb_Store *OH_Rdb_CreateOrOpen(const OH_Rdb_ConfigV2 *config, int *errCode) { if (config == nullptr || (config->magicNum != RDB_CONFIG_V2_MAGIC_CODE) || errCode == nullptr) { LOG_ERROR("Parameters set error:config is NULL ? %{public}d or magicNum is not valid %{public}d or" - " errCode is NULL ? %{public}d ", (config == nullptr), (config == nullptr ? 0 : config->magicNum), - (errCode == nullptr)); + " errCode is NULL ? %{public}d ", + (config == nullptr), (config == nullptr ? 0 : config->magicNum), (errCode == nullptr)); return nullptr; } OHOS::NativeRdb::RdbStoreConfig rdbStoreConfig = GetRdbStoreConfig(config, errCode); @@ -719,17 +719,16 @@ int RelationalStore::DoSubScribe(Rdb_SubscribeType type, const Rdb_DataObserver std::lock_guard lock(mutex_); auto result = std::any_of(dataObservers_[type].begin(), dataObservers_[type].end(), - [observer](const std::shared_ptr &item) { - return *item.get() == observer; - }); + [observer](const std::shared_ptr &item) { return *item.get() == observer; }); if (result) { LOG_INFO("duplicate subscribe."); return OH_Rdb_ErrCode::RDB_OK; } auto subscribeOption = SubscribeOption{ .mode = NDKUtils::GetSubscribeType(type), .event = "data_change" }; auto ndkObserver = std::make_shared(observer, type); - int subscribeResult = (type == RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS) ? - store_->SubscribeObserver(subscribeOption, ndkObserver) : store_->Subscribe(subscribeOption, ndkObserver.get()); + int subscribeResult = (type == RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS) + ? store_->SubscribeObserver(subscribeOption, ndkObserver) + : store_->Subscribe(subscribeOption, ndkObserver.get()); if (subscribeResult != OHOS::NativeRdb::E_OK) { LOG_ERROR("subscribe failed."); } else { @@ -750,8 +749,8 @@ int RelationalStore::DoUnsubScribe(Rdb_SubscribeType type, const Rdb_DataObserve continue; } auto subscribeOption = SubscribeOption{ .mode = NDKUtils::GetSubscribeType(type), .event = "data_change" }; - int errCode = (type == RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS) ? - store_->UnsubscribeObserver(subscribeOption, *it) : store_->UnSubscribe(subscribeOption, it->get()); + int errCode = (type == RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS) ? store_->UnsubscribeObserver(subscribeOption, *it) + : store_->UnSubscribe(subscribeOption, it->get()); if (errCode != NativeRdb::E_OK) { LOG_ERROR("unsubscribe failed."); return ConvertorErrorCode::NativeToNdk(errCode); diff --git a/relational_store/interfaces/ndk/src/relational_store_impl.h b/relational_store/interfaces/ndk/src/relational_store_impl.h index 46e106d951d298f5ad283c80548ff4de8571b723..5f4ddd0695127e285ae1f503ab504108435fd43c 100644 --- a/relational_store/interfaces/ndk/src/relational_store_impl.h +++ b/relational_store/interfaces/ndk/src/relational_store_impl.h @@ -45,15 +45,15 @@ public: void OnChange(const std::vector &devices) override; - void OnChange(const OHOS::DistributedRdb::Origin &origin, const PrimaryFields &fields, - ChangeInfo &&changeInfo) override; + void OnChange( + const OHOS::DistributedRdb::Origin &origin, const PrimaryFields &fields, ChangeInfo &&changeInfo) override; void OnChange() override; bool operator==(const Rdb_DataObserver *other); private: - void ConvertKeyInfoData(Rdb_KeyInfo::Rdb_KeyData *keyInfoData, - std::vector &primaryKey); + void ConvertKeyInfoData( + Rdb_KeyInfo::Rdb_KeyData *keyInfoData, std::vector &primaryKey); size_t GetKeyInfoSize(RdbStoreObserver::ChangeInfo &&changeInfo); int32_t GetKeyDataType(std::vector &primaryKey); int mode_ = Rdb_SubscribeType::RDB_SUBSCRIBE_TYPE_CLOUD; diff --git a/relational_store/rdbmock/frameworks/native/rdb/ashmem.h b/relational_store/rdbmock/frameworks/native/rdb/ashmem.h index d8f9a68a798e0a4251a8960b27f2e5274504492c..6e89da2e2c7bb115a9f96dfba6beb05201bb3e7c 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/ashmem.h +++ b/relational_store/rdbmock/frameworks/native/rdb/ashmem.h @@ -20,9 +20,12 @@ namespace OHOS { namespace AppDataFwk { class Ashmem { public: - int GetAshmemFd() { return 0; }; + int GetAshmemFd() + { + return 0; + }; }; -} -} +} // namespace AppDataFwk +} // namespace OHOS #endif //RELATIONAL_STORE_MESSAGE_PARCEL_H diff --git a/relational_store/rdbmock/frameworks/native/rdb/concurrent_map.h b/relational_store/rdbmock/frameworks/native/rdb/concurrent_map.h index 82aa6b05d81cba7876a3536479eb4fef1dd76252..481c886b0868407aae7aebddce4acb149606a99b 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/concurrent_map.h +++ b/relational_store/rdbmock/frameworks/native/rdb/concurrent_map.h @@ -80,8 +80,8 @@ public: } template - typename std::enable_if()), filter_type>, bool>::type - Emplace(_Args &&...__args) noexcept + typename std::enable_if()), filter_type>, bool>::type Emplace( + _Args &&...__args) noexcept { std::lock_guard lock(mutex_); auto it = entries_.emplace(std::forward<_Args>(__args)...); @@ -89,8 +89,8 @@ public: } template - typename std::enable_if, bool>::type - Emplace(const _Filter &filter, _Args &&...__args) noexcept + typename std::enable_if, bool>::type Emplace( + const _Filter &filter, _Args &&...__args) noexcept { std::lock_guard lock(mutex_); if (!filter(entries_)) { @@ -105,10 +105,10 @@ public: std::lock_guard lock(mutex_); auto it = entries_.find(key); if (it == entries_.end()) { - return std::pair { false, mapped_type() }; + return std::pair{ false, mapped_type() }; } - return std::pair { true, it->second }; + return std::pair{ true, it->second }; } bool Contains(const key_type &key) const noexcept @@ -117,7 +117,7 @@ public: return (entries_.find(key) != entries_.end()); } - template + template bool InsertOrAssign(const key_type &key, _Obj &&obj) noexcept { std::lock_guard lock(mutex_); @@ -128,7 +128,7 @@ public: bool Insert(const key_type &key, const mapped_type &value) noexcept { std::lock_guard lock(mutex_); - auto it = entries_.insert(value_type { key, value }); + auto it = entries_.insert(value_type{ key, value }); return it.second; } @@ -165,8 +165,8 @@ public: } std::lock_guard lock(mutex_); #if __cplusplus > 201703L - auto count = std::erase_if(entries_, - [&action](value_type &value) -> bool { return action(value.first, value.second); }); + auto count = std::erase_if( + entries_, [&action](value_type &value) -> bool { return action(value.first, value.second); }); #else auto count = entries_.size(); for (auto it = entries_.begin(); it != entries_.end();) { diff --git a/relational_store/rdbmock/frameworks/native/rdb/file_ex.h b/relational_store/rdbmock/frameworks/native/rdb/file_ex.h index 36dee10bed1bdbf78661fbf2c5d25a5b26c05974..197fbf31b4b6fb59923f2e6c7aafa320cafa15bd 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/file_ex.h +++ b/relational_store/rdbmock/frameworks/native/rdb/file_ex.h @@ -19,12 +19,12 @@ #include #include -static bool SaveBufferToFile(const std::string& filePath, const std::vector& content, bool truncated = true) +static bool SaveBufferToFile(const std::string &filePath, const std::vector &content, bool truncated = true) { return true; } -static bool LoadBufferFromFile(const std::string& filePath, std::vector& content) +static bool LoadBufferFromFile(const std::string &filePath, std::vector &content) { return true; } @@ -43,5 +43,4 @@ extern "C" { #ifdef __cplusplus } #endif -#endif /* MOCK_UTILS_BASE_FILE_EX_H */ - +#endif /* MOCK_UTILS_BASE_FILE_EX_H */ diff --git a/relational_store/rdbmock/frameworks/native/rdb/hks_api.h b/relational_store/rdbmock/frameworks/native/rdb/hks_api.h index ebaefaa32c153eb47ea9a4a4c76860532360f5e6..9437f90f100bdd143e7afd16ac5b4450084ce913 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/hks_api.h +++ b/relational_store/rdbmock/frameworks/native/rdb/hks_api.h @@ -30,8 +30,8 @@ extern "C" { * @param token token * @return error code, see hks_type.h */ -static int32_t HksInit(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, - struct HksBlob *handle, struct HksBlob *token) +static int32_t HksInit( + const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, struct HksBlob *handle, struct HksBlob *token) { return HKS_SUCCESS; } @@ -71,8 +71,8 @@ static int32_t HksFinish(const struct HksBlob *handle, const struct HksParamSet * @param paramSetOut output parameter set * @return error code, see hks_type.h */ -static int32_t HksGenerateKey(const struct HksBlob *keyAlias, - const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut) +static int32_t HksGenerateKey( + const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut) { return HKS_SUCCESS; } diff --git a/relational_store/rdbmock/frameworks/native/rdb/hks_param.h b/relational_store/rdbmock/frameworks/native/rdb/hks_param.h index ed3034bdd36f24a67371c0f8f10fe0cc06f8b61e..84d3cb3a3e289aeadb973e21cd5fe9eddcbbb78a 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/hks_param.h +++ b/relational_store/rdbmock/frameworks/native/rdb/hks_param.h @@ -18,7 +18,6 @@ #include "hks_type.h" - #ifdef __cplusplus extern "C" { #endif @@ -41,8 +40,7 @@ static int32_t HksInitParamSet(struct HksParamSet **paramSet) * @param paramCnt numbers of params * @return error code, see hks_type.h */ -static int32_t HksAddParams(struct HksParamSet *paramSet, - const struct HksParam *params, uint32_t paramCnt) +static int32_t HksAddParams(struct HksParamSet *paramSet, const struct HksParam *params, uint32_t paramCnt) { return HKS_SUCCESS; } @@ -64,7 +62,7 @@ static int32_t HksBuildParamSet(struct HksParamSet **paramSet) */ static void HksFreeParamSet(struct HksParamSet **paramSet) { - return ; + return; } #ifdef __cplusplus diff --git a/relational_store/rdbmock/frameworks/native/rdb/hks_type.h b/relational_store/rdbmock/frameworks/native/rdb/hks_type.h index d0bf938314758e98d205ee2a1d36854728b9d11c..d08e3677f80c45fee8800a1ef57c34f5af70313e 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/hks_type.h +++ b/relational_store/rdbmock/frameworks/native/rdb/hks_type.h @@ -95,7 +95,6 @@ enum HksTag { struct HksParamSet; - #ifdef __cplusplus } #endif diff --git a/relational_store/rdbmock/frameworks/native/rdb/lru_bucket.h b/relational_store/rdbmock/frameworks/native/rdb/lru_bucket.h index fb89981355bc5943cf7b96f28cb3af0578f79c74..44d95dd4a15a82099ac1ebb19f142f484750443e 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/lru_bucket.h +++ b/relational_store/rdbmock/frameworks/native/rdb/lru_bucket.h @@ -16,16 +16,17 @@ #ifndef OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_LRU_BUCKET_H #define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_LRU_BUCKET_H +#include #include #include -#include namespace OHOS { template class LRUBucket { public: - LRUBucket(size_t capacity) - : size_(0), capacity_(capacity) {} + LRUBucket(size_t capacity) : size_(0), capacity_(capacity) + { + } LRUBucket(LRUBucket &&bucket) noexcept = delete; LRUBucket(const LRUBucket &bucket) = delete; @@ -102,7 +103,7 @@ public: PopBack(); } - auto *node = new(std::nothrow) Node(value); + auto *node = new (std::nothrow) Node(value); if (node == nullptr) { return false; } diff --git a/relational_store/rdbmock/frameworks/native/rdb/message_parcel.h b/relational_store/rdbmock/frameworks/native/rdb/message_parcel.h index 4b20e33e356f8b3e9bf1722c1d5aff438037860e..509cad8ef169e2e4797cf60d91842447a9550b3c 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/message_parcel.h +++ b/relational_store/rdbmock/frameworks/native/rdb/message_parcel.h @@ -18,9 +18,8 @@ namespace OHOS { namespace AppDataFwk { -class MessageParcel { -}; -} -} +class MessageParcel {}; +} // namespace AppDataFwk +} // namespace OHOS #endif //RELATIONAL_STORE_MESSAGE_PARCEL_H diff --git a/relational_store/rdbmock/frameworks/native/rdb/mock.cpp b/relational_store/rdbmock/frameworks/native/rdb/mock.cpp index 30797ddc3d1b54bab219fdb8a8bf793b545e8e3c..46e6b63a4f88ff2990509cb9984c9faf5b66e2b8 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/mock.cpp +++ b/relational_store/rdbmock/frameworks/native/rdb/mock.cpp @@ -14,6 +14,7 @@ */ #include "mock.h" + #include "relational_store_client.h" namespace OHOS { diff --git a/relational_store/rdbmock/frameworks/native/rdb/parcel.h b/relational_store/rdbmock/frameworks/native/rdb/parcel.h index 949304b9bd4c985e97fed334a43e66f725af693f..d1d727fd3fe1519fda47e5d828f6a1b2eefda785 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/parcel.h +++ b/relational_store/rdbmock/frameworks/native/rdb/parcel.h @@ -16,7 +16,6 @@ #ifndef RELATIONAL_STORE_PARCEL_H #define RELATIONAL_STORE_PARCEL_H -class MessageParcel { -}; +class MessageParcel {}; #endif //RELATIONAL_STORE_PARCEL_H diff --git a/relational_store/rdbmock/frameworks/native/rdb/relational_store_client.h b/relational_store/rdbmock/frameworks/native/rdb/relational_store_client.h index 161abcb43143140b6cac73212e9e3478474e969c..7a083da35846273fa2dd4794fa2c8e5bdada7a3b 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/relational_store_client.h +++ b/relational_store/rdbmock/frameworks/native/rdb/relational_store_client.h @@ -32,15 +32,15 @@ class RelationalStoreManager { public: static std::string GetDistributedLogTableName(const std::string &tableName); }; -} +} // namespace DistributedDB DistributedDB::DBStatus UnRegisterClientObserver(sqlite3 *db); -DistributedDB::DBStatus RegisterStoreObserver(sqlite3 *db, - const std::shared_ptr &storeObserver); +DistributedDB::DBStatus RegisterStoreObserver( + sqlite3 *db, const std::shared_ptr &storeObserver); -DistributedDB::DBStatus UnregisterStoreObserver(sqlite3 *db, - const std::shared_ptr &storeObserver); +DistributedDB::DBStatus UnregisterStoreObserver( + sqlite3 *db, const std::shared_ptr &storeObserver); DistributedDB::DBStatus UnregisterStoreObserver(sqlite3 *db); @@ -49,7 +49,6 @@ DistributedDB::DBStatus Lock( DistributedDB::DBStatus UnLock( const std::string &tableName, const std::vector> &hashKey, sqlite3 *db); -DistributedDB::DBStatus DropLogicDeletedData(sqlite3* db, - const std::string& tableName, uint64_t cursor); +DistributedDB::DBStatus DropLogicDeletedData(sqlite3 *db, const std::string &tableName, uint64_t cursor); #endif //RELATIONAL_STORE_RELATIONAL_STORE_CLIENT_H diff --git a/relational_store/rdbmock/frameworks/native/rdb/store_observer.h b/relational_store/rdbmock/frameworks/native/rdb/store_observer.h index a71465d80fcbc2fb45d6cdaf0322020c73d37345..e869046ce80a5ec707a623e17eaba9dbdb85a363 100644 --- a/relational_store/rdbmock/frameworks/native/rdb/store_observer.h +++ b/relational_store/rdbmock/frameworks/native/rdb/store_observer.h @@ -40,6 +40,6 @@ public: using StoreChangedInfo = std::vector; virtual void OnChange(StoreChangedInfo &&data) {}; }; -} +} // namespace DistributedDB #endif //RELATIONAL_STORE_OBSERVER_H \ No newline at end of file diff --git a/relational_store/test/js/clouddata/unittest/src/CloudClientTest.js b/relational_store/test/js/clouddata/unittest/src/CloudClientTest.js index a5f0dcbcfae8e07da0a1acf1329bc3b09e4658f2..01698a0fb716f6467f2b7705c9e0417747957f92 100644 --- a/relational_store/test/js/clouddata/unittest/src/CloudClientTest.js +++ b/relational_store/test/js/clouddata/unittest/src/CloudClientTest.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import cloudData from '@ohos.data.cloudData'; const TAG = "[CLOUD_CLIENT_JSKITS_TEST]" diff --git a/relational_store/test/js/clouddata/unittest/src/CloudShareTest.js b/relational_store/test/js/clouddata/unittest/src/CloudShareTest.js index 806ba3fa01848328160c518609c5ef618f199f9a..9f4aaf16acb275155880db17d69766554f666fe7 100644 --- a/relational_store/test/js/clouddata/unittest/src/CloudShareTest.js +++ b/relational_store/test/js/clouddata/unittest/src/CloudShareTest.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import cloudData from '@ohos.data.cloudData' import data_relationalStore from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; diff --git a/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigCallback.js b/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigCallback.js index 5a8f754b7bf80f2016359a48fd6d4d11a8948d17..285797598eef677a28520babfcb39c7429125c79 100644 --- a/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigCallback.js +++ b/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigCallback.js @@ -14,7 +14,7 @@ */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import cloudData from '@ohos.data.cloudData'; describe('CloudConfigCallbackTest', function () { @@ -252,7 +252,7 @@ describe('CloudConfigCallbackTest', function () { it('NotifyDataChangeInvalidArgsCallbackTest', 0, function (done) { console.info('NotifyDataChangeInvalidArgsCallbackTest'); try { - cloudData.Config.notifyDataChange(null, function(err) { + cloudData.Config.notifyDataChange(null, function (err) { if (err == undefined) { expect(null).assertFail(); console.info('NotifyDataChangeInvalidArgsCallbackTest notifyDataChange success'); @@ -336,7 +336,7 @@ describe('CloudConfigCallbackTest', function () { try { let account = "test_id"; let bundleName1 = "test_bundleName1"; - let appActions = {[bundleName1]: 3}; + let appActions = { [bundleName1]: 3 }; cloudData.Config.clear(account, appActions, function (err) { if (err == undefined) { expect(null).assertFail(); diff --git a/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigPromise.js b/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigPromise.js index 63cbf17bd362cd38bdf0b6286d8c9cf417134f1c..2eaace3aa001d695fd7fa700f3cd53ffb59fd258 100644 --- a/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigPromise.js +++ b/relational_store/test/js/clouddata/unittest/src/CloudSyncConfigPromise.js @@ -14,7 +14,7 @@ */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import cloudData from '@ohos.data.cloudData'; const TAG = "[CLOUD_CONFIG_JSKITS_TEST]" @@ -294,7 +294,7 @@ describe('CloudConfigPromiseTest', function () { try { let account = "test_id"; let bundleName1 = "test_bundleName1"; - let appActions = {[bundleName1]: 3}; + let appActions = { [bundleName1]: 3 }; await cloudData.Config.clear(account, appActions).then(() => { console.info('ClearInvalidArgsTest success'); expect(null).assertFail(); 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 03ab110ce728e20863dc947aac54b9e02c5a6377..171a26c67986d3101f5fad90fdc5cbf1dc2dd630 100644 --- a/relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js +++ b/relational_store/test/js/dataability/unittest/src/DataAbilityPredicatesJsunit.test.js @@ -12,19 +12,19 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; import dataAbility from '@ohos.data.dataAbility'; const TAG = "[RDB_JSKITS _TEST]" const CREATE_TABLE_ALL_DATA_TYPE_SQL = "CREATE TABLE IF NOT EXISTS AllDataType " -+ "(id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "integerValue INTEGER , longValue INTEGER , shortValue INTEGER , booleanValue INTEGER , " -+ "doubleValue REAL , floatValue REAL , stringValue TEXT , blobValue BLOB , clobValue TEXT , " -+ "byteValue INTEGER , dateValue INTEGER , timeValue INTEGER , timestampValue INTEGER , " -+ "calendarValue INTEGER , characterValue TEXT , primIntValue INTEGER , primLongValue INTEGER , " -+ "primShortValue INTEGER , primFloatValue REAL , primDoubleValue REAL , " -+ "primBooleanValue INTEGER , primByteValue INTEGER , primCharValue TEXT, `order` INTEGER);"; + + "(id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "integerValue INTEGER , longValue INTEGER , shortValue INTEGER , booleanValue INTEGER , " + + "doubleValue REAL , floatValue REAL , stringValue TEXT , blobValue BLOB , clobValue TEXT , " + + "byteValue INTEGER , dateValue INTEGER , timeValue INTEGER , timestampValue INTEGER , " + + "calendarValue INTEGER , characterValue TEXT , primIntValue INTEGER , primLongValue INTEGER , " + + "primShortValue INTEGER , primFloatValue REAL , primDoubleValue REAL , " + + "primBooleanValue INTEGER , primByteValue INTEGER , primCharValue TEXT, `order` INTEGER);"; const STORE_CONFIG = { name: "Predicates.db", diff --git a/relational_store/test/js/rdb/performance/src/PredicatestPerf.js b/relational_store/test/js/rdb/performance/src/PredicatestPerf.js index 7bcf8e5a95c36dcbfe4ee72b5ef5162937627809..44073376c84676c6054044ff7a5755c7bc479907 100644 --- a/relational_store/test/js/rdb/performance/src/PredicatestPerf.js +++ b/relational_store/test/js/rdb/performance/src/PredicatestPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.rdb'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js b/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js index 619003ac419210415e97d674206f880213d5e751..bd6df999140af6cdb4b12267a586dd081162d693 100644 --- a/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.rdb'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js index 243bb63dcd6709f18c2314c121fc199f2acac95d..3abb4550962acbc92022897cdaa74150a3f7c3c9 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.rdb'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js index 87d11c05961fdd97990af9868def8af11e8f21d8..cfc39cfa990cc345b142cc3c3bbc3e36d8de92ed 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.rdb'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js b/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js index f7ea8a3b858c8fd32c8b3e2d846ffd4bc19de74a..a06d140feb664da9f3d4dac305912ae347072d9f 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.rdb'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js index 5d0bc10154da9ecbdf410d084c9a137f68767091..9d31c1d6031a46f9a131b21e105b8737a338f0ac 100644 --- a/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js +++ b/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.rdb'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/rdb/performance/src/ResultSetPerf.js b/relational_store/test/js/rdb/performance/src/ResultSetPerf.js index 384a20132b8196e727b90d9b9360531c8f57866a..07e087c61728ae9b94f8621b63f77dbe7ca84f3c 100644 --- a/relational_store/test/js/rdb/performance/src/ResultSetPerf.js +++ b/relational_store/test/js/rdb/performance/src/ResultSetPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.rdb'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js index 8c8ed31f308fce8b70f3d12f72aedb90149c2a2c..0d489f94bb621b041d227fa60859354b5a73e7b0 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbStoreDataShareJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_rdb from '@ohos.data.rdb' import ability_featureAbility from '@ohos.ability.featureAbility' import data_dataSharePredicates from '@ohos.data.dataSharePredicates' 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 ba726dd042efd219039e3f4cc748ae791b3d64f2..bf46e3edd2675b3e9cb37c0eb53afd911abef13e 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbStoreDistributedJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS_TEST_Distributed]" @@ -295,7 +295,7 @@ describe('rdbStoreDistributedTest', function () { predicates = predicates.inDevices(["12345678abcd"]); try { rdbStore.sync(dataRdb.SyncMode.SYNC_MODE_PUSH, predicates); - console.log(TAG + "sync push success"); + console.log(TAG + "sync push success"); } catch (err) { console.log(TAG + "sync push" + err); expect().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 3af946c29cb8d68f0e170e08a50e30b5423ee465..5fe880029cf3dd507138ba6598fdc274cd21a8cd 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbStoreResultSetJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb' const TAG = "[RDB_JSKITS_TEST]" @@ -2269,7 +2269,7 @@ describe('rdbResultSetTest', function () { resultSet = null; done(); console.log(TAG + "************* testBigData0014 end *************"); - + }) console.log(TAG + "*************Unit Test End*************"); }) \ No newline at end of file diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js index 5b8910de0e0a789bfc1a6997e6fcb8834b876a51..3e2f4ec3e1565b3ed84101204cb249ebe006d870 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; import featureAbility from '@ohos.ability.featureAbility'; 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 ca83347023d6ba175bb20cd68062779f10b4b57d..ec3de69e2960b0433989b8560026e24b28686ca8 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreDeleteJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS_TEST]" diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js index 247ebcdd38ec06b603257ab172e2d4ed4da10107..b054febfc56bc4abc81c1995e55d1661c609880f 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreEncryptionJsunit.test.js @@ -12,14 +12,14 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_rdb from '@ohos.data.rdb' import ability_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)" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)" let context = null; const STORE_CONFIG_ENCRYPT = { @@ -172,11 +172,11 @@ describe('rdbEncryptTest', function () { context = ability_featureAbility.getContext(); await CreateRdbStore(context, STORE_CONFIG_ENCRYPT); try { - let rdbStore = await CreateRdbStore(context, STORE_CONFIG_WRONG); - expect(rdbStore !== null).assertTrue(); + let rdbStore = await CreateRdbStore(context, STORE_CONFIG_WRONG); + expect(rdbStore !== null).assertTrue(); } catch (err) { - console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); - expect().assertFail(); + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); } done(); console.log(TAG + "************* RdbEncryptTest_0040 end *************"); @@ -195,11 +195,11 @@ describe('rdbEncryptTest', function () { context = ability_featureAbility.getContext(); await CreateRdbStore(context, STORE_CONFIG_WRONG); try { - let rdbStore = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT); - expect(rdbStore !== null).assertTrue(); + let rdbStore = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT); + expect(rdbStore !== null).assertTrue(); } catch (err) { - console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); - expect().assertFail(); + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); } done(); console.log(TAG + "************* RdbEncryptTest_0041 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 1a26e3c1cccb453222bed9ddcbb5e9b62a3d3f83..0920b3a0a0180dfd63c7107aad68cdd847460ef9 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreInsertJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS_TEST]" @@ -24,7 +24,7 @@ const STORE_CONFIG = { name: "InsertTest.db", } -var rdbStore = undefined; +let rdbStore = undefined; describe('rdbStoreInsertTest', function () { beforeAll(async function () { @@ -57,7 +57,7 @@ describe('rdbStoreInsertTest', function () { */ it('testRdbStoreInsert0001', 0, async function (done) { console.log(TAG + "************* testRdbStoreInsert0001 start *************"); - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) { const valueBucket = { "name": "zhangsan", @@ -122,7 +122,7 @@ describe('rdbStoreInsertTest', function () { */ it('testRdbStoreInsert0002', 0, async function (done) { console.log(TAG + "************* testRdbStoreInsert0002 start *************"); - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) { const valueBucket = { "name": "zhangsan", @@ -150,7 +150,7 @@ describe('rdbStoreInsertTest', function () { */ it('testRdbStoreInsert0003', 0, async function (done) { console.log(TAG + "************* testRdbStoreInsert0003 start *************"); - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) { const valueBucket = { "name": "zhangsan", @@ -159,7 +159,7 @@ describe('rdbStoreInsertTest', function () { "blobType": u8, } try { - let insertPromise = rdbStore.insert(null, valueBucket) + let insertPromise = rdbStore.insert(null, valueBucket) insertPromise.then(async (ret) => { expect(1).assertEqual(ret) console.log(TAG + "insert first done: " + ret) @@ -168,7 +168,7 @@ describe('rdbStoreInsertTest', function () { console.log(TAG + "insert with null table") expect(null).assertFail() }) - } catch(err) { + } catch (err) { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() @@ -185,8 +185,8 @@ describe('rdbStoreInsertTest', function () { */ it('testRdbStoreInsert0004', 0, async function (done) { console.log(TAG + "************* testRdbStoreInsert0004 start *************"); - var u8 = new Uint8Array([1, 2, 3]) - var nameStr = "abcd" + "e".repeat(2000) + "./&*$!@()" + let u8 = new Uint8Array([1, 2, 3]) + let nameStr = "abcd" + "e".repeat(2000) + "./&*$!@()" const valueBucket = { "name": nameStr, "age": 19, @@ -219,8 +219,8 @@ describe('rdbStoreInsertTest', function () { */ it('testRdbStoreInsert0005', 0, async function (done) { console.log(TAG + "************* testRdbStoreInsert0005 start *************"); - var u8 = new Uint8Array([1, 2, 3]) - var nameStr = "苹果是水果" + "e".repeat(2000) + let u8 = new Uint8Array([1, 2, 3]) + let nameStr = "苹果是水果" + "e".repeat(2000) const valueBucket = { "name": nameStr, "age": 20, @@ -253,8 +253,8 @@ describe('rdbStoreInsertTest', function () { */ it('testRdbStoreInsert0006', 0, async function (done) { console.log(TAG + "************* testRdbStoreInsert0006 start *************"); - var u8 = new Uint8Array([1, 2, 3]) - var nameStr = "西瓜是水果" + "e".repeat(2000) + "好吃又好看" + let u8 = new Uint8Array([1, 2, 3]) + let nameStr = "西瓜是水果" + "e".repeat(2000) + "好吃又好看" const valueBucket = { "name": nameStr, "age": 21, @@ -287,7 +287,7 @@ describe('rdbStoreInsertTest', function () { */ it('testRdbStoreGetString0001', 0, async function (done) { console.log(TAG + "************* testRdbStoreGetString0001 start *************"); - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "", "age": 21, @@ -322,7 +322,7 @@ describe('rdbStoreInsertTest', function () { it('testRdbStorebatchInsert001', 0, async function () { console.log(TAG + "************* testRdbStorebatchInsert001 start *************"); - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "zhangsan", "age": 18, @@ -341,20 +341,20 @@ describe('rdbStoreInsertTest', function () { console.log(TAG + "************* testRdbStorebatchInsert001 end *************"); }) - /** - * @tc.name: rdb batchInsert test - * @tc.number: SUB_DDM_AppDataFWK_JSRDB_batchInsert_0001 - * @tc.desc: rdb batchInsert test - * @tc.require: issueI5GZGX - */ - it('testRdbStorebatchInsert002', 0, async function () { + /** + * @tc.name: rdb batchInsert test + * @tc.number: SUB_DDM_AppDataFWK_JSRDB_batchInsert_0001 + * @tc.desc: rdb batchInsert test + * @tc.require: issueI5GZGX + */ + it('testRdbStorebatchInsert002', 0, async function () { console.log(TAG + "************* testRdbStorebatchInsert002 start *************"); await rdbStore.executeSql("delete from test"); let valueBucketArray = new Array(); - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "zhangsan", "age": 18, @@ -407,20 +407,20 @@ describe('rdbStoreInsertTest', function () { console.log(TAG + "************* testRdbStorebatchInsert002 end *************"); }) - /** - * @tc.name: rdb batchInsert test - * @tc.number: SUB_DDM_AppDataFWK_JSRDB_batchInsert_0003 - * @tc.desc: rdb batchInsert not exist column test - * @tc.require: issueIB3DGQ - */ - it('testRdbStorebatchInsert003', 0, async function () { + /** + * @tc.name: rdb batchInsert test + * @tc.number: SUB_DDM_AppDataFWK_JSRDB_batchInsert_0003 + * @tc.desc: rdb batchInsert not exist column test + * @tc.require: issueIB3DGQ + */ + it('testRdbStorebatchInsert003', 0, async function () { console.log(TAG + "************* testRdbStorebatchInsert003 start *************"); await rdbStore.executeSql("delete from test"); let valueBucketArray = new Array(); - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "zhangsan", "age": 18, @@ -438,5 +438,26 @@ describe('rdbStoreInsertTest', function () { resultSet.close() console.log(TAG + "************* testRdbStorebatchInsert003 end *************"); }) + + /** + * @tc.name: rdb batchInsert test + * @tc.number: SUB_DDM_AppDataFWK_JSRDB_batchInsert_0004 + * @tc.desc: Test with empty valueBucket in rdb batchInsert + * @tc.require: issueIB3DGQ + */ + it('testRdbStorebatchInsert004', 0, async function () { + console.log(TAG + "************* testRdbStorebatchInsert004 start *************"); + + await rdbStore.executeSql("delete from test"); + + let valueBucketArray = []; + let errCode = await rdbStore.batchInsert("test", valueBucketArray); + expect(0).assertEqual(errCode); + let resultSet = await rdbStore.querySql("SELECT * FROM test"); + let count = resultSet.rowCount; + expect(0).assertEqual(count); + resultSet.close() + console.log(TAG + "************* testRdbStorebatchInsert004 end *************"); + }) console.log(TAG + "*************Unit Test End*************"); }) \ No newline at end of file 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 df572a73efbf93f2a09db9863e66dde42ff793a4..6f3a5d1fa3cc5530342f3d03bf8f2cd7762d454a 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinBJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinBJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const DEPT_TABLE = "CREATE TABLE IF NOT EXISTS dept" @@ -72,10 +72,10 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(DEPT_TABLE); const depts = [ - {id:10, dName:"JiaoYanBU", loc:"BeiJing"}, - {id:20, dName:"XueGongBu", loc:"ShangHai"}, - {id:30, dName:"XiaoShouBu", loc:"GuangZhou"}, - {id:40, dName:"CaiWuBu", loc:"ShenZhen"}, + { id: 10, dName: "JiaoYanBU", loc: "BeiJing" }, + { id: 20, dName: "XueGongBu", loc: "ShangHai" }, + { id: 30, dName: "XiaoShouBu", loc: "GuangZhou" }, + { id: 40, dName: "CaiWuBu", loc: "ShenZhen" }, ]; await rdbStore.batchInsert("dept", depts); @@ -87,10 +87,10 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(JOB_TABLE); var jobs = [ - {id:1, jName:"Chairman", description:"ManageTheEntireCompany"}, - {id:2, jName:"Manager", description:"ManageEmployeesOfTheDepartment"}, - {id:3, jName:"Salesperson", description:"SellingProductsToCustomers"}, - {id:4, jName:"Clerk", description:"UseOfficeSoftware"}, + { id: 1, jName: "Chairman", description: "ManageTheEntireCompany" }, + { id: 2, jName: "Manager", description: "ManageEmployeesOfTheDepartment" }, + { id: 3, jName: "Salesperson", description: "SellingProductsToCustomers" }, + { id: 4, jName: "Clerk", description: "UseOfficeSoftware" }, ] await rdbStore.batchInsert("job", jobs); @@ -102,20 +102,20 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(EMP_TABLE); var emps = [ - {id:1001, eName:"SunWuKong", jobId:4, mgr:1004, joinDate:"2000-12-17", salary:8000.00, bonus:null, deptId:20}, - {id:1002, eName:"LuJunYi", jobId:3, mgr:1006, joinDate:"2001-02-20", salary:16000.00, bonus:3000.00, deptId:30}, - {id:1003, eName:"LinChong", jobId:3, mgr:1006, joinDate:"2001-02-22", salary:12500.00, bonus:5000.00, deptId:30}, - {id:1004, eName:"TangCeng", jobId:2, mgr:1009, joinDate:"2001-04-02", salary:29750.00, bonus:null, deptId:20}, - {id:1005, eName:"LiKui", jobId:4, mgr:1006, joinDate:"2001-09-28", salary:12500.00, bonus:14000.00, deptId:30}, - {id:1006, eName:"SongJiang", jobId:2, mgr:1009, joinDate:"2001-05-01", salary:28500.00, bonus:null, deptId:30}, - {id:1007, eName:"LiuBei", jobId:2, mgr:1009, joinDate:"2001-09-01", salary:24500.00, bonus:null, deptId:10}, - {id:1008, eName:"ZhuBaJie", jobId:4, mgr:1004, joinDate:"2007-04-19", salary:30000.00, bonus:null, deptId:20}, - {id:1009, eName:"LuoGuanZhong", jobId:1, mgr:null, joinDate:"2001-11-17", salary:50000.00, bonus:null, deptId:10}, - {id:1010, eName:"WuYong", jobId:3, mgr:1006, joinDate:"2001-09-08", salary:15000.00, bonus:0.00, deptId:30}, - {id:1011, eName:"ShaCeng", jobId:4, mgr:1004, joinDate:"2007-05-23", salary:11000.00, bonus:null, deptId:20}, - {id:1012, eName:"LiKui", jobId:4, mgr:1006, joinDate:"2001-12-03", salary:9500.00, bonus:null, deptId:30}, - {id:1013, eName:"XiaoBaiLong", jobId:4, mgr:1004, joinDate:"2001-12-03", salary:30000.00, bonus:null, deptId:20}, - {id:1014, eName:"GuanYu", jobId:4, mgr:1007, joinDate:"2002-01-23", salary:13000.00, bonus:null, deptId:10}, + { id: 1001, eName: "SunWuKong", jobId: 4, mgr: 1004, joinDate: "2000-12-17", salary: 8000.00, bonus: null, deptId: 20 }, + { id: 1002, eName: "LuJunYi", jobId: 3, mgr: 1006, joinDate: "2001-02-20", salary: 16000.00, bonus: 3000.00, deptId: 30 }, + { id: 1003, eName: "LinChong", jobId: 3, mgr: 1006, joinDate: "2001-02-22", salary: 12500.00, bonus: 5000.00, deptId: 30 }, + { id: 1004, eName: "TangCeng", jobId: 2, mgr: 1009, joinDate: "2001-04-02", salary: 29750.00, bonus: null, deptId: 20 }, + { id: 1005, eName: "LiKui", jobId: 4, mgr: 1006, joinDate: "2001-09-28", salary: 12500.00, bonus: 14000.00, deptId: 30 }, + { id: 1006, eName: "SongJiang", jobId: 2, mgr: 1009, joinDate: "2001-05-01", salary: 28500.00, bonus: null, deptId: 30 }, + { id: 1007, eName: "LiuBei", jobId: 2, mgr: 1009, joinDate: "2001-09-01", salary: 24500.00, bonus: null, deptId: 10 }, + { id: 1008, eName: "ZhuBaJie", jobId: 4, mgr: 1004, joinDate: "2007-04-19", salary: 30000.00, bonus: null, deptId: 20 }, + { id: 1009, eName: "LuoGuanZhong", jobId: 1, mgr: null, joinDate: "2001-11-17", salary: 50000.00, bonus: null, deptId: 10 }, + { id: 1010, eName: "WuYong", jobId: 3, mgr: 1006, joinDate: "2001-09-08", salary: 15000.00, bonus: 0.00, deptId: 30 }, + { id: 1011, eName: "ShaCeng", jobId: 4, mgr: 1004, joinDate: "2007-05-23", salary: 11000.00, bonus: null, deptId: 20 }, + { id: 1012, eName: "LiKui", jobId: 4, mgr: 1006, joinDate: "2001-12-03", salary: 9500.00, bonus: null, deptId: 30 }, + { id: 1013, eName: "XiaoBaiLong", jobId: 4, mgr: 1004, joinDate: "2001-12-03", salary: 30000.00, bonus: null, deptId: 20 }, + { id: 1014, eName: "GuanYu", jobId: 4, mgr: 1007, joinDate: "2002-01-23", salary: 13000.00, bonus: null, deptId: 10 }, ]; await rdbStore.batchInsert("emp", emps); @@ -128,11 +128,11 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(SALARYGRADE_TABLE); var salarygrades = [ - {grade:1, loSalary:7000, hiSalary:12000}, - {grade:2, loSalary:12010, hiSalary:14000}, - {grade:3, loSalary:14010, hiSalary:20000}, - {grade:4, loSalary:20010, hiSalary:30000}, - {grade:5, loSalary:30010, hiSalary:99990}, + { grade: 1, loSalary: 7000, hiSalary: 12000 }, + { grade: 2, loSalary: 12010, hiSalary: 14000 }, + { grade: 3, loSalary: 14010, hiSalary: 20000 }, + { grade: 4, loSalary: 20010, hiSalary: 30000 }, + { grade: 5, loSalary: 30010, hiSalary: 99990 }, ]; await rdbStore.batchInsert("salarygrade", salarygrades); diff --git a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js index f529bc7422955f2780317b9a43cdfeb899fd839f..2d7cdeed4b39b9c2b5a9496e3790f5518f437a71 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJoinJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const USER_TABLE = "CREATE TABLE IF NOT EXISTS user " @@ -68,11 +68,11 @@ describe('rdbStorePredicatesJoinTest', function () { await rdbStore.executeSql(USER_TABLE); const users = [ - {userId:1, firstName:"Zhang", lastName:"San", age:29, balance:100.51}, - {userId:2, firstName:"Li", lastName:"Si", age:30, balance:200.51}, - {userId:3, firstName:"wang", lastName:"wu", age:30, balance:300.51}, - {userId:4, firstName:"sun", lastName:"liu", age:30, balance:400.51}, - {userId:5, firstName:"ma", lastName:"qi", age:32, balance:500.51}, + { userId: 1, firstName: "Zhang", lastName: "San", age: 29, balance: 100.51 }, + { userId: 2, firstName: "Li", lastName: "Si", age: 30, balance: 200.51 }, + { userId: 3, firstName: "wang", lastName: "wu", age: 30, balance: 300.51 }, + { userId: 4, firstName: "sun", lastName: "liu", age: 30, balance: 400.51 }, + { userId: 5, firstName: "ma", lastName: "qi", age: 32, balance: 500.51 }, ]; var objects = new Array(); @@ -93,9 +93,9 @@ describe('rdbStorePredicatesJoinTest', function () { await rdbStore.executeSql(BOOK_TABLE); var books = [ - {id:1, name:"SanGuo", userId:1}, - {id:2, name:"XiYouJi", userId:2}, - {id:3, name:"ShuiHuZhuan", userId:3}, + { id: 1, name: "SanGuo", userId: 1 }, + { id: 2, name: "XiYouJi", userId: 2 }, + { id: 3, name: "ShuiHuZhuan", userId: 3 }, ] var objects = new Array(); 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 cb26f471cfb1d76712f76b1c0b951ec6179323bf..f0d99b056faedbf640eadaa5e3f7c1c60d974e42 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstorePredicatesJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS _TEST]" @@ -458,7 +458,7 @@ describe('rdbPredicatesTest', function () { * @tc.desc 1.predicates not equalTo normal test * 2.predicates not equalTo abnormal test */ - it('testNotEqualTo0009', 0, async function (done) { + it('testNotEqualTo0009', 0, async function (done) { console.log(TAG + "************* testNotEqualTo0009 start *************"); let predicates1 = new dataRdb.RdbPredicates("AllDataType"); @@ -776,7 +776,7 @@ describe('rdbPredicatesTest', function () { * 4.predicates greaterThan abnormal "Number.MIN_SAFE_INTEGER" test * 5.predicates greaterThan abnormal "Number.MAX_SAFE_INTEGER" test */ - it('testGreaterThan0009', 0, async function (done) { + it('testGreaterThan0009', 0, async function (done) { console.log(TAG + "************* testGreaterThan0009 start *************"); let predicates1 = new dataRdb.RdbPredicates("AllDataType"); @@ -1471,7 +1471,7 @@ describe('rdbPredicatesTest', function () { * 5.predicates between abnormal "Number.NEGATIVE_INFINITY" test * 6.predicates between abnormal "Number.POSITIVE_INFINITY" test */ - it('testNotBetween0005', 0, async function (done) { + it('testNotBetween0005', 0, async function (done) { console.log(TAG + "************* testNotBetween0005 start *************"); let predicates1 = new dataRdb.RdbPredicates("AllDataType"); @@ -1703,7 +1703,7 @@ describe('rdbPredicatesTest', function () { * @tc.desc 1.predicates contains abnormal "null" test * 2.predicates contains abnormal "undefined" test */ - it('testContains0005', 0, async function (done) { + it('testContains0005', 0, async function (done) { console.log(TAG + "************* testContains0005 start *************"); let predicates1 = new dataRdb.RdbPredicates("AllDataType"); @@ -1935,7 +1935,7 @@ describe('rdbPredicatesTest', function () { * @tc.desc 1.predicates like abnormal "null" test * 2.predicates like abnormal "undefined" test */ - it('testLike0005', 0, async function (done) { + it('testLike0005', 0, async function (done) { console.log(TAG + "************* testLike0005 start *************"); let predicates1 = new dataRdb.RdbPredicates("AllDataType"); @@ -2453,7 +2453,7 @@ describe('rdbPredicatesTest', function () { console.log(TAG + "************* testIn0004 end *************"); }) - /** + /** * @tc.name predicates in normal test * @tc.number SUB_DDM_AppDataFWK_JSRDB_Predicates_0194 * @tc.desc predicates in normal test 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 39a5ea722fe779c92ead1116b980af414be0ace6..5bf9b6d6d0653af955cefc765a80a677a7cff74f 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreRdbstoreJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS_TEST]" diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js index 2fef3b4bfc72f919f9e1a3653b6a8d585357e85f..60c72b019b591be3da2dd430335ef11b0af9b27e 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS_TEST]" @@ -203,7 +203,7 @@ describe('rdbStoreExcuteSqlTest', function () { { let executeSqlPromise = rdbStore.executeSql("DELETE FROM test WHERE age = 19 AND name ='" + nameStr + "'") executeSqlPromise.then(async () => { - await console.log(TAG + "executeSql done." ); + await console.log(TAG + "executeSql done."); }).catch((err) => { expect(null).assertFail(); }) diff --git a/relational_store/test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js b/relational_store/test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js index 977d795ce7bb794b84b6daa4a8b602f64c5818a1..b6369dc8cae3b8b9412632c09789002f7e2b128f 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreTransactionJsunit.test.js @@ -13,11 +13,11 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS_TEST]" -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY, " + +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = { 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 d5130bb6c23c0ef71931c50f0d7dfaacebd28b18..63339ec739cf037fc474b849eb25f9df1c0ebedc 100644 --- a/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js +++ b/relational_store/test/js/rdb/unittest/src/RdbstoreUpdateJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import dataRdb from '@ohos.data.rdb'; const TAG = "[RDB_JSKITS_TEST]" diff --git a/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js b/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js index da7fd55667909073b7898bb0c25dff127201fa25..b70d9fb37056e247e4f152dd6d234d500df8cdec 100644 --- a/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js index 7781c9dddb136adffddac2251d5f6e3d2f8596da..a0b6ba909c67cdf3b956eb1619b48b80c2365e24 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js b/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js index 0b14e242b9a2edb545219c082492e4611bd7ee1f..5c9af297a16bb409a4f67d8a8995de78aabf114b 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js index 72aed689349e5844eba2c1bd25937790d34327d3..3b16b3ccfbb0a86ac5f5899e316538cb169a1763 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js index 1bce013b5c1b5e7961c915fc990a3617776490e9..b04a51f49d133b06d271f8681f2179daaf4d70af 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js index a2209b6f2eda796749646b0fea46becdeb63d94d..b03729bbf3a61f6d41c6340177a3563318a330ab 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js index 3a3b90f288a0868846bcb18e68cc56f6b0419a3f..42fe4f7514422790a72b3de3127e28ca71685ac7 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js b/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js index 797a790627bb38dec55fd72460786ce1547d67d6..ab8cb9a147fc8e3ca95257fc7a7ef75ebb9e0aff 100644 --- a/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; diff --git a/relational_store/test/js/relationalstore/performance/src/SceneGetValuesBucketPerf.js b/relational_store/test/js/relationalstore/performance/src/SceneGetValuesBucketPerf.js index 91760e76f2200ddb665b67ebe827828c47986488..2113c85ccbb07dd6e98f54ae90d1b385b7256406 100644 --- a/relational_store/test/js/relationalstore/performance/src/SceneGetValuesBucketPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/SceneGetValuesBucketPerf.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js index 5ee705a9f1f3560b1de94db36aa8c955d5dca8ac..5b81898d07dba7dad0e557662248bf406b358dfb 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -151,7 +151,7 @@ describe('rdbAssetResultSetTest', function () { try { await rdbStore.insert("test", valuesBucket) expect().assertFail(); - } catch(e) { + } catch (e) { console.log("insert failed, err: code=" + e.code + " message=" + e.message) expect(e.code == 401).assertTrue(); } @@ -184,7 +184,7 @@ describe('rdbAssetResultSetTest', function () { try { await rdbStore.batchInsert("test", array) expect().assertFail(); - } catch(e) { + } catch (e) { console.log("batchInsert failed, err: code=" + e.code + " message=" + e.message) expect(e.code == 401).assertTrue(); } @@ -207,7 +207,7 @@ describe('rdbAssetResultSetTest', function () { try { await rdbStore.executeSql("insert into test (data1, data2, data3) values (?,?,?)", array) expect().assertFail(); - } catch(e) { + } catch (e) { console.log("executeSql failed, err: code=" + e.code + " message=" + e.message) expect(e.code == 401).assertTrue(); } @@ -692,7 +692,7 @@ describe('rdbAssetResultSetTest', function () { } let assets = [asset]; let valuesBucket = { - "data3" : assets, + "data3": assets, } await rdbStore.insert("test", valuesBucket); let predicates = await new data_relationalStore.RdbPredicates("test") @@ -710,7 +710,7 @@ describe('rdbAssetResultSetTest', function () { expect(null).assertFail(); } console.log(TAG + "************* testGetAssetsUpdate1 insert success *************"); - const asset5 = { + const asset5 = { name: "name4", uri: "uri5", createTime: "createTime5", @@ -721,7 +721,7 @@ describe('rdbAssetResultSetTest', function () { } assets = [asset5]; valuesBucket = { - "data3" : assets, + "data3": assets, } predicates.equalTo("id", id); await rdbStore.update(valuesBucket, predicates); @@ -767,7 +767,7 @@ describe('rdbAssetResultSetTest', function () { } let assets = [asset]; let valuesBucket = { - "data3" : assets, + "data3": assets, } await rdbStore.insert("test", valuesBucket); let predicates = await new data_relationalStore.RdbPredicates("test") @@ -785,7 +785,7 @@ describe('rdbAssetResultSetTest', function () { expect(null).assertFail(); } console.log(TAG + "************* testGetAssetsUpdate2 insert success *************"); - const asset5 = { + const asset5 = { name: "name4", uri: "uri5", createTime: "createTime5", @@ -796,7 +796,7 @@ describe('rdbAssetResultSetTest', function () { } assets = [asset5]; valuesBucket = { - "data3" : assets, + "data3": assets, } predicates.equalTo("id", id); await rdbStore.update(valuesBucket, predicates); @@ -853,7 +853,7 @@ describe('rdbAssetResultSetTest', function () { console.log(TAG + "insert throw error: " + e.code + ", message is " + e.message); expect(null).assertFail(); } - const asset5 = { + const asset5 = { name: "name5", uri: "uri5", createTime: "createTime5", @@ -863,7 +863,7 @@ describe('rdbAssetResultSetTest', function () { status: data_relationalStore.AssetStatus.ASSET_UPDATE, } valuesBucket = { - "data1" : asset5, + "data1": asset5, } predicates.equalTo("id", id); await rdbStore.update(valuesBucket, predicates); @@ -917,7 +917,7 @@ describe('rdbAssetResultSetTest', function () { console.log(TAG + "insert throw error: " + e.code + ", message is " + e.message); expect(null).assertFail(); } - const asset5 = { + const asset5 = { name: "name5", uri: "uri5", createTime: "createTime5", @@ -927,7 +927,7 @@ describe('rdbAssetResultSetTest', function () { status: data_relationalStore.AssetStatus.ASSET_UPDATE, } valuesBucket = { - "data1" : asset5, + "data1": asset5, } predicates.equalTo("id", id); await rdbStore.update(valuesBucket, predicates); @@ -980,7 +980,7 @@ describe('rdbAssetResultSetTest', function () { console.log(TAG + "insert throw error: " + e.code + ", message is " + e.message); expect(null).assertFail(); } - const asset5 = { + const asset5 = { name: "name1", uri: "uri5", createTime: "createTime5", @@ -990,7 +990,7 @@ describe('rdbAssetResultSetTest', function () { status: data_relationalStore.AssetStatus.ASSET_DELETE, } valuesBucket = { - "data1" : asset5, + "data1": asset5, } predicates.equalTo("id", id); await rdbStore.update(valuesBucket, predicates); @@ -1037,7 +1037,7 @@ describe('rdbAssetResultSetTest', function () { console.log(TAG + "insert throw error: " + e.code + ", message is " + e.message); expect(null).assertFail(); } - const asset5 = { + const asset5 = { name: "name1", uri: "uri5", createTime: "createTime5", @@ -1047,7 +1047,7 @@ describe('rdbAssetResultSetTest', function () { status: data_relationalStore.AssetStatus.ASSET_NORMAL, } valuesBucket = { - "data1" : asset5, + "data1": asset5, } predicates.equalTo("id", id); await rdbStore.update(valuesBucket, predicates); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreAttachJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreAttachJsunit.test.js index 9b3e9b865628d15ed3b5bfda88157ef400e5548c..93439183274485d9efc10c6a273e17bae4fa67b8 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreAttachJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreAttachJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -23,10 +23,10 @@ var context = ability_featureAbility.getContext(); const TAG = "[RELATIONAL_STORE_JSKITS_TEST]" const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + -"name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const CREATE_TABLE_TEST1 = "CREATE TABLE IF NOT EXISTS test1 (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + -"name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = { @@ -52,407 +52,407 @@ const STORE_CONFIG3 = { } describe('ActsRdbStoreAttachTest', function () { -beforeAll(async function () { - console.info(TAG + 'beforeAll'); -}) - -beforeEach(async function () { - console.info(TAG + 'beforeEach'); - let attachStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG1); - await attachStore.executeSql(CREATE_TABLE_TEST1); - let attachStore1 = await data_relationalStore.getRdbStore(context, STORE_CONFIG2); - await attachStore1.executeSql(CREATE_TABLE_TEST1); -}) - -afterEach(async function () { - console.info(TAG + 'afterEach') - await data_relationalStore.deleteRdbStore(context, "rdbstore.db"); - await data_relationalStore.deleteRdbStore(context, "rdbstore1.db"); - await data_relationalStore.deleteRdbStore(context, "rdbstore2.db"); - await data_relationalStore.deleteRdbStore(context, "rdbstore3.db"); -}) - -afterAll(async function () { - console.info(TAG + 'afterAll'); -}) - - -async function attachInsert(store, tableName) { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - }; - await store.insert(tableName, valueBucket); -} - -async function attachBatchInsert(store, tableName) { - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - }; - let valueBucketArray = new Array(); - for (let i = 0; i < 10; i++) { - valueBucketArray.push(valueBucket); + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + }) + + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + let attachStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG1); + await attachStore.executeSql(CREATE_TABLE_TEST1); + let attachStore1 = await data_relationalStore.getRdbStore(context, STORE_CONFIG2); + await attachStore1.executeSql(CREATE_TABLE_TEST1); + }) + + afterEach(async function () { + console.info(TAG + 'afterEach') + await data_relationalStore.deleteRdbStore(context, "rdbstore.db"); + await data_relationalStore.deleteRdbStore(context, "rdbstore1.db"); + await data_relationalStore.deleteRdbStore(context, "rdbstore2.db"); + await data_relationalStore.deleteRdbStore(context, "rdbstore3.db"); + }) + + afterAll(async function () { + console.info(TAG + 'afterAll'); + }) + + + async function attachInsert(store, tableName) { + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + }; + await store.insert(tableName, valueBucket); } - await store.batchInsert(tableName, valueBucketArray); -} - -async function insertCheck(store, tableName, ret) { - let predicates = new data_relationalStore.RdbPredicates(tableName); - let resultSet = await store.query(predicates); - let count = resultSet.rowCount; - expect(ret).assertEqual(count); - resultSet.close(); -} -async function updateCheck(store, tableName) { - var u8 = new Uint8Array([4, 5, 6]); - const valueBucket = { - "name": "lisi", - "age": 20, - "salary": 200.5, - "blobType": u8, - }; - let predicates = new data_relationalStore.RdbPredicates(tableName) - predicates.equalTo("id", "1"); - let ret = await store.update(valueBucket, predicates); - expect(1).assertEqual(ret); -} - -async function deleteCheck(store, tableName, count) { - let predicates = new data_relationalStore.RdbPredicates(tableName); - let ret = await store.delete(predicates); - expect(count).assertEqual(ret); -} - -async function attachCheck(store) { - await attachInsert(store, "test"); - await insertCheck(store, "test", 2); - await updateCheck(store, "test"); - await attachBatchInsert(store, "test"); - await insertCheck(store, "test", 12); - await deleteCheck(store, "test", 12); - - await attachInsert(store, "test1"); - await insertCheck(store, "test1", 1) - await updateCheck(store, "test1"); - await attachBatchInsert(store, "test1"); - await insertCheck(store, "test1", 11); - await deleteCheck(store, "test1", 11); -} - -console.log(TAG + "*************Unit Test Begin*************"); - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_001 - * @tc.desc non encrypted database attach non encrypted database - */ -it('testRdbStoreAttach0001', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0001 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachInsert(store, "test"); - - let number = await store.attach(context, STORE_CONFIG1, "attachDB"); - expect(1).assertEqual(number); - - await attachCheck(store); - expect(0).assertEqual(await store.detach("attachDB")) - console.log(TAG + "************* testRdbStoreAttach0001 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_002 - * @tc.desc non encrypted database attach encrypted database - */ -it('testRdbStoreAttach0002', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0002 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachInsert(store, "test"); - - let number = await store.attach(context, STORE_CONFIG2, "attachDB"); - expect(1).assertEqual(number); - - await attachCheck(store); - expect(0).assertEqual(await store.detach("attachDB")) - console.log(TAG + "************* testRdbStoreAttach0002 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_003 - * @tc.desc encrypted database attach encrypted database - */ -it('testRdbStoreAttach0003', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0003 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG3); - await store.executeSql(CREATE_TABLE_TEST); - await attachInsert(store, "test"); - - let number = await store.attach(context, STORE_CONFIG2, "attachDB"); - expect(1).assertEqual(number); - - await attachCheck(store); - expect(0).assertEqual(await store.detach("attachDB")); - console.log(TAG + "************* testRdbStoreAttach0003 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_004 - * @tc.desc encrypted databases are not supported for attaching non encrypted databases - */ -it('testRdbStoreAttach0004', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0004 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG3); - try { - await store.attach(context, STORE_CONFIG1, "attachDB"); - expect().assertFail(); - } catch(e) { - console.log("attach err: failed, err: code=" + e.code + " message=" + e.message) - expect(801).assertEqual(e.code); + async function attachBatchInsert(store, tableName) { + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + }; + let valueBucketArray = new Array(); + for (let i = 0; i < 10; i++) { + valueBucketArray.push(valueBucket); + } + await store.batchInsert(tableName, valueBucketArray); } - console.log(TAG + "************* testRdbStoreAttach0004 end *************"); -}) -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_005 - * @tc.desc non encrypted database attach non encrypted database - */ -it('testRdbStoreAttach0005', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0005 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachInsert(store, "test"); - let number = await store.attach("/data/storage/el2/database/entry/rdb/rdbstore1.db", "attachDB"); - expect(1).assertEqual(number); - await attachCheck(store); - expect(0).assertEqual(await store.detach("attachDB")); - console.log(TAG + "************* testRdbStoreAttach0005 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_006 - * @tc.desc path error for non encrypted database - */ -it('testRdbStoreAttach0006', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0006 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachInsert(store, "test"); - - let STORE_CONFIG4 = { - name: "/wrong/rdbstore.db", - securityLevel: data_relationalStore.SecurityLevel.S1, - } - try { - await store.attach(context, STORE_CONFIG4, "attachDB"); - } catch (e) { - console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) - expect("401").assertEqual(e.code); + async function insertCheck(store, tableName, ret) { + let predicates = new data_relationalStore.RdbPredicates(tableName); + let resultSet = await store.query(predicates); + let count = resultSet.rowCount; + expect(ret).assertEqual(count); + resultSet.close(); } - console.log(TAG + "************* testRdbStoreAttach0006 end *************"); -}) -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_007 - * @tc.desc non encrypted database attach non encrypted database with same table name - */ -it('testRdbStoreAttach0007', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0007 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST1); - await attachInsert(store, "test1"); - - let number = await store.attach(context, STORE_CONFIG1, "attachDB"); - expect(1).assertEqual(number); - - await attachInsert(store, "test1"); - await insertCheck(store, "test1", 2); - await updateCheck(store, "test1"); - await attachBatchInsert(store, "test1"); - await insertCheck(store, "test1", 12); - await deleteCheck(store, "test1", 12); - - await attachInsert(store, "attachDB.test1"); - await insertCheck(store, "attachDB.test1", 1) - await updateCheck(store, "attachDB.test1"); - await attachBatchInsert(store, "attachDB.test1"); - await insertCheck(store, "attachDB.test1", 11); - await deleteCheck(store, "attachDB.test1", 11); - - expect(0).assertEqual(await store.detach("attachDB")) - console.log(TAG + "************* testRdbStoreAttach0007 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_008 - * @tc.desc resultSet occupies connection, attach failed - */ -it('testRdbStoreAttach0008', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0008 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachBatchInsert(store, "test"); - - let predicates = new data_relationalStore.RdbPredicates("test"); - let resultSet = await store.query(predicates); - let count = resultSet.rowCount; - expect(10).assertEqual(count); - try { - await store.attach("/data/storage/el2/database/entry/rdb/rdbstore1.db", "attachDB"); - expect().assertFail(); - } catch(e) { - expect(14800015).assertEqual(e.code); - } - resultSet.close(); - console.log(TAG + "************* testRdbStoreAttach0008 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_009 - * @tc.desc repeat attach using the same alias - */ -it('testRdbStoreAttach0009', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach0009 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachBatchInsert(store, "test"); - let number = await store.attach(context, STORE_CONFIG1, 'attachDB'); - expect(1).assertEqual(number); - try { - await store.attach(context, STORE_CONFIG1, 'attachDB'); - expect().assertFail(); - } catch(e) { - console.log("testRdbStoreAttach0009: failed, err: code=" + e.code + " message=" + e.message); - expect(14800016).assertEqual(e.code); - } - expect(0).assertEqual(await store.detach("attachDB")); - - console.log(TAG + "************* testRdbStoreAttach0009 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0010 - * @tc.desc WaitTime exceeds maximum limit - */ -it('testRdbStoreAttach00010', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach00010 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachBatchInsert(store, "test"); - let number = await store.attach(context, STORE_CONFIG1, 'attachDB', 300); - expect(1).assertEqual(number); - try { - await store.attach(context, STORE_CONFIG1, 'attachDB', 301); - expect().assertFail(); - } catch(e) { - console.log("testRdbStoreAttach00010: failed, err: code=" + e.code + " message=" + e.message); - expect("401").assertEqual(e.code); - } - expect(0).assertEqual(await store.detach("attachDB")); - - console.log(TAG + "************* testRdbStoreAttach00010 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0011 - * @tc.desc WaitTime exceeds the minimum limit - */ -it('testRdbStoreAttach00011', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach00011 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachBatchInsert(store, "test"); - let number = await store.attach(context, STORE_CONFIG1, 'attachDB', 1); - expect(1).assertEqual(number); - try { - await store.attach(context, STORE_CONFIG1, 'attachDB', -1); - expect().assertFail(); - } catch(e) { - console.log("testRdbStoreAttach00011: failed, err: code=" + e.code + " message=" + e.message); - expect('401').assertEqual(e.code); + async function updateCheck(store, tableName) { + var u8 = new Uint8Array([4, 5, 6]); + const valueBucket = { + "name": "lisi", + "age": 20, + "salary": 200.5, + "blobType": u8, + }; + let predicates = new data_relationalStore.RdbPredicates(tableName) + predicates.equalTo("id", "1"); + let ret = await store.update(valueBucket, predicates); + expect(1).assertEqual(ret); } - expect(0).assertEqual(await store.detach("attachDB")); - console.log(TAG + "************* testRdbStoreAttach00011 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0012 - * @tc.desc the alias cannot be empty - */ -it('testRdbStoreAttach00012', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach00012 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachBatchInsert(store, "test"); - try { - await store.attach(context, STORE_CONFIG1, ''); - expect().assertFail(); - } catch(e) { - console.log("testRdbStoreAttach00012 : failed, err: code=" + e.code + " message=" + e.message); - expect('401').assertEqual(e.code); + async function deleteCheck(store, tableName, count) { + let predicates = new data_relationalStore.RdbPredicates(tableName); + let ret = await store.delete(predicates); + expect(count).assertEqual(ret); } - console.log(TAG + "************* testRdbStoreAttach00012 end *************"); -}) -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0013 - * @tc.desc input error path - */ -it('testRdbStoreAttach00013', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach00013 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachBatchInsert(store, "test"); - try { - await store.attach("/path/errPath/attach.db", "attachDB"); - expect().assertFail(); - } catch(e) { - console.log("testRdbStoreAttach00013 : failed, err: code=" + e.code + " message=" + e.message); - expect(14800010).assertEqual(e.code); - } - console.log(TAG + "************* testRdbStoreAttach00013 end *************"); -}) - -/** - * @tc.name the attach function - * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0014 - * @tc.desc input empty path - */ -it('testRdbStoreAttach00014', 0, async function () { - console.log(TAG + "************* testRdbStoreAttach00014 start *************"); - let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); - await store.executeSql(CREATE_TABLE_TEST); - await attachBatchInsert(store, "test"); - try { - await store.attach("", "attachDB"); - expect().assertFail(); - } catch(e) { - console.log("testRdbStoreAttach00014 : failed, err: code=" + e.code + " message=" + e.message); - expect('401').assertEqual(e.code); + async function attachCheck(store) { + await attachInsert(store, "test"); + await insertCheck(store, "test", 2); + await updateCheck(store, "test"); + await attachBatchInsert(store, "test"); + await insertCheck(store, "test", 12); + await deleteCheck(store, "test", 12); + + await attachInsert(store, "test1"); + await insertCheck(store, "test1", 1) + await updateCheck(store, "test1"); + await attachBatchInsert(store, "test1"); + await insertCheck(store, "test1", 11); + await deleteCheck(store, "test1", 11); } - console.log(TAG + "************* testRdbStoreAttach00014 end *************"); -}) -console.log(TAG + "*************Unit Test End*************"); + console.log(TAG + "*************Unit Test Begin*************"); + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_001 + * @tc.desc non encrypted database attach non encrypted database + */ + it('testRdbStoreAttach0001', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0001 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachInsert(store, "test"); + + let number = await store.attach(context, STORE_CONFIG1, "attachDB"); + expect(1).assertEqual(number); + + await attachCheck(store); + expect(0).assertEqual(await store.detach("attachDB")) + console.log(TAG + "************* testRdbStoreAttach0001 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_002 + * @tc.desc non encrypted database attach encrypted database + */ + it('testRdbStoreAttach0002', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0002 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachInsert(store, "test"); + + let number = await store.attach(context, STORE_CONFIG2, "attachDB"); + expect(1).assertEqual(number); + + await attachCheck(store); + expect(0).assertEqual(await store.detach("attachDB")) + console.log(TAG + "************* testRdbStoreAttach0002 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_003 + * @tc.desc encrypted database attach encrypted database + */ + it('testRdbStoreAttach0003', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0003 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG3); + await store.executeSql(CREATE_TABLE_TEST); + await attachInsert(store, "test"); + + let number = await store.attach(context, STORE_CONFIG2, "attachDB"); + expect(1).assertEqual(number); + + await attachCheck(store); + expect(0).assertEqual(await store.detach("attachDB")); + console.log(TAG + "************* testRdbStoreAttach0003 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_004 + * @tc.desc encrypted databases are not supported for attaching non encrypted databases + */ + it('testRdbStoreAttach0004', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0004 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG3); + try { + await store.attach(context, STORE_CONFIG1, "attachDB"); + expect().assertFail(); + } catch (e) { + console.log("attach err: failed, err: code=" + e.code + " message=" + e.message) + expect(801).assertEqual(e.code); + } + console.log(TAG + "************* testRdbStoreAttach0004 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_005 + * @tc.desc non encrypted database attach non encrypted database + */ + it('testRdbStoreAttach0005', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0005 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachInsert(store, "test"); + let number = await store.attach("/data/storage/el2/database/entry/rdb/rdbstore1.db", "attachDB"); + expect(1).assertEqual(number); + await attachCheck(store); + expect(0).assertEqual(await store.detach("attachDB")); + console.log(TAG + "************* testRdbStoreAttach0005 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_006 + * @tc.desc path error for non encrypted database + */ + it('testRdbStoreAttach0006', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0006 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachInsert(store, "test"); + + let STORE_CONFIG4 = { + name: "/wrong/rdbstore.db", + securityLevel: data_relationalStore.SecurityLevel.S1, + } + try { + await store.attach(context, STORE_CONFIG4, "attachDB"); + } catch (e) { + console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) + expect("401").assertEqual(e.code); + } + console.log(TAG + "************* testRdbStoreAttach0006 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_007 + * @tc.desc non encrypted database attach non encrypted database with same table name + */ + it('testRdbStoreAttach0007', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0007 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST1); + await attachInsert(store, "test1"); + + let number = await store.attach(context, STORE_CONFIG1, "attachDB"); + expect(1).assertEqual(number); + + await attachInsert(store, "test1"); + await insertCheck(store, "test1", 2); + await updateCheck(store, "test1"); + await attachBatchInsert(store, "test1"); + await insertCheck(store, "test1", 12); + await deleteCheck(store, "test1", 12); + + await attachInsert(store, "attachDB.test1"); + await insertCheck(store, "attachDB.test1", 1) + await updateCheck(store, "attachDB.test1"); + await attachBatchInsert(store, "attachDB.test1"); + await insertCheck(store, "attachDB.test1", 11); + await deleteCheck(store, "attachDB.test1", 11); + + expect(0).assertEqual(await store.detach("attachDB")) + console.log(TAG + "************* testRdbStoreAttach0007 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_008 + * @tc.desc resultSet occupies connection, attach failed + */ + it('testRdbStoreAttach0008', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0008 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachBatchInsert(store, "test"); + + let predicates = new data_relationalStore.RdbPredicates("test"); + let resultSet = await store.query(predicates); + let count = resultSet.rowCount; + expect(10).assertEqual(count); + try { + await store.attach("/data/storage/el2/database/entry/rdb/rdbstore1.db", "attachDB"); + expect().assertFail(); + } catch (e) { + expect(14800015).assertEqual(e.code); + } + resultSet.close(); + console.log(TAG + "************* testRdbStoreAttach0008 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_009 + * @tc.desc repeat attach using the same alias + */ + it('testRdbStoreAttach0009', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach0009 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachBatchInsert(store, "test"); + let number = await store.attach(context, STORE_CONFIG1, 'attachDB'); + expect(1).assertEqual(number); + try { + await store.attach(context, STORE_CONFIG1, 'attachDB'); + expect().assertFail(); + } catch (e) { + console.log("testRdbStoreAttach0009: failed, err: code=" + e.code + " message=" + e.message); + expect(14800016).assertEqual(e.code); + } + expect(0).assertEqual(await store.detach("attachDB")); + + console.log(TAG + "************* testRdbStoreAttach0009 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0010 + * @tc.desc WaitTime exceeds maximum limit + */ + it('testRdbStoreAttach00010', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach00010 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachBatchInsert(store, "test"); + let number = await store.attach(context, STORE_CONFIG1, 'attachDB', 300); + expect(1).assertEqual(number); + try { + await store.attach(context, STORE_CONFIG1, 'attachDB', 301); + expect().assertFail(); + } catch (e) { + console.log("testRdbStoreAttach00010: failed, err: code=" + e.code + " message=" + e.message); + expect("401").assertEqual(e.code); + } + expect(0).assertEqual(await store.detach("attachDB")); + + console.log(TAG + "************* testRdbStoreAttach00010 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0011 + * @tc.desc WaitTime exceeds the minimum limit + */ + it('testRdbStoreAttach00011', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach00011 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachBatchInsert(store, "test"); + let number = await store.attach(context, STORE_CONFIG1, 'attachDB', 1); + expect(1).assertEqual(number); + try { + await store.attach(context, STORE_CONFIG1, 'attachDB', -1); + expect().assertFail(); + } catch (e) { + console.log("testRdbStoreAttach00011: failed, err: code=" + e.code + " message=" + e.message); + expect('401').assertEqual(e.code); + } + expect(0).assertEqual(await store.detach("attachDB")); + + console.log(TAG + "************* testRdbStoreAttach00011 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0012 + * @tc.desc the alias cannot be empty + */ + it('testRdbStoreAttach00012', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach00012 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachBatchInsert(store, "test"); + try { + await store.attach(context, STORE_CONFIG1, ''); + expect().assertFail(); + } catch (e) { + console.log("testRdbStoreAttach00012 : failed, err: code=" + e.code + " message=" + e.message); + expect('401').assertEqual(e.code); + } + console.log(TAG + "************* testRdbStoreAttach00012 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0013 + * @tc.desc input error path + */ + it('testRdbStoreAttach00013', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach00013 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachBatchInsert(store, "test"); + try { + await store.attach("/path/errPath/attach.db", "attachDB"); + expect().assertFail(); + } catch (e) { + console.log("testRdbStoreAttach00013 : failed, err: code=" + e.code + " message=" + e.message); + expect(14800010).assertEqual(e.code); + } + console.log(TAG + "************* testRdbStoreAttach00013 end *************"); + }) + + /** + * @tc.name the attach function + * @tc.number SUB_DDM_AppDataFWK_JSRDB_RdbStore_attach_0014 + * @tc.desc input empty path + */ + it('testRdbStoreAttach00014', 0, async function () { + console.log(TAG + "************* testRdbStoreAttach00014 start *************"); + let store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + await store.executeSql(CREATE_TABLE_TEST); + await attachBatchInsert(store, "test"); + try { + await store.attach("", "attachDB"); + expect().assertFail(); + } catch (e) { + console.log("testRdbStoreAttach00014 : failed, err: code=" + e.code + " message=" + e.message); + expect('401').assertEqual(e.code); + } + console.log(TAG + "************* testRdbStoreAttach00014 end *************"); + }) + + console.log(TAG + "*************Unit Test End*************"); }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js index 9f08c5ad9d8d5e68618a9724ce8ae36f19c7c89e..1aa3f190f53b0185cbdc640f8ef72a828df9ce4d 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' @@ -165,15 +165,15 @@ describe('rdbStoreCloud', function () { } await rdbStore.setDistributedTables(['employee', 'product'], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config).then((err) => { - console.log(TAG + "set employee and product to be distributed cloud table success"); - expect(true).assertTrue(); - done(); - console.log(TAG + "************* testRdbStoreCloud0004 end *************"); - }).catch((err) => { - console.log(TAG + `set employee and product as distributed, errcode:${JSON.stringify(err)}.`); - expect().assertFail(); - done() - }); + console.log(TAG + "set employee and product to be distributed cloud table success"); + expect(true).assertTrue(); + done(); + console.log(TAG + "************* testRdbStoreCloud0004 end *************"); + }).catch((err) => { + console.log(TAG + `set employee and product as distributed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); + done() + }); } catch (err) { console.log(TAG + `set employee and product as distributed, errcode:${JSON.stringify(err)}.`); expect().assertFail(); @@ -194,15 +194,15 @@ describe('rdbStoreCloud', function () { } await rdbStore.setDistributedTables(['local'], undefined, config).then((err) => { - console.log(TAG + "set local to be distributed device table success"); - expect(true).assertTrue(); - done(); - console.log(TAG + "************* testRdbStoreCloud0005 end *************"); - }).catch((err) => { - console.log(TAG + `set local to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); - expect().assertFail(); - done() - }); + console.log(TAG + "set local to be distributed device table success"); + expect(true).assertTrue(); + done(); + console.log(TAG + "************* testRdbStoreCloud0005 end *************"); + }).catch((err) => { + console.log(TAG + `set local to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); + done() + }); } catch (err) { console.log(TAG + `set local to be distributed table failed 2, errcode:${JSON.stringify(err)}.`); expect().assertFail(); @@ -271,15 +271,15 @@ describe('rdbStoreCloud', function () { try { await rdbStore.setDistributedTables(['employee'], relationalStore.DistributedType.DISTRIBUTED_CLOUD, undefined).then((err) => { - console.log(TAG + "set employee to be distributed cloud table success"); - expect(true).assertTrue(); - done(); - console.log(TAG + "************* testRdbStoreCloud0008 end *************"); - }).catch((err) => { - console.log(TAG + `set employee to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); - expect().assertFail(); - done() - }); + console.log(TAG + "set employee to be distributed cloud table success"); + expect(true).assertTrue(); + done(); + console.log(TAG + "************* testRdbStoreCloud0008 end *************"); + }).catch((err) => { + console.log(TAG + `set employee to be distributed table failed 1, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); + done() + }); } catch (err) { console.log(TAG + `set employee to be distributed table failed 2, errcode:${JSON.stringify(err)}.`); expect().assertFail(); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js index 003d1af54f0119d935499e97794c33b7385cd71d..daf66477ba8ec20af1c71acdd8027e5b80edc4d0 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreCloudSync.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' @@ -427,7 +427,7 @@ describe('rdbStoreCloudSyncTest', function () { done(); } let predicates = new relationalStore.RdbPredicates("test") - predicates.in("id", ["id1","id2"]); + predicates.in("id", ["id1", "id2"]); try { await rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, predicates, Progress) } catch (err) { @@ -451,7 +451,7 @@ describe('rdbStoreCloudSyncTest', function () { console.log(TAG + `Progress:` + JSON.stringify(detail)); } let predicates = new relationalStore.RdbPredicates("test") - predicates.in("id", ["id1","id2"]); + predicates.in("id", ["id1", "id2"]); rdbStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_TIME_FIRST, predicates, Progress, () => { done(); expect(false).assertTrue() diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataChange.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataChange.test.js index 8af7561d3daf9584abe8a68ccb0245f0426fba56..912f4ce8dc79aff981a9aecc61031ac4632f3bba 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataChange.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataChange.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' @@ -347,7 +347,7 @@ describe('RdbStoreDataChangeTest', function () { it('testRdbStoreDataChange0007', 0, async function (done) { console.info(TAG + "************* testRdbStoreDataChange0007 start *************"); try { - rdbStore.on('', relationalStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL_DETAILS, (ChangeInfos) => {}) + rdbStore.on('', relationalStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL_DETAILS, (ChangeInfos) => { }) expect().assertFail(); } catch (err) { console.error(TAG + `register fail, code:${err.code}, message: ${err.message}`); @@ -375,7 +375,7 @@ describe('RdbStoreDataChangeTest', function () { it('testRdbStoreDataChange0008', 0, async function (done) { console.info(TAG + "************* testRdbStoreDataChange0008 start *************"); try { - rdbStore.off('', relationalStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL_DETAILS, (ChangeInfos) => {}) + rdbStore.off('', relationalStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL_DETAILS, (ChangeInfos) => { }) expect().assertFail(); } catch (err) { console.error(TAG + `register fail, code:${err.code}, message: ${err.message}`); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataShareJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataShareJsunit.test.js index 5b6c32356da2a22c7c411107eca58a0ab687c375..e36994b690c87a8b5487cdce2b2888c6f17d0f68 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataShareJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDataShareJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' import data_dataSharePredicates from '@ohos.data.dataSharePredicates' @@ -135,7 +135,7 @@ describe('rdbStoreDataSharePredicatesTest', function () { try { await rdbStore.update("test", valueBucket, predicates) expect(false).assertTrue() - } catch(e) { + } catch (e) { console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) expect("202").assertEqual(e.code) } @@ -173,7 +173,7 @@ describe('rdbStoreDataSharePredicatesTest', function () { rdbStore.update("test", valueBucket, predicates, async function (err, ret) { expect(false).assertTrue() }) - } catch(e) { + } catch (e) { console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) expect("202").assertEqual(e.code) } @@ -203,7 +203,7 @@ describe('rdbStoreDataSharePredicatesTest', function () { try { await rdbStore.query("test", predicates) expect(false).assertTrue() - } catch(e) { + } catch (e) { console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) expect("202").assertEqual(e.code) } @@ -232,10 +232,10 @@ describe('rdbStoreDataSharePredicatesTest', function () { try { rdbStore.query("test", predicates, ["ID", "NAME", "AGE", "SALARY", "blobType"], function (err, resultSet) { - expect(false).assertTrue() + expect(false).assertTrue() }) - } catch(e) { + } catch (e) { console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) expect("202").assertEqual(e.code) } @@ -264,7 +264,7 @@ describe('rdbStoreDataSharePredicatesTest', function () { try { await rdbStore.delete("test", predicates) expect(false).assertTrue() - } catch(e) { + } catch (e) { console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) expect("202").assertEqual(e.code) } @@ -294,7 +294,7 @@ describe('rdbStoreDataSharePredicatesTest', function () { rdbStore.delete("test", predicates, async function (err, ret) { expect(false).assertTrue() }) - } catch(e) { + } catch (e) { console.log("catch err: failed, err: code=" + e.code + " message=" + e.message) expect("202").assertEqual(e.code) } diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js index a8684cd21a2e490428b0e1b23bb794f05452b524..b40836f9da1451a980c338ba7ee3bff79fb53f4f 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreDistributedJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByCursor.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByCursor.test.js index a07a477d6782966e81aa335a8e80756fef4c2b16..7f28abc51880d6aac1691e3a1883c6b555ccc709 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByCursor.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByCursor.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' @@ -215,7 +215,7 @@ describe('rdbStoreQueryByCursorTest', function () { resultSet.close(); expect(true).assertEqual(resultSet.isClosed); }) - } catch(err) { + } catch (err) { console.log(TAG + `query cursor fail, errcode:${JSON.stringify(err)}.`); done(); expect().assertFail(); @@ -248,7 +248,7 @@ describe('rdbStoreQueryByCursorTest', function () { resultSet.close(); expect(true).assertEqual(resultSet.isClosed); }) - } catch(err) { + } catch (err) { console.log(TAG + `query cursor fail, errcode:${JSON.stringify(err)}.`); done(); expect().assertFail(); @@ -341,7 +341,7 @@ describe('rdbStoreQueryByCursorTest', function () { rdbStore.cleanDirtyData("query_tb", cursor, (err) => { if (err) { console.error(TAG, "clean dirty data failed, err: code=" + err.code + " message=" + err.message); - expect(false).assertTrue() ; + expect(false).assertTrue(); } done(); }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStep.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStep.test.js index e9ada2e214badb7fd93cb81d40273bf934975192..0b051d4b8396ff0b5f2203369df894e676fdbf82 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStep.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStep.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' @@ -90,7 +90,7 @@ describe('rdbStoreQueryByStepTest', function () { }) async function InsertTest() { - console.info(TAG, "insertTest data start"); + console.info(TAG, "insertTest data start"); let u8 = new Uint8Array([1, 2, 3]); const assets1 = [asset1, asset2]; let valuesBucket1 = { @@ -115,7 +115,7 @@ describe('rdbStoreQueryByStepTest', function () { "salary": 5503.3, } await rdbStore.insert("test", valuesBucket3); - console.info(TAG, "insertTest data end"); + console.info(TAG, "insertTest data end"); } console.info(TAG + "*************Unit Test Begin*************"); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStepSync.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStepSync.test.js index 45077e6378d483be8f20485f9ac4a4cb702ecf70..e33dbdbde62e27bf044f26189ae3635dfb213ce6 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStepSync.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreQueryByStepSync.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' @@ -90,7 +90,7 @@ describe('rdbStoreQueryByStepSyncTest', function () { }) async function InsertTest() { - console.info(TAG, "insertTest data start"); + console.info(TAG, "insertTest data start"); let u8 = new Uint8Array([1, 2, 3]); const assets1 = [asset1, asset2]; let valuesBucket1 = { @@ -115,7 +115,7 @@ describe('rdbStoreQueryByStepSyncTest', function () { "salary": 5503.3, } await rdbStore.insert("test", valuesBucket3); - console.info(TAG, "insertTest data end"); + console.info(TAG, "insertTest data end"); } console.info(TAG + "*************Unit Test Begin*************"); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreReadOnlyJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreReadOnlyJsunit.test.js index 71debfd8e437ea883d312aa693d369bf71eb3477..49f31906fb8dbfe645839bd8c24de4cbb05f58e1 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreReadOnlyJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreReadOnlyJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from '@ohos/hypium'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; import relationalStore from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetRow.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetRow.test.js index ddb8e74a4f169bd014203e59db6b7601649cf89e..0f27c785829d2b9b9106f1f972b11904330fbf87 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetRow.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetRow.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetValue.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetValue.test.js index 9a5bcf6c66fb06ddbc69c6f97a9c68ef049183d0..5f56638ec5464244465feb6c372045e91047215d 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetValue.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetValue.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js index e9dea909705e5f465045f0896a75d477d7e9d639..45fd2aaa4124da45048faa21f8a652a16140b14f 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetSyncJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetSyncJsunit.test.js index 92cd069acb4c57f79f9007eccafef9819e10b8a7..33e202c77ac7cf7c1e9af7c133c6389d24b8e1c7 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetSyncJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetSyncJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreStatisticsJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreStatisticsJsunit.test.js index 6b42a032b2b0e78b7b57adf149ee785c9ebecd41..79318b0adeb3eafd149246e86232be209bba2f79 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreStatisticsJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreStatisticsJsunit.test.js @@ -567,7 +567,7 @@ describe('RdbStoreStatisticsTest', function () { }).catch((err) => { console.error(`close failed, code is ${err.code},message is ${err.message}`); }) - + try { rdbStore.on('statistics', (SqlExeInfo) => { }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreTransaction.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreTransaction.test.js index 96c945c387fbf3171c850dee443670d13142b263..269740ff79a21405a3430b6474e8f42844305bfb 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreTransaction.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreTransaction.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -375,40 +375,40 @@ describe('rdbStoreTransactionTest', function () { * 3.QuerySql */ it('testExecute0002', 0, async function (done) { - console.log(TAG + "************* testExecute0002 start *************"); - var transaction = await rdbStore.createTransaction() - var u8 = new Uint8Array([1, 2, 3]) - try { - var valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - for (let i = 0; i < 3; i++) { - valueBucket.age = valueBucket.age + 1; - var row = await transaction.insert("test", valueBucket) - console.log(TAG + "testExecute0002 insert row " + row) - } - await transaction.execute("DELETE FROM test WHERE age = ? OR age = ?", [21, 20]) - - let resultSet = await transaction.querySql("select * from test") - console.log(TAG + "testExecute0002 transaction.querySql result count " + resultSet.rowCount) - expect(1).assertEqual(resultSet.rowCount) - expect(true).assertEqual(resultSet.goToFirstRow()) - const age = resultSet.getLong(resultSet.getColumnIndex("age")) - expect(19).assertEqual(age); - await resultSet.close() - await transaction.commit() - } catch (e) { - await transaction.rollback() - console.log(TAG + e); - expect(null).assertFail() - console.log(TAG + "testExecute0002 failed"); + console.log(TAG + "************* testExecute0002 start *************"); + var transaction = await rdbStore.createTransaction() + var u8 = new Uint8Array([1, 2, 3]) + try { + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + for (let i = 0; i < 3; i++) { + valueBucket.age = valueBucket.age + 1; + var row = await transaction.insert("test", valueBucket) + console.log(TAG + "testExecute0002 insert row " + row) } - done(); - console.log(TAG + "************* testExecute0002 end *************"); + await transaction.execute("DELETE FROM test WHERE age = ? OR age = ?", [21, 20]) + + let resultSet = await transaction.querySql("select * from test") + console.log(TAG + "testExecute0002 transaction.querySql result count " + resultSet.rowCount) + expect(1).assertEqual(resultSet.rowCount) + expect(true).assertEqual(resultSet.goToFirstRow()) + const age = resultSet.getLong(resultSet.getColumnIndex("age")) + expect(19).assertEqual(age); + await resultSet.close() + await transaction.commit() + } catch (e) { + await transaction.rollback() + console.log(TAG + e); + expect(null).assertFail() + console.log(TAG + "testExecute0002 failed"); } + done(); + console.log(TAG + "************* testExecute0002 end *************"); + } ) /** diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreValueType.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreValueType.test.js index 59a3b3a2dce1ad3fe97a853e9b41bc20b95ff181..15f323542808634eca45d9d84de3cf96389ef7b3 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreValueType.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreValueType.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore' import featureAbility from '@ohos.ability.featureAbility' @@ -64,8 +64,8 @@ describe('ActsRdbStoreValueTypeTest', function () { it('testValueType0001', 0, async function (done) { console.log(TAG + "************* testValueType0001 start *************"); let bucket = { - "value1":BigInt(158), - "value2":BigInt(-158) + "value1": BigInt(158), + "value2": BigInt(-158) }; try { console.log(TAG + "insert(bigint_table," + bucket + ")"); @@ -103,8 +103,8 @@ describe('ActsRdbStoreValueTypeTest', function () { it('testValueType0002', 0, async function (done) { console.log(TAG + "************* testValueType0002 start *************"); let bucket = { - "value1":BigInt("15822401018187971961171"), - "value2":BigInt("-15822401018187971961171") + "value1": BigInt("15822401018187971961171"), + "value2": BigInt("-15822401018187971961171") }; try { console.log(TAG + "insert(bigint_table," + bucket + ")"); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseJsunit.test.js index e032bfe55ea03f35535816834d90f8e6ae30905d..af3f4e00fd391d5c6308383f6663f6ea257c9a55 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -113,7 +113,7 @@ describe('rdbStoreAfterCloseTest', function () { await relationalStore.deleteRdbStore(context, STORE_NAME); console.log(TAG + "************* testRdbAfterClose0002 end *************"); }) - + /** * @tc.number testRdbAfterClose0003 * @tc.name RDB Close test @@ -223,10 +223,10 @@ describe('rdbStoreAfterCloseTest', function () { } await relationalStore.deleteRdbStore(context, STORE_NAME); - done(); + done(); console.log(TAG + "************* testRdbAfterClose0006 end *************"); }) - + /** * @tc.number testRdbAfterClose0007 diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseSyncJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseSyncJsunit.test.js index 8578c3d409c38be96f8093ff0dc0e16e6828b1e6..4254601be162263d996db3f489667d79a6019783 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseSyncJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreAfterCloseSyncJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -138,7 +138,7 @@ describe('rdbStoreAfterCloseSyncTest', function () { console.log(TAG + "catch err: failed, err: code=" + err.code + " message=" + err.message); expect("14800014").assertEqual(err.code) } - + await relationalStore.deleteRdbStore(context, STORE_NAME); console.log(TAG + "************* testSyncRdbAfterClose0003 end *************"); }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js index 4869700cc574dffd21b49c2bcc835b262a85b02d..ea5fcaa53824b096b0d14556abe727b0a250e715 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' import fileio from '@ohos.file.fs' @@ -97,201 +97,201 @@ async function RestoreTest(restoreName) { } describe('rdbStoreBackupRestoreWithFAContextTest', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll') - }) - - beforeEach(async function () { - console.info(TAG + 'beforeEach') - rdbStore = await CreatRdbStore(STORE_CONFIG) - }) - - afterEach(async function () { - console.info(TAG + 'afterEach') - rdbStore = null - await data_relationalStore.deleteRdbStore(context, STORE_CONFIG.name) - await data_relationalStore.deleteRdbStore(context, DATABASE_BACKUP_NAME) - }) - - afterAll(async function () { - console.info(TAG + 'afterAll') - }) - - console.log(TAG + "*************Unit Test Begin*************") - - /** - * @tc.name RDB Backup Restore test - * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0010 - * @tc.desc RDB backup and restore function test - */ - it('RdbBackupRestoreTest_0010', 0, async function (done) { - await console.log(TAG + "************* RdbBackupRestoreTest_0010 start *************") - - try { - await rdbStore.backup(DATABASE_BACKUP_NAME) - // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + DATABASE_BACKUP_NAME)) - // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) - - await rdbStore.restore(DATABASE_BACKUP_NAME) - // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) - } catch (err) { - expect().assertFail() - } - - // RDB after restored, data query test - let predicates = new data_relationalStore.RdbPredicates("test") - predicates.equalTo("name", "zhangsan") - let resultSet = await rdbStore.query(predicates) - try { - console.log(TAG + "After restore resultSet query done") - expect(true).assertEqual(resultSet.goToFirstRow()) - const id = resultSet.getLong(resultSet.getColumnIndex("id")) - const name = resultSet.getString(resultSet.getColumnIndex("name")) - const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) - expect(1).assertEqual(id) - expect("zhangsan").assertEqual(name) - expect(1).assertEqual(blobType[0]) - } catch (err) { - expect(false).assertTrue() - } - resultSet.close() - resultSet = null - done() - await console.log(TAG + "************* RdbBackupRestoreTest_0010 end *************") - }) - - /** - * @tc.name RDB Backup test - * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0020 - * @tc.desc RDB backup function test - */ - it('RdbBackupRestoreTest_0020', 0, async function (done) { - await console.log(TAG + "************* RdbBackupRestoreTest_0020 start *************") - // RDB backup function test, backup file name empty - BackupTest("") - - // RDB backup function test, backup file name already exists - BackupTest(STORE_CONFIG.name) - - done() - await console.log(TAG + "************* RdbBackupRestoreTest_0020 end *************") - }) - - /** - * @tc.name RDB BackupRestore test - * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0030 - * @tc.desc RDB restore function test - */ - it('RdbBackupRestoreTest_0030', 0, async function (done) { - await console.log(TAG + "************* RdbBackupRestoreTest_0030 start *************") + beforeAll(async function () { + console.info(TAG + 'beforeAll') + }) + + beforeEach(async function () { + console.info(TAG + 'beforeEach') + rdbStore = await CreatRdbStore(STORE_CONFIG) + }) + + afterEach(async function () { + console.info(TAG + 'afterEach') + rdbStore = null + await data_relationalStore.deleteRdbStore(context, STORE_CONFIG.name) + await data_relationalStore.deleteRdbStore(context, DATABASE_BACKUP_NAME) + }) + + afterAll(async function () { + console.info(TAG + 'afterAll') + }) + + console.log(TAG + "*************Unit Test Begin*************") + + /** + * @tc.name RDB Backup Restore test + * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0010 + * @tc.desc RDB backup and restore function test + */ + it('RdbBackupRestoreTest_0010', 0, async function (done) { + await console.log(TAG + "************* RdbBackupRestoreTest_0010 start *************") + + try { await rdbStore.backup(DATABASE_BACKUP_NAME) + // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + DATABASE_BACKUP_NAME)) + // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) - // RDB restore function test, backup file name empty - RestoreTest("") + await rdbStore.restore(DATABASE_BACKUP_NAME) + // expect(true).assertEqual(fileio.accessSync(DATABASE_DIR + STORE_CONFIG.name)) + } catch (err) { + expect().assertFail() + } - // RDB restore function test, backup file is specified to database name - RestoreTest(STORE_CONFIG.name) + // RDB after restored, data query test + let predicates = new data_relationalStore.RdbPredicates("test") + predicates.equalTo("name", "zhangsan") + let resultSet = await rdbStore.query(predicates) + try { + console.log(TAG + "After restore resultSet query done") + expect(true).assertEqual(resultSet.goToFirstRow()) + const id = resultSet.getLong(resultSet.getColumnIndex("id")) + const name = resultSet.getString(resultSet.getColumnIndex("name")) + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) + expect(1).assertEqual(id) + expect("zhangsan").assertEqual(name) + expect(1).assertEqual(blobType[0]) + } catch (err) { + expect(false).assertTrue() + } + resultSet.close() + resultSet = null + done() + await console.log(TAG + "************* RdbBackupRestoreTest_0010 end *************") + }) + + /** + * @tc.name RDB Backup test + * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0020 + * @tc.desc RDB backup function test + */ + it('RdbBackupRestoreTest_0020', 0, async function (done) { + await console.log(TAG + "************* RdbBackupRestoreTest_0020 start *************") + // RDB backup function test, backup file name empty + BackupTest("") + + // RDB backup function test, backup file name already exists + BackupTest(STORE_CONFIG.name) + + done() + await console.log(TAG + "************* RdbBackupRestoreTest_0020 end *************") + }) + + /** + * @tc.name RDB BackupRestore test + * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0030 + * @tc.desc RDB restore function test + */ + it('RdbBackupRestoreTest_0030', 0, async function (done) { + await console.log(TAG + "************* RdbBackupRestoreTest_0030 start *************") + await rdbStore.backup(DATABASE_BACKUP_NAME) + + // RDB restore function test, backup file name empty + RestoreTest("") + + // RDB restore function test, backup file is specified to database name + RestoreTest(STORE_CONFIG.name) + + done() + await console.log(TAG + "************* RdbBackupRestoreTest_0030 end *************") + }) + + /** + * @tc.name RDB BackupRestore test + * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0040 + * @tc.desc RDB restore function test + */ + it('RdbBackupRestoreTest_0040', 0, async function (done) { + await console.log(TAG + "************* RdbBackupRestoreTest_0040 start *************") + let dbName = "notExistName.db" + + // RDB restore function test, backup file does not exists + try { + expect(false).assertEqual(fileio.accessSync(DATABASE_DIR + dbName)) + } catch (errCode) { + expect(13900002).assertEqual(errCode.code) + } + RestoreTest(dbName) + done() + await console.log(TAG + "************* RdbBackupRestoreTest_0040 end *************") + }) + + /** + * @tc.name RDB BackupRestore test + * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0050 + * @tc.desc RDB backup function test + */ + it('RdbBackupRestoreBackupTest_0050', 0, async function (done) { + console.log(TAG + "************* RdbBackupRestoreBackupTest_0050 start *************") + + const STORE_NAME = "AfterCloseTest.db"; + const rdbStore = await data_relationalStore.getRdbStore( + context, + { + name: STORE_NAME, + securityLevel: data_relationalStore.SecurityLevel.S1 + } + ) + try { + await rdbStore.close(); + console.info(`${TAG} close succeeded`); + } catch (err) { + expect(null).assertFail(); + console.error(`${TAG} close failed, code is ${err.code},message is ${err.message}`); + } - done() - await console.log(TAG + "************* RdbBackupRestoreTest_0030 end *************") - }) + try { + let dbName = "QueryTest_bak.db" + await rdbStore.backup(dbName) + } catch (err) { + console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + expect("14800014").assertEqual(err.code) + } - /** - * @tc.name RDB BackupRestore test - * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0040 - * @tc.desc RDB restore function test - */ - it('RdbBackupRestoreTest_0040', 0, async function (done) { - await console.log(TAG + "************* RdbBackupRestoreTest_0040 start *************") - let dbName = "notExistName.db" - - // RDB restore function test, backup file does not exists - try { - expect(false).assertEqual(fileio.accessSync(DATABASE_DIR + dbName)) - } catch (errCode) { - expect(13900002).assertEqual(errCode.code) + await data_relationalStore.deleteRdbStore(context, STORE_NAME); + done(); + console.log(TAG + "************* RdbBackupRestoreBackupTest_0050 end *************") + }) + /** + * @tc.name RDB BackupRestore test + * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0060 + * @tc.desc RDB restore function test + */ + it('RdbBackupRestoreBackupTest_0060', 0, async function (done) { + console.log(TAG + "************* RdbBackupRestoreBackupTest_0060 start *************") + + const STORE_NAME = "AfterCloseTest.db"; + const rdbStore = await data_relationalStore.getRdbStore( + context, + { + name: STORE_NAME, + securityLevel: data_relationalStore.SecurityLevel.S1 } - RestoreTest(dbName) - done() - await console.log(TAG + "************* RdbBackupRestoreTest_0040 end *************") - }) + ) - /** - * @tc.name RDB BackupRestore test - * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0050 - * @tc.desc RDB backup function test - */ - it('RdbBackupRestoreBackupTest_0050', 0, async function (done) { - console.log(TAG + "************* RdbBackupRestoreBackupTest_0050 start *************") - - const STORE_NAME = "AfterCloseTest.db"; - const rdbStore = await data_relationalStore.getRdbStore( - context, - { - name: STORE_NAME, - securityLevel: data_relationalStore.SecurityLevel.S1 - } - ) - try { - await rdbStore.close(); - console.info(`${TAG} close succeeded`); - } catch (err) { - expect(null).assertFail(); - console.error(`${TAG} close failed, code is ${err.code},message is ${err.message}`); - } + let dbName = "notExistName.db" + BackupTest(dbName); - try { - let dbName = "QueryTest_bak.db" - await rdbStore.backup(dbName) - } catch (err) { - console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) - expect("14800014").assertEqual(err.code) - } - - await data_relationalStore.deleteRdbStore(context, STORE_NAME); - done(); - console.log(TAG + "************* RdbBackupRestoreBackupTest_0050 end *************") - }) - /** - * @tc.name RDB BackupRestore test - * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0060 - * @tc.desc RDB restore function test - */ - it('RdbBackupRestoreBackupTest_0060', 0, async function (done) { - console.log(TAG + "************* RdbBackupRestoreBackupTest_0060 start *************") - - const STORE_NAME = "AfterCloseTest.db"; - const rdbStore = await data_relationalStore.getRdbStore( - context, - { - name: STORE_NAME, - securityLevel: data_relationalStore.SecurityLevel.S1 - } - ) - - let dbName = "notExistName.db" - BackupTest(dbName); - - try { - await rdbStore.close(); - console.info(`${TAG} close succeeded`); - } catch (err) { - expect(null).assertFail(); - console.error(`${TAG} close failed, code is ${err.code},message is ${err.message}`); - } + try { + await rdbStore.close(); + console.info(`${TAG} close succeeded`); + } catch (err) { + expect(null).assertFail(); + console.error(`${TAG} close failed, code is ${err.code},message is ${err.message}`); + } - try { - await rdbStore.restore(dbName) - } catch (err) { - console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) - expect("14800014").assertEqual(err.code) - } + try { + await rdbStore.restore(dbName) + } catch (err) { + console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + expect("14800014").assertEqual(err.code) + } - await data_relationalStore.deleteRdbStore(context, STORE_NAME); - done(); - console.log(TAG + "************* RdbBackupRestoreBackupTest_0060 end *************") - }) + await data_relationalStore.deleteRdbStore(context, STORE_NAME); + done(); + console.log(TAG + "************* RdbBackupRestoreBackupTest_0060 end *************") + }) - console.log(TAG + "*************Unit Test End*************") - } + console.log(TAG + "*************Unit Test End*************") +} ) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js index 1b63ab1dbb1d18f7bc8f7b1918c036a91813bb17..79e3d28459ca9b146fa5197d768ed82a4191c25f 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js @@ -13,14 +13,14 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility'; const TAG = "[RELATIONAL_STORE_CALLBACK_TEST]" const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + - "id INTEGER PRIMARY KEY AUTOINCREMENT, " + - "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"; + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"; const STORE_CONFIG = { name: "RDBCallbackTest.db", @@ -58,7 +58,7 @@ describe('rdbStoreCallBackTest', async function () { * 6.Execute deleteRdbStore */ it('testRdbStoreCallBackTest0001', 0, async function (done) { - console.info(TAG, "************* testRdbStoreCallBackTest0001 start *************"); + console.info(TAG, "************* testRdbStoreCallBackTest0001 start *************"); try { await data_relationalStore.getRdbStore(context, STORE_CONFIG, async (err, rdbStore) => { if (err) { @@ -100,7 +100,7 @@ describe('rdbStoreCallBackTest', async function () { expect(false).assertTrue() } done() - console.info(TAG, "************* testRdbStoreCallBackTest0001 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0001 end *************") }); resultSet.close() rdbStore = null @@ -118,10 +118,10 @@ describe('rdbStoreCallBackTest', async function () { * 2.Execute getRdbStore */ it('testRdbStoreCallBackTest0002', 0, function (done) { - console.info(TAG, "************* testRdbStoreCallBackTest0002 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0002 start *************") try { data_relationalStore.getRdbStore(context, - {dbname: "RDBCallbackTest.db", securityLevel: data_relationalStore.SecurityLevel.S1,}, + { dbname: "RDBCallbackTest.db", securityLevel: data_relationalStore.SecurityLevel.S1, }, (err, rdbStore) => { if (err) { console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) @@ -134,7 +134,7 @@ describe('rdbStoreCallBackTest', async function () { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() - console.info(TAG, "************* testRdbStoreCallBackTest0002 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0002 end *************") } }) @@ -145,24 +145,24 @@ describe('rdbStoreCallBackTest', async function () { * 2.Execute getRdbStore */ it('testRdbStoreCallBackTest0003', 0, function (done) { - console.info(TAG, "************* testRdbStoreCallBackTest0003 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0003 start *************") try { data_relationalStore.getRdbStore(null, { name: "RDBCallbackTest.db", securityLevel: data_relationalStore.SecurityLevel.S1 }, (err, rdbStore) => { if (err) { - console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } - console.info(TAG, "Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") expect(false).assertTrue() }) } catch (err) { - console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() - console.info(TAG, "************* testRdbStoreCallBackTest0003 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0003 end *************") } }) @@ -173,7 +173,7 @@ describe('rdbStoreCallBackTest', async function () { * 2.Execute getRdbStore */ it('testRdbStoreCallBackTest0004', 0, function (done) { - console.info(TAG, "************* testRdbStoreCallBackTest0004 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0004 start *************") try { data_relationalStore.getRdbStore(context, STORE_CONFIG, (err, rdbStore) => { if (err) { @@ -182,7 +182,7 @@ describe('rdbStoreCallBackTest', async function () { } rdbStore = null done() - console.info(TAG, "************* testRdbStoreCallBackTest0004 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0004 end *************") }) } catch (err) { console.error("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) @@ -198,7 +198,7 @@ describe('rdbStoreCallBackTest', async function () { * 3.Execute deleteRdbStore */ it('testRdbStoreCallBackTest0005', 0, async function (done) { - console.info(TAG, "************* testRdbStoreCallBackTest0005 start *************"); + console.info(TAG, "************* testRdbStoreCallBackTest0005 start *************"); data_relationalStore.getRdbStore(context, STORE_CONFIG).then((rdbStore) => { try { rdbStore = null @@ -214,7 +214,7 @@ describe('rdbStoreCallBackTest', async function () { console.info(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() - console.info(TAG, "************* testRdbStoreCallBackTest0005 end *************"); + console.info(TAG, "************* testRdbStoreCallBackTest0005 end *************"); } }).catch((err) => { console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) @@ -230,7 +230,7 @@ describe('rdbStoreCallBackTest', async function () { * 3.Execute deleteRdbStore */ it('testRdbStoreCallBackTest0006', 0, async function (done) { - console.info(TAG, "************* testRdbStoreCallBackTest0006 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0006 start *************") data_relationalStore.getRdbStore(context, STORE_CONFIG).then((rdbStore) => { try { rdbStore = null @@ -241,7 +241,7 @@ describe('rdbStoreCallBackTest', async function () { } console.info(TAG, "Delete RdbStore successfully.") done() - console.info(TAG, "************* testRdbStoreCallBackTest0006 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0006 end *************") }); } catch (err) { console.error(TAG, "Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) @@ -253,5 +253,5 @@ describe('rdbStoreCallBackTest', async function () { }) }) - console.info(TAG, "*************Unit Test End*************"); + console.info(TAG, "*************Unit Test End*************"); }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js index 6f44b562967d88606575e047aeb9b2eae0e2fb92..f816b62d912c6d90d22deedcb0341b1a6d712860 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCreateDeleteWithFAContextJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility'; diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCustomDir.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCustomDir.test.js index 35dd86a29745b3c834417b5ef5881cabba25f74d..58dc0aaf366ea664d6fc1f33db541d2dc6ce5127 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCustomDir.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCustomDir.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility'; @@ -108,7 +108,7 @@ describe('rdbStoreCustomTest', function () { }) async function InsertTest() { - console.info(TAG, "insertTest data start"); + console.info(TAG, "insertTest data start"); let u8 = new Uint8Array([1, 2, 3]); const assets1 = [asset1, asset2]; let valuesBucket1 = { @@ -128,11 +128,11 @@ describe('rdbStoreCustomTest', function () { "salary": 1503.3, } await store.insert("test", valuesBucket2); - console.info(TAG, "insertTest data end"); + console.info(TAG, "insertTest data end"); } async function UpdateTest() { - console.info(TAG, "updateTest data start"); + console.info(TAG, "updateTest data start"); let u8 = new Uint8Array([1, 2, 3]); const assets1 = [asset2]; let valuesBucket = { @@ -147,10 +147,10 @@ describe('rdbStoreCustomTest', function () { let predicates = new data_relationalStore.RdbPredicates("test") predicates.equalTo("id", "1") await store.update(valuesBucket, predicates); - console.info(TAG, "updateTest data end"); + console.info(TAG, "updateTest data end"); } - console.info(TAG, "*************Unit Test Begin*************"); + console.info(TAG, "*************Unit Test Begin*************"); /** * @tc.number testRdbStoreCustomDirTest0001 @@ -167,7 +167,7 @@ describe('rdbStoreCustomTest', function () { store = await data_relationalStore.getRdbStore(context, STORE_CONFIG3); expect(store != null).assertTrue(); done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -191,7 +191,7 @@ describe('rdbStoreCustomTest', function () { let store1 = await data_relationalStore.getRdbStore(context, STORE_CONFIG1); expect(store1 != null).assertTrue(); store1 = null; - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -200,7 +200,7 @@ describe('rdbStoreCustomTest', function () { try { await data_relationalStore.deleteRdbStore(context, STORE_CONFIG1); done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -226,7 +226,7 @@ describe('rdbStoreCustomTest', function () { let store1 = await data_relationalStore.getRdbStore(context, STORE_CONFIG1); expect(store1 != null).assertTrue(); store1 = null; - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore1 failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -237,7 +237,7 @@ describe('rdbStoreCustomTest', function () { expect(store2 != null).assertTrue(); store2 = null; done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore2 failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -262,7 +262,7 @@ describe('rdbStoreCustomTest', function () { store = await data_relationalStore.getRdbStore(context, STORE_CONFIG1); expect(store != null).assertTrue(); await store.executeSql(CREATE_TABLE_TEST,) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore2 failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -270,7 +270,7 @@ describe('rdbStoreCustomTest', function () { try { await InsertTest(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Insert data failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -281,7 +281,7 @@ describe('rdbStoreCustomTest', function () { let resultSet = await store.query(predicates); expect(2).assertEqual(resultSet.rowCount); done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: query data failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -307,7 +307,7 @@ describe('rdbStoreCustomTest', function () { store = await data_relationalStore.getRdbStore(context, STORE_CONFIG1); expect(store != null).assertTrue(); await store.executeSql(CREATE_TABLE_TEST,) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -316,7 +316,7 @@ describe('rdbStoreCustomTest', function () { try { await InsertTest(); await UpdateTest(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Insert and update data failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -329,7 +329,7 @@ describe('rdbStoreCustomTest', function () { expect(true).assertEqual(resultSet.goToFirstRow()); expect("tim").assertEqual(resultSet.getString(resultSet.getColumnIndex("name"))); done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: query data failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -357,7 +357,7 @@ describe('rdbStoreCustomTest', function () { store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); expect(store != null).assertTrue(); done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -386,7 +386,7 @@ describe('rdbStoreCustomTest', function () { store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); expect(store != null).assertTrue(); done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); @@ -414,7 +414,7 @@ describe('rdbStoreCustomTest', function () { store = await data_relationalStore.getRdbStore(context, STORE_CONFIG); expect(store != null).assertTrue(); done(); - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message); expect(false).assertTrue(); done(); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteJsunit.test.js index 94562e0b52f6cc8a975e54c4eab659fffaca5945..68ed97ab09adaa088ef4a5f99c6f57a4fa20c2f2 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -374,7 +374,7 @@ describe('rdbStoreDeleteTest', function () { */ it('testRdbStoreDelete0008', 0, async function (done) { console.log(TAG + "************* testRdbStoreDelete0008 start *************"); - + const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT UNIQUE, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_NAME = "AfterCloseTest.db"; @@ -411,7 +411,7 @@ describe('rdbStoreDeleteTest', function () { console.log(TAG + "catch err: failed, err: code=" + err.code + " message=" + err.message); expect("14800014").assertEqual(err.code); } - + await data_relationalStore.deleteRdbStore(context, STORE_NAME); done(); console.log(TAG + "************* testRdbStoreDelete0008 end *************"); @@ -426,7 +426,7 @@ describe('rdbStoreDeleteTest', function () { */ it('testRdbStoreDelete0009', 0, async function (done) { console.log(TAG + "************* testRdbStoreDelete0009 start *************"); - + const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT UNIQUE, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_NAME = "AfterCloseTest.db"; @@ -438,7 +438,7 @@ describe('rdbStoreDeleteTest', function () { } ) await rdbStore.executeSql(CREATE_TABLE_TEST); - + var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "zhangsan", @@ -457,12 +457,12 @@ describe('rdbStoreDeleteTest', function () { let predicates = new data_relationalStore.RdbPredicates("test"); predicates.equalTo("age", 18); try { - rdbStore.delete(predicates, () => {}); + rdbStore.delete(predicates, () => { }); } catch (err) { console.log(TAG + "catch err: failed, err: code=" + err.code + " message=" + err.message); expect("14800014").assertEqual(err.code); } - + await data_relationalStore.deleteRdbStore(context, STORE_NAME); done(); console.log(TAG + "************* testRdbStoreDelete0009 end *************"); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteSyncJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteSyncJsunit.test.js index 18f3d2db90c38c173332152413d1a2735e938ba9..fb726ac4223f4d8e66354fae59d7026dd0424da4 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteSyncJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreDeleteSyncJsunit.test.js @@ -387,7 +387,7 @@ describe('rdbStoreDeleteSyncTest', function () { console.log(TAG + "catch err: failed, err: code=" + err.code + " message=" + err.message); expect("14800014").assertEqual(err.code); } - + await data_relationalStore.deleteRdbStore(context, STORE_NAME); done(); console.log(TAG + "************* testSyncRdbStoreDelete0008 end *************"); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js index d88fbb025c0dfffb2027293f3affeb30953759a3..72519ca8cfa1f7dfb2d69b48062610bf884f1fbe 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreEncryptionJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' import factory from '@ohos.data.distributedKVStore' @@ -246,11 +246,11 @@ describe('rdbEncryptTest', function () { context = ability_featureAbility.getContext(); await CreateRdbStore(context, STORE_CONFIG_ENCRYPT); try { - let rdbStore = await CreateRdbStore(context, STORE_CONFIG_WRONG); - expect(rdbStore !== null).assertTrue(); + let rdbStore = await CreateRdbStore(context, STORE_CONFIG_WRONG); + expect(rdbStore !== null).assertTrue(); } catch (err) { - console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); - expect().assertFail(); + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); } done(); console.log(TAG + "************* RdbEncryptTest_0040 end *************"); @@ -269,11 +269,11 @@ describe('rdbEncryptTest', function () { context = ability_featureAbility.getContext(); await CreateRdbStore(context, STORE_CONFIG_WRONG); try { - let rdbStore = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT); - expect(rdbStore !== null).assertTrue(); + let rdbStore = await CreateRdbStore(context, STORE_CONFIG_ENCRYPT); + expect(rdbStore !== null).assertTrue(); } catch (err) { - console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); - expect().assertFail(); + console.log(TAG + `failed, errcode:${JSON.stringify(err)}.`); + expect().assertFail(); } done(); console.log(TAG + "************* RdbEncryptTest_0041 end *************"); @@ -430,7 +430,7 @@ describe('rdbEncryptTest', function () { * @tc.number SUB_DDM_RDB_JS_RdbDecryptTest_0030 * @tc.desc RDB decrypt function invalid key config test */ - it('RdbDecryptTest_0030', 0, async function () { + it('RdbDecryptTest_0030', 0, async function () { console.info(TAG + "************* RdbDecryptTest_0030 start *************") let invalid_key_config = { name: "nondefault.db", @@ -459,7 +459,7 @@ describe('rdbEncryptTest', function () { * @tc.number SUB_DDM_RDB_JS_RdbDecryptTest_0040 * @tc.desc RDB decrypt function invalid iteration config test */ - it('RdbDecryptTest_0040', 0, async function () { + it('RdbDecryptTest_0040', 0, async function () { console.info(TAG + "************* RdbDecryptTest_0040 start *************") let invalid_iter_config = { name: "nondefault.db", @@ -611,7 +611,7 @@ describe('rdbEncryptTest', function () { resultSet.goToFirstRow() const x = resultSet.getLong(resultSet.getColumnIndex("x")) const y = resultSet.getLong(resultSet.getColumnIndex("y")) - valueBucket = {"x" : x, "y" : y} + valueBucket = { "x": x, "y": y } resultSet.close() } catch (err) { console.error(`Read data failed, error code: ${err.code}, err message: ${err.message}`); @@ -633,7 +633,7 @@ describe('rdbEncryptTest', function () { console.error(`Insert and check data, error code: ${err.code}, err message: ${err.message}`); expect().assertFail() } - + await store.close() console.log(TAG + "************* RdbDecryptTest_0070 end *************") }) @@ -734,14 +734,62 @@ describe('rdbEncryptTest', function () { console.log(TAG + "************* RdbDecryptTest_0090 end *************") }) - /** - * @tc.number testEncryptRdbAndKv0002 - * @tc.name Normal test case of using encrypt kv, then using rdb attach interface - * @tc.desc 1.Get encrypt kv db - * 2.Get encrypt rdb1 - * 3.rdb1.backup(rdb2) - * 4.rdb1.restore(rdb2) - */ + /** + * @tc.number testEncryptRdbAndKv0001 + * @tc.name Normal test case of using encrypt kv, then using rdb attach interface + * @tc.desc 1.Get encrypt kv db + * 2.Get encrypt rdb1 + * 3.Get encrypt rdb2 + * 4.rdb2.attach rdb1 + */ + it('testEncryptRdbAndKv0001', 0, async () => { + console.log(TAG + "************* testEncryptRdbAndKv0001 start *************"); + let kvConfig = { + bundleName: TEST_BUNDLE_NAME, + context: context + } + let options = { + createIfMissing: true, + encrypt: true, + backup: false, + autoSync: false, + kvStoreType: factory.KVStoreType.SINGLE_VERSION, + securityLevel: factory.SecurityLevel.S2, + } + let rdbConfig = { + name: "RdbTest.db", + securityLevel: data_relationalStore.SecurityLevel.S1, + encrypt: true, + } + let kvManager = factory.createKVManager(kvConfig); + try { + let kvDb = await kvManager.getKVStore('kvDb', options) + rdbConfig.name = "RdbTest1.db" + let rdbStore1 = await data_relationalStore.getRdbStore(context, rdbConfig); + rdbConfig.name = "RdbTest2.db" + let rdbStore2 = await data_relationalStore.getRdbStore(context, rdbConfig); + rdbStore2.close(); + await rdbStore1.attach(context, rdbConfig, "alias"); + expect(true).assertTrue(); + } catch (e) { + console.log(TAG + e); + expect(null).assertFail(); + console.log(TAG + "testEncryptRdbAndKv0001 failed"); + } + await kvManager.closeKVStore(TEST_BUNDLE_NAME, 'kvDb'); + await data_relationalStore.deleteRdbStore(context, "RdbTest1.db"); + await data_relationalStore.deleteRdbStore(context, "RdbTest2.db"); + console.log(TAG + "************* testEncryptRdbAndKv0001 end *************"); + }) + + /** + * @tc.number testEncryptRdbAndKv0002 + * @tc.name Normal test case of using encrypt kv, then using rdb attach interface + * @tc.desc 1.Get encrypt kv db + * 2.Get encrypt rdb1 + * 3.rdb1.backup(rdb2) + * 4.rdb1.restore(rdb2) + */ it('testEncryptRdbAndKv0002', 0, async () => { console.log(TAG + "************* testEncryptRdbAndKv0002 start *************"); let kvConfig = { diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js index 1309567d827035496541eff7d71d30ea3c1f38ef..bd388015bf0d9ebff7a424305067aa82b9f711c3 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' @@ -175,7 +175,7 @@ describe('rdbStoreInsertTest', function () { console.log(TAG + "insert with null table") expect(null).assertFail() }) - } catch(err) { + } catch (err) { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() @@ -468,9 +468,9 @@ describe('rdbStoreInsertTest', function () { await rdbStore1.executeSql(CREATE_TABLE_TEST, null); await rdbStore1.close().then(() => { console.info(`close succeeded`); - }).catch((err) => { + }).catch((err) => { console.error(`close failed, code is ${err.code},message is ${err.message}`); - }) + }) var u8 = new Uint8Array([1, 2, 3]) const valueBucket = { @@ -527,7 +527,7 @@ describe('rdbStoreInsertTest', function () { console.log(TAG + "insert with wrong valuebucket and ConflictResolution is default") done(); }) - } catch(err) { + } catch (err) { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) expect(null).assertFail() @@ -744,7 +744,7 @@ describe('rdbStoreInsertTest', function () { try { rdbStore.insert("test", valueBucket, 6); expect(null).assertFail() - } catch(err) { + } catch (err) { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertSyncJsUnit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertSyncJsUnit.test.js index 3a14233ec719178c723e042e2489d94e228bac5e..1a4a4d183a1bef03f48f850d5781239c5c13d8e8 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertSyncJsUnit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertSyncJsUnit.test.js @@ -743,27 +743,27 @@ describe('rdbStoreInsertSyncTest', function () { * 3.BatchInsert data * 4.Query data */ - it('testRdbStoreSyncbatchInsert001', 0, async function () { - console.log(TAG + "************* testRdbStoreSyncbatchInsert001 start *************"); - - var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - let valueBucketArray = new Array(); - for (let i = 0; i < 100; i++) { - valueBucketArray.push(valueBucket); - } - rdbStore.batchInsertSync("test", valueBucketArray); - let resultSet = await rdbStore.querySql("SELECT * FROM test"); - let count = resultSet.rowCount; - expect(100).assertEqual(count); - resultSet.close() - console.log(TAG + "************* testRdbStoreSyncbatchInsert001 end *************"); - }) + it('testRdbStoreSyncbatchInsert001', 0, async function () { + console.log(TAG + "************* testRdbStoreSyncbatchInsert001 start *************"); + + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + let valueBucketArray = new Array(); + for (let i = 0; i < 100; i++) { + valueBucketArray.push(valueBucket); + } + rdbStore.batchInsertSync("test", valueBucketArray); + let resultSet = await rdbStore.querySql("SELECT * FROM test"); + let count = resultSet.rowCount; + expect(100).assertEqual(count); + resultSet.close() + console.log(TAG + "************* testRdbStoreSyncbatchInsert001 end *************"); + }) /** * @tc.number SUB_DDM_AppDataFWK_JSRDB_batchInsert_0002 diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreLockRowJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreLockRowJsunit.test.js index 223a58173974a10afff7d1faa1a8ad5eaf187c11..08abbb00567ffae8a756d5ff92caf66639fbb94a 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreLockRowJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreLockRowJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' var context = ability_featureAbility.getContext() @@ -80,7 +80,7 @@ describe('rdbStoreLockRowTest', function () { console.info(TAG + 'beforeAll') rdbStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG); await rdbStore.executeSql(CREATE_TABLE_TEST, null); - + try { let tableArray = [TABLE]; const setConfig = { @@ -108,14 +108,14 @@ describe('rdbStoreLockRowTest', function () { rdbStore = null await data_relationalStore.deleteRdbStore(context, "LockRowTest.db"); }) - + async function checkStatus(name, status) { try { let sql = CHECK_STATUS + name + "'"; let resultSet = await rdbStore.querySql(sql); expect(true).assertEqual(resultSet.goToNextRow()); expect(status).assertEqual(resultSet.getLong(0)); - console.log(TAG + `checkStatus success, status: `+ resultSet.getLong(0) + ', expert is ' + status) + console.log(TAG + `checkStatus success, status: ` + resultSet.getLong(0) + ', expert is ' + status) resultSet.close(); } catch (err) { console.log(TAG + `checkStatus failed, err: ${JSON.stringify(err)}`) @@ -315,7 +315,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName, LOCKED) console.log(TAG + `lock success`) @@ -329,7 +329,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName, LOCKED) console.log(TAG + `lock success`) @@ -343,7 +343,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName, UNLOCK) console.log(TAG + `unlock success`) @@ -369,7 +369,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName, UNLOCK) console.log(TAG + `unlock success`) @@ -383,7 +383,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName, LOCKED) console.log(TAG + `lock success`) @@ -406,7 +406,7 @@ describe('rdbStoreLockRowTest', function () { let ret = await rdbStore.update(valueBucket, predicates) await expect(1).assertEqual(ret); console.log(TAG + "update done: " + ret); - + // check default status await checkStatus(checkName, LOCK_CHANGE) console.log(TAG + `lock change success`) @@ -432,7 +432,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName, LOCK_CHANGE) console.log(TAG + `lock change success`) @@ -455,7 +455,7 @@ describe('rdbStoreLockRowTest', function () { let ret = await rdbStore.update(valueBucket, predicates) await expect(1).assertEqual(ret); await console.log(TAG + "update done: " + ret); - + // check default status await checkStatus(checkName, LOCK_CHANGE) console.log(TAG + `lock change success`) @@ -469,7 +469,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName, UNLOCKING) console.log(TAG + `unlocking success`) @@ -494,7 +494,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName, UNLOCKING) console.log(TAG + `unlocking success`) @@ -508,7 +508,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName, LOCK_CHANGE) console.log(TAG + `lock change success`) @@ -590,7 +590,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName2, LOCKED) console.log(TAG + `lock success`) @@ -604,7 +604,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName2, LOCKED) console.log(TAG + `lock success`) @@ -618,7 +618,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName2, UNLOCK) console.log(TAG + `unlock success`) @@ -644,7 +644,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName2, UNLOCK) console.log(TAG + `unlock success`) @@ -658,7 +658,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName2, LOCKED) console.log(TAG + `lock success`) @@ -684,7 +684,7 @@ describe('rdbStoreLockRowTest', function () { let ret = await rdbStore.update(valueBucket, predicates) await expect(1).assertEqual(ret); await console.log(TAG + "update done: " + ret); - + // check default status await checkStatus(checkName2, LOCK_CHANGE) console.log(TAG + `lock change success`) @@ -710,7 +710,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName2, LOCK_CHANGE) console.log(TAG + `lock change success`) @@ -736,7 +736,7 @@ describe('rdbStoreLockRowTest', function () { let ret = await rdbStore.update(valueBucket, predicates) await expect(1).assertEqual(ret); await console.log(TAG + "update done: " + ret); - + // check default status await checkStatus(checkName2, LOCK_CHANGE) console.log(TAG + `lock change success`) @@ -750,7 +750,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName2, UNLOCKING) console.log(TAG + `unlocking success`) @@ -775,7 +775,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.unlockRow(predicates) - + // check default status await checkStatus(checkName2, UNLOCKING) console.log(TAG + `unlocking success`) @@ -789,7 +789,7 @@ describe('rdbStoreLockRowTest', function () { let predicates = new data_relationalStore.RdbPredicates(TABLE) predicates.equalTo("name", checkName2) await rdbStore.lockRow(predicates) - + // check default status await checkStatus(checkName2, LOCK_CHANGE) console.log(TAG + `lock change success`) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstorePluginLibsJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstorePluginLibsJsunit.test.js index 6648c2224518d18d64b4e5d3a0702c473fc70c96..3c97db33ad647c0ea8a3c44018fe88b67e819590 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstorePluginLibsJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstorePluginLibsJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -55,7 +55,7 @@ describe('rdbStorePluginLibsTest', function () { it('testPluginLibs0001', 0, async function () { console.log(TAG + "************* testPluginLibs0001 start *************"); try { - storeConfig.pluginLibs = [ "", "" ] + storeConfig.pluginLibs = ["", ""] rdbStore = await data_relationalStore.getRdbStore(context, storeConfig); } catch (e) { console.log("getRdbStore err: failed, err: code=" + e.code + " message=" + e.message) @@ -72,7 +72,7 @@ describe('rdbStorePluginLibsTest', function () { it('testPluginLibs0002', 0, async function () { console.log(TAG + "************* testPluginLibs0002 start *************"); try { - storeConfig.pluginLibs = [ "./" ] + storeConfig.pluginLibs = ["./"] rdbStore = await data_relationalStore.getRdbStore(context, storeConfig); expect().assertFail(); } catch (e) { @@ -90,7 +90,7 @@ describe('rdbStorePluginLibsTest', function () { it('testPluginLibs0003', 0, async function () { console.log(TAG + "************* testPluginLibs0003 start *************"); try { - storeConfig.pluginLibs = [ "/data/errPath/err.so" ] + storeConfig.pluginLibs = ["/data/errPath/err.so"] rdbStore = await data_relationalStore.getRdbStore(context, storeConfig); expect().assertFail(); } catch (e) { @@ -108,7 +108,7 @@ describe('rdbStorePluginLibsTest', function () { it('testPluginLibs0004', 0, async function () { console.log(TAG + "************* testPluginLibs0004 start *************"); try { - storeConfig.pluginLibs = [ "/data/app/el1/bundle/public/" ] + storeConfig.pluginLibs = ["/data/app/el1/bundle/public/"] rdbStore = await data_relationalStore.getRdbStore(context, storeConfig); expect().assertFail(); } catch (e) { @@ -127,7 +127,7 @@ describe('rdbStorePluginLibsTest', function () { console.log(TAG + "************* testPluginLibs0005 start *************"); try { let path = await context.getFilesDir(); - storeConfig.pluginLibs = [ String(path) ] + storeConfig.pluginLibs = [String(path)] rdbStore = await data_relationalStore.getRdbStore(context, storeConfig); expect().assertFail(); } catch (e) { diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinBJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinBJsunit.test.js index 3080fd1c559ce8a825b855ef08ef8e1ba1d3737a..a78a7e0c03e76437f80b7ac19e7a46a3ee380692 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinBJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinBJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -75,10 +75,10 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(DEPT_TABLE); const depts = [ - {id:10, dName:"JiaoYanBU", loc:"BeiJing"}, - {id:20, dName:"XueGongBu", loc:"ShangHai"}, - {id:30, dName:"XiaoShouBu", loc:"GuangZhou"}, - {id:40, dName:"CaiWuBu", loc:"ShenZhen"}, + { id: 10, dName: "JiaoYanBU", loc: "BeiJing" }, + { id: 20, dName: "XueGongBu", loc: "ShangHai" }, + { id: 30, dName: "XiaoShouBu", loc: "GuangZhou" }, + { id: 40, dName: "CaiWuBu", loc: "ShenZhen" }, ]; await rdbStore.batchInsert("dept", depts); @@ -90,10 +90,10 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(JOB_TABLE); var jobs = [ - {id:1, jName:"Chairman", description:"ManageTheEntireCompany"}, - {id:2, jName:"Manager", description:"ManageEmployeesOfTheDepartment"}, - {id:3, jName:"Salesperson", description:"SellingProductsToCustomers"}, - {id:4, jName:"Clerk", description:"UseOfficeSoftware"}, + { id: 1, jName: "Chairman", description: "ManageTheEntireCompany" }, + { id: 2, jName: "Manager", description: "ManageEmployeesOfTheDepartment" }, + { id: 3, jName: "Salesperson", description: "SellingProductsToCustomers" }, + { id: 4, jName: "Clerk", description: "UseOfficeSoftware" }, ] await rdbStore.batchInsert("job", jobs); @@ -105,20 +105,20 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(EMP_TABLE); var emps = [ - {id:1001, eName:"SunWuKong", jobId:4, mgr:1004, joinDate:"2000-12-17", salary:8000.00, bonus:null, deptId:20}, - {id:1002, eName:"LuJunYi", jobId:3, mgr:1006, joinDate:"2001-02-20", salary:16000.00, bonus:3000.00, deptId:30}, - {id:1003, eName:"LinChong", jobId:3, mgr:1006, joinDate:"2001-02-22", salary:12500.00, bonus:5000.00, deptId:30}, - {id:1004, eName:"TangCeng", jobId:2, mgr:1009, joinDate:"2001-04-02", salary:29750.00, bonus:null, deptId:20}, - {id:1005, eName:"LiKui", jobId:4, mgr:1006, joinDate:"2001-09-28", salary:12500.00, bonus:14000.00, deptId:30}, - {id:1006, eName:"SongJiang", jobId:2, mgr:1009, joinDate:"2001-05-01", salary:28500.00, bonus:null, deptId:30}, - {id:1007, eName:"LiuBei", jobId:2, mgr:1009, joinDate:"2001-09-01", salary:24500.00, bonus:null, deptId:10}, - {id:1008, eName:"ZhuBaJie", jobId:4, mgr:1004, joinDate:"2007-04-19", salary:30000.00, bonus:null, deptId:20}, - {id:1009, eName:"LuoGuanZhong", jobId:1, mgr:null, joinDate:"2001-11-17", salary:50000.00, bonus:null, deptId:10}, - {id:1010, eName:"WuYong", jobId:3, mgr:1006, joinDate:"2001-09-08", salary:15000.00, bonus:0.00, deptId:30}, - {id:1011, eName:"ShaCeng", jobId:4, mgr:1004, joinDate:"2007-05-23", salary:11000.00, bonus:null, deptId:20}, - {id:1012, eName:"LiKui", jobId:4, mgr:1006, joinDate:"2001-12-03", salary:9500.00, bonus:null, deptId:30}, - {id:1013, eName:"XiaoBaiLong", jobId:4, mgr:1004, joinDate:"2001-12-03", salary:30000.00, bonus:null, deptId:20}, - {id:1014, eName:"GuanYu", jobId:4, mgr:1007, joinDate:"2002-01-23", salary:13000.00, bonus:null, deptId:10}, + { id: 1001, eName: "SunWuKong", jobId: 4, mgr: 1004, joinDate: "2000-12-17", salary: 8000.00, bonus: null, deptId: 20 }, + { id: 1002, eName: "LuJunYi", jobId: 3, mgr: 1006, joinDate: "2001-02-20", salary: 16000.00, bonus: 3000.00, deptId: 30 }, + { id: 1003, eName: "LinChong", jobId: 3, mgr: 1006, joinDate: "2001-02-22", salary: 12500.00, bonus: 5000.00, deptId: 30 }, + { id: 1004, eName: "TangCeng", jobId: 2, mgr: 1009, joinDate: "2001-04-02", salary: 29750.00, bonus: null, deptId: 20 }, + { id: 1005, eName: "LiKui", jobId: 4, mgr: 1006, joinDate: "2001-09-28", salary: 12500.00, bonus: 14000.00, deptId: 30 }, + { id: 1006, eName: "SongJiang", jobId: 2, mgr: 1009, joinDate: "2001-05-01", salary: 28500.00, bonus: null, deptId: 30 }, + { id: 1007, eName: "LiuBei", jobId: 2, mgr: 1009, joinDate: "2001-09-01", salary: 24500.00, bonus: null, deptId: 10 }, + { id: 1008, eName: "ZhuBaJie", jobId: 4, mgr: 1004, joinDate: "2007-04-19", salary: 30000.00, bonus: null, deptId: 20 }, + { id: 1009, eName: "LuoGuanZhong", jobId: 1, mgr: null, joinDate: "2001-11-17", salary: 50000.00, bonus: null, deptId: 10 }, + { id: 1010, eName: "WuYong", jobId: 3, mgr: 1006, joinDate: "2001-09-08", salary: 15000.00, bonus: 0.00, deptId: 30 }, + { id: 1011, eName: "ShaCeng", jobId: 4, mgr: 1004, joinDate: "2007-05-23", salary: 11000.00, bonus: null, deptId: 20 }, + { id: 1012, eName: "LiKui", jobId: 4, mgr: 1006, joinDate: "2001-12-03", salary: 9500.00, bonus: null, deptId: 30 }, + { id: 1013, eName: "XiaoBaiLong", jobId: 4, mgr: 1004, joinDate: "2001-12-03", salary: 30000.00, bonus: null, deptId: 20 }, + { id: 1014, eName: "GuanYu", jobId: 4, mgr: 1007, joinDate: "2002-01-23", salary: 13000.00, bonus: null, deptId: 10 }, ]; await rdbStore.batchInsert("emp", emps); @@ -131,11 +131,11 @@ describe('rdbStorePredicatesJoinBTest', function () { await rdbStore.executeSql(SALARYGRADE_TABLE); var salarygrades = [ - {grade:1, loSalary:7000, hiSalary:12000}, - {grade:2, loSalary:12010, hiSalary:14000}, - {grade:3, loSalary:14010, hiSalary:20000}, - {grade:4, loSalary:20010, hiSalary:30000}, - {grade:5, loSalary:30010, hiSalary:99990}, + { grade: 1, loSalary: 7000, hiSalary: 12000 }, + { grade: 2, loSalary: 12010, hiSalary: 14000 }, + { grade: 3, loSalary: 14010, hiSalary: 20000 }, + { grade: 4, loSalary: 20010, hiSalary: 30000 }, + { grade: 5, loSalary: 30010, hiSalary: 99990 }, ]; await rdbStore.batchInsert("salarygrade", salarygrades); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinJsunit.test.js index d493fe992f9f22766c3679f516410ab9b1502298..bfdab4526ac53e9de2ec7bfd83a208a96406bacf 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJoinJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' @@ -72,11 +72,11 @@ describe('rdbStorePredicatesJoinTest', function () { await rdbStore.executeSql(USER_TABLE); const users = [ - {userId:1, firstName:"Zhang", lastName:"San", age:29, balance:100.51}, - {userId:2, firstName:"Li", lastName:"Si", age:30, balance:200.51}, - {userId:3, firstName:"wang", lastName:"wu", age:30, balance:300.51}, - {userId:4, firstName:"sun", lastName:"liu", age:30, balance:400.51}, - {userId:5, firstName:"ma", lastName:"qi", age:32, balance:500.51}, + { userId: 1, firstName: "Zhang", lastName: "San", age: 29, balance: 100.51 }, + { userId: 2, firstName: "Li", lastName: "Si", age: 30, balance: 200.51 }, + { userId: 3, firstName: "wang", lastName: "wu", age: 30, balance: 300.51 }, + { userId: 4, firstName: "sun", lastName: "liu", age: 30, balance: 400.51 }, + { userId: 5, firstName: "ma", lastName: "qi", age: 32, balance: 500.51 }, ]; var objects = new Array(); @@ -97,9 +97,9 @@ describe('rdbStorePredicatesJoinTest', function () { await rdbStore.executeSql(BOOK_TABLE); var books = [ - {id:1, name:"SanGuo", userId:1}, - {id:2, name:"XiYouJi", userId:2}, - {id:3, name:"ShuiHuZhuan", userId:3}, + { id: 1, name: "SanGuo", userId: 1 }, + { id: 2, name: "XiYouJi", userId: 2 }, + { id: 3, name: "ShuiHuZhuan", userId: 3 }, ] var objects = new Array(); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJsunit.test.js index f56825a8484c123b786b2c54372956162c2cc89d..a146a3478e655475ea006cb619aa17a1d7bbc6d4 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstorePredicatesJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -2260,7 +2260,7 @@ describe('rdbPredicatesTest', function () { expect(2).assertEqual(result.getLong(0)); expect(true).assertEqual(result.goToNextRow()) expect(1).assertEqual(result.getLong(0)); - result.close() + result.close() result = null done(); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js index 413dc1fa606d1a4cb460f6fcdeecd1ce75180b61..3649e9372c544240c8ff689b603a5f048fd5cdeb 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js @@ -13,14 +13,14 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility'; const TAG = "[RELATIONAL_STORE_JSKITS_TEST]" const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + - "id INTEGER PRIMARY KEY AUTOINCREMENT, " + - "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"; + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"; const STORE_CONFIG = { name: "RDBPromiseTest.db", @@ -100,7 +100,7 @@ describe('rdbStorePromiseTest', function () { }) }) }) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(null).assertFail() done() @@ -117,14 +117,14 @@ describe('rdbStorePromiseTest', function () { it('testRdbStorePromiseTest0002', 0, async function (done) { console.info(TAG, "************* testRdbStorePromiseTest0002 start *************") try { - data_relationalStore.getRdbStore(context, {dbname: "RDBCallbackTest.db"}).then((rdbStore) => { + data_relationalStore.getRdbStore(context, { dbname: "RDBCallbackTest.db" }).then((rdbStore) => { console.info(TAG, "Get RdbStore successfully.") expect(false).assertTrue() }).catch((err) => { console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() @@ -150,7 +150,7 @@ describe('rdbStorePromiseTest', function () { console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } @@ -177,7 +177,7 @@ describe('rdbStorePromiseTest', function () { console.error(TAG, "Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() @@ -204,7 +204,7 @@ describe('rdbStorePromiseTest', function () { console.error(TAG, "Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } @@ -264,7 +264,7 @@ describe('rdbStorePromiseTest', function () { console.error(TAG, "Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) - } catch(err) { + } catch (err) { console.error(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js index be2545dc1c714d7d6adbf21cab7db42ee3efd42e..3de78fe46a2cbca6067626748c298fe2210a1bab 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreRdbstoreJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility' var context = ability_featureAbility.getContext() @@ -316,22 +316,22 @@ describe('rdbStoreTest', function () { const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "blobType BLOB)"; - + rdbStore.executeSync(CREATE_TABLE_TEST); - + const valueBuckets = Array(rowCount).fill(0).map(() => { return { blobType: new Uint8Array(Array(1024 * 1024).fill(1)), } }) - + rdbStore.batchInsertSync('test', valueBuckets); - + const predicates = new data_relationalStore.RdbPredicates('test'); const resultSet = rdbStore.querySync(predicates); expect(resultSet.rowCount).assertEqual(rowCount); resultSet.goToFirstRow() - + const startTime = new Date().getTime(); rdbStore.insertSync('test', { blobType: new Uint8Array(Array(1024 * 1024).fill(1)), @@ -339,7 +339,7 @@ describe('rdbStoreTest', function () { const middleTime = new Date().getTime(); console.log(TAG + "testRdbStore0012, startTime:" + startTime + " middleTime:" + middleTime); - expect((middleTime - startTime) > 1000).assertTrue(); + expect((middleTime - startTime) > 500).assertTrue(); rdbStore.insertSync('test', { blobType: new Uint8Array(Array(1024 * 1024).fill(1)), @@ -347,7 +347,7 @@ describe('rdbStoreTest', function () { const endTime = new Date().getTime(); console.log(TAG + "testRdbStore0012, endTime:" + endTime + " middleTime:" + middleTime); - expect((endTime - middleTime) < 1000).assertTrue(); + expect((endTime - middleTime) < 500).assertTrue(); console.log(TAG + "************* testRdbStore0012 end *************"); done(); } catch (e) { diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteJsunit.test.js index 65bcc727b37783046a4bf52996da732e41e4da11..0c90c48c96fecdfc9898dfbd3b2f6d81431fdd5b 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js index 84a0e3fda7296023673686cd458c3f8fd1828c0d..798db5c2e92d7b63440a87577d866d7d8f9c7c25 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSqlJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' var context = ability_featureAbility.getContext() @@ -213,7 +213,7 @@ describe('rdbStoreExecuteSqlTest', function () { { let executeSqlPromise = rdbStore.executeSql("DELETE FROM test WHERE age = 19 AND name ='" + nameStr + "'") executeSqlPromise.then(async () => { - await console.log(TAG + "executeSql done." ); + await console.log(TAG + "executeSql done."); }).catch((err) => { expect(null).assertFail(); }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSyncJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSyncJsunit.test.js index 48631b76611cf838ad54654ac2e4ee1f689843db..52e4189c2d1c1e0d34a90dccf3d92865ffcf57d2 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSyncJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreStoreExcuteSyncJsunit.test.js @@ -13,7 +13,7 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreTransactionJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreTransactionJsunit.test.js index bd91c48909ab0436b1d8970a6177430cff40f27b..c5c595ad31aa13ba0f18c485266b8bb14d1e76cb 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreTransactionJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreTransactionJsunit.test.js @@ -13,13 +13,13 @@ * limitations under the License. */ -import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' var context = ability_featureAbility.getContext() const TAG = "[RELATIONAL_STORE_JSKITS_TEST]" -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY, " + +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = { diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js index bee4341e1198ab686e94d268168b60f442b1f54d..c09b0a6a2eae5011a81c08f724d5915ec850e918 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -470,7 +470,7 @@ describe('rdbStoreUpdateTest', function () { console.log(TAG + `failed, err: ${JSON.stringify(err)}`) expect().assertFail() } - + await rdbStore.close().then(() => { console.info(`close succeeded`); }).catch((err) => { @@ -494,7 +494,7 @@ describe('rdbStoreUpdateTest', function () { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) expect("14800014").assertEqual(err.code) } - + await data_relationalStore.deleteRdbStore(context, STORE_NAME); console.log(TAG + "************* testRdbStoreUpdate0009 end *************"); }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateSyncJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateSyncJsunit.test.js index 9562b107a5bf697cb70fb9817a21f3f78fc7406a..5abe18e83128b556fed2cc63506499a60fa34d29 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateSyncJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreUpdateSyncJsunit.test.js @@ -12,7 +12,7 @@ * 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 { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore' import ability_featureAbility from '@ohos.ability.featureAbility' import dataSharePredicates from '@ohos.data.dataSharePredicates'; @@ -468,7 +468,7 @@ describe('rdbStoreUpdateSyncTest', function () { console.log(TAG + `failed, err: ${JSON.stringify(err)}`) expect().assertFail() } - + await rdbStore.close().then(() => { console.info(`close succeeded`); }).catch((err) => { @@ -492,7 +492,7 @@ describe('rdbStoreUpdateSyncTest', function () { console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) expect("14800014").assertEqual(err.code) } - + await data_relationalStore.deleteRdbStore(context, STORE_NAME); console.log(TAG + "************* testSyncRdbStoreUpdate0009 end *************"); }) diff --git a/relational_store/test/native/clouddata/unittest/cloud_data_test.cpp b/relational_store/test/native/clouddata/unittest/cloud_data_test.cpp index a58f2d787fe5d42d3dfcaddc2f0d744e5d17b75b..0db6e691697d2c665c8c96a7f994f1f1747c1c94 100644 --- a/relational_store/test/native/clouddata/unittest/cloud_data_test.cpp +++ b/relational_store/test/native/clouddata/unittest/cloud_data_test.cpp @@ -168,13 +168,10 @@ HWTEST_F(CloudDataTest, CloudDataTest_001, TestSize.Level0) { AllocNormalHapToken(g_normalPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - if (state != CloudService::SUCCESS) { - EXPECT_TRUE(false); - } else { - auto [status, info] = proxy->QueryStatistics(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); - EXPECT_EQ(status, CloudService::PERMISSION_DENIED); - EXPECT_TRUE(info.empty()); - } + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + auto [status, info] = proxy->QueryStatistics(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); + EXPECT_EQ(status, CloudService::PERMISSION_DENIED); + EXPECT_TRUE(info.empty()); } /* * @@ -187,13 +184,10 @@ HWTEST_F(CloudDataTest, CloudDataTest_002, TestSize.Level0) { AllocSystemHapToken(g_notPermissonPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - if (state != CloudService::SUCCESS) { - EXPECT_TRUE(false); - } else { - auto [status, info] = proxy->QueryStatistics(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); - EXPECT_EQ(status, CloudService::CLOUD_CONFIG_PERMISSION_DENIED); - EXPECT_TRUE(info.empty()); - } + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + auto [status, info] = proxy->QueryStatistics(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); + EXPECT_EQ(status, CloudService::CLOUD_CONFIG_PERMISSION_DENIED); + EXPECT_TRUE(info.empty()); } /* * @@ -206,13 +200,10 @@ HWTEST_F(CloudDataTest, CloudDataTest_003, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - if (state != CloudService::SUCCESS) { - EXPECT_TRUE(false); - } else { - auto [status, info] = proxy->QueryStatistics(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); - EXPECT_EQ(status, CloudService::ERROR); - EXPECT_TRUE(info.empty()); - } + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + auto [status, info] = proxy->QueryStatistics(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); + EXPECT_EQ(status, CloudService::ERROR); + EXPECT_TRUE(info.empty()); } /* * @@ -225,7 +216,7 @@ HWTEST_F(CloudDataTest, EnableCloud001, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - ASSERT_EQ(state, CloudService::SUCCESS); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); std::map switches; switches.emplace(TEST_BUNDLE_NAME, 0); auto status = proxy->EnableCloud(TEST_ACCOUNT_ID, switches); @@ -242,7 +233,7 @@ HWTEST_F(CloudDataTest, DisableCloud001, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - ASSERT_EQ(state, CloudService::SUCCESS); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); auto status = proxy->DisableCloud(TEST_ACCOUNT_ID); EXPECT_NE(status, CloudService::SUCCESS); } @@ -257,7 +248,7 @@ HWTEST_F(CloudDataTest, ChangeAppSwitch001, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - ASSERT_EQ(state, CloudService::SUCCESS); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); auto status = proxy->ChangeAppSwitch(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, 0); EXPECT_NE(status, CloudService::SUCCESS); } @@ -272,7 +263,7 @@ HWTEST_F(CloudDataTest, Clean001, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - ASSERT_EQ(state, CloudService::SUCCESS); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); std::map actions; actions.emplace(TEST_BUNDLE_NAME, 0); auto status = proxy->Clean(TEST_ACCOUNT_ID, actions); @@ -289,7 +280,7 @@ HWTEST_F(CloudDataTest, NotifyDataChange001, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - ASSERT_EQ(state, CloudService::SUCCESS); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); auto status = proxy->NotifyDataChange("id", "data", 100); EXPECT_EQ(status, CloudService::INVALID_ARGUMENT); } @@ -304,7 +295,7 @@ HWTEST_F(CloudDataTest, NotifyDataChange002, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - ASSERT_EQ(state, CloudService::SUCCESS); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); auto status = proxy->NotifyDataChange(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME); EXPECT_EQ(status, CloudService::INVALID_ARGUMENT); } @@ -319,7 +310,7 @@ HWTEST_F(CloudDataTest, SetGlobalCloudStrategy001, TestSize.Level0) { AllocSystemHapToken(g_systemPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - ASSERT_EQ(state, CloudService::SUCCESS); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); std::vector values = { 0 }; auto status = proxy->SetGlobalCloudStrategy(Strategy::STRATEGY_NETWORK, values); EXPECT_EQ(status, CloudService::SUCCESS); @@ -335,13 +326,10 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo001, TestSize.Level0) { AllocNormalHapToken(g_normalPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - if (state != CloudService::SUCCESS) { - EXPECT_TRUE(false); - } else { - auto [status, info] = proxy->QueryLastSyncInfo(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); - EXPECT_EQ(status, CloudService::PERMISSION_DENIED); - EXPECT_TRUE(info.empty()); - } + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + auto [status, info] = proxy->QueryLastSyncInfo(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); + EXPECT_EQ(status, CloudService::PERMISSION_DENIED); + EXPECT_TRUE(info.empty()); } /* * @@ -354,12 +342,190 @@ HWTEST_F(CloudDataTest, QueryLastSyncInfo002, TestSize.Level0) { AllocSystemHapToken(g_notPermissonPolicy); auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); - if (state != CloudService::SUCCESS) { - EXPECT_TRUE(false); - } else { - auto [status, info] = proxy->QueryLastSyncInfo(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); - EXPECT_EQ(status, CloudService::CLOUD_CONFIG_PERMISSION_DENIED); - EXPECT_TRUE(info.empty()); - } + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + auto [status, info] = proxy->QueryLastSyncInfo(TEST_ACCOUNT_ID, TEST_BUNDLE_NAME, TEST_STORE_ID); + EXPECT_EQ(status, CloudService::CLOUD_CONFIG_PERMISSION_DENIED); + EXPECT_TRUE(info.empty()); +} + +/* * + * @tc.name: AllocResourceAndShare001 + * @tc.desc: Test the system application permissions of the AllocResourceAndShare001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, AllocResourceAndShare001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + DistributedRdb::PredicatesMemo predicates; + predicates.tables_.push_back(TEST_BUNDLE_NAME); + std::vector columns; + CloudData::Participants participants; + auto [ret, _] = proxy->AllocResourceAndShare(TEST_STORE_ID, predicates, columns, participants); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name: Share001 + * @tc.desc: Test the system application permissions of the Share001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, Share001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string sharingRes = ""; + CloudData::Participants participants{}; + CloudData::Results results; + auto ret = proxy->Share(sharingRes, participants, results); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name: Unshare001 + * @tc.desc: Test the system application permissions of the Unshare001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, Unshare001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string sharingRes = ""; + CloudData::Participants participants{}; + CloudData::Results results; + auto ret = proxy->Unshare(sharingRes, participants, results); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name: Exit001 + * @tc.desc: Test the system application permissions of the Exit001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, Exit001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string sharingRes = ""; + std::pair result; + auto ret = proxy->Exit(sharingRes, result); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name: ChangePrivilege001 + * @tc.desc: Test the system application permissions of the ChangePrivilege001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, ChangePrivilege001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string sharingRes = ""; + CloudData::Participants participants{}; + CloudData::Results results; + auto ret = proxy->ChangePrivilege(sharingRes, participants, results); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name: Query001 + * @tc.desc: Test the system application permissions of the Query001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, Query001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string sharingRes = ""; + CloudData::QueryResults result; + auto ret = proxy->Query(sharingRes, result); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name:QueryByInvitation001 + * @tc.desc: Test the system application permissions of the QueryByInvitation001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, QueryByInvitation001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string invitation = ""; + CloudData::QueryResults result; + auto ret = proxy->QueryByInvitation(invitation, result); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name:ConfirmInvitation001 + * @tc.desc: Test the system application permissions of the ConfirmInvitation001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, ConfirmInvitation001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string sharingRes = ""; + int32_t confirmation = 0; + std::tuple result; + auto ret = proxy->ConfirmInvitation(sharingRes, confirmation, result); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name:ChangeConfirmation001 + * @tc.desc: Test the system application permissions of the ChangeConfirmation001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, ChangeConfirmation001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::string sharingRes = ""; + int32_t confirmation = 0; + std::pair result; + auto ret = proxy->ChangeConfirmation(sharingRes, confirmation, result); + EXPECT_EQ(ret, CloudService::PERMISSION_DENIED); +} + +/* * + * @tc.name:SetCloudStrategy001 + * @tc.desc: Test the system application permissions of the SetCloudStrategy001 API + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(CloudDataTest, SetCloudStrategy001, TestSize.Level0) +{ + AllocNormalHapToken(g_normalPolicy); + auto [state, proxy] = CloudManager::GetInstance().GetCloudService(); + ASSERT_EQ(state == CloudService::SUCCESS && proxy != nullptr, true); + std::vector values; + values.push_back(CloudData::NetWorkStrategy::WIFI); + CloudData::Strategy strategy = CloudData::Strategy::STRATEGY_BUTT; + auto ret = proxy->SetCloudStrategy(strategy, values); + EXPECT_EQ(ret, CloudService::IPC_ERROR); + strategy = CloudData::Strategy::STRATEGY_NETWORK; + ret = proxy->SetCloudStrategy(strategy, values); + EXPECT_EQ(ret, CloudService::SUCCESS); } } // namespace OHOS::CloudData \ No newline at end of file diff --git a/relational_store/test/native/rdb/BUILD.gn b/relational_store/test/native/rdb/BUILD.gn index aa0e8e37f57e614469002e4c5234a8a100fb0da6..5bf2a26366850e3ddc2887295058b570f96a3c3b 100644 --- a/relational_store/test/native/rdb/BUILD.gn +++ b/relational_store/test/native/rdb/BUILD.gn @@ -160,6 +160,7 @@ ohos_unittest("NativeRdbTest") { "hilog:libhilog", "huks:libhukssdk", "ipc:ipc_core", + "kv_store:distributeddata_inner", "kv_store:distributeddb", "samgr:samgr_proxy", ] diff --git a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp b/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp index 27c7497852d49b84704934871a5b904bb0717fc1..5101fb5ff061333e693554f438719ca2a4467feb 100644 --- a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp +++ b/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/rdbimpl_fuzzer.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ -#include "rdb_store_config.h" +#include "rdbimpl_fuzzer.h" + #include "rdb_errno.h" +#include "rdb_store_config.h" #include "rdb_store_impl.h" -#include "rdbimpl_fuzzer.h" using namespace OHOS; using namespace OHOS::NativeRdb; namespace OHOS { @@ -32,13 +33,12 @@ void RdbStoreImplFuzz(const uint8_t *data, size_t size) tables.push_back(rawString); rdbStoreImpl.SetDistributedTables(tables, size & 0x1, { size & 0x1 }); } -} +} // namespace OHOS /* Fuzzer entry point */ -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ OHOS::RdbStoreImplFuzz(data, size); return 0; } - diff --git a/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/rddbrepair_fuzzer/rddbrepair_fuzzer.cpp b/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/rddbrepair_fuzzer/rddbrepair_fuzzer.cpp index c95c225ddb286caf07046d4615c16e050e0bb396..ce6c2faf58472e237df7ce0e78c3f7bf22cf913f 100644 --- a/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/rddbrepair_fuzzer/rddbrepair_fuzzer.cpp +++ b/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/rddbrepair_fuzzer/rddbrepair_fuzzer.cpp @@ -13,10 +13,10 @@ * limitations under the License. */ -#include "rdb_store_config.h" +#include "rd_utils.h" #include "rdb_errno.h" +#include "rdb_store_config.h" #include "rdb_store_impl.h" -#include "rd_utils.h" using namespace OHOS; using namespace OHOS::NativeRdb; namespace OHOS { @@ -25,13 +25,12 @@ void rddbrepairFuzzer(const uint8_t *data, size_t size) { RdUtils::RdDbRepair(reinterpret_cast(data), reinterpret_cast(data)); } -} +} // namespace OHOS /* Fuzzer entry point */ -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ OHOS::rddbrepairFuzzer(data, size); return 0; } - diff --git a/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/transfergrderrno_fuzzer/transfergrderrno_fuzzer.cpp b/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/transfergrderrno_fuzzer/transfergrderrno_fuzzer.cpp index b96efc1dfde5ca86a6f1539b0df8ae5759935665..b7d963fb9826069bda357c0f9b23c983d80634ef 100644 --- a/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/transfergrderrno_fuzzer/transfergrderrno_fuzzer.cpp +++ b/relational_store/test/native/rdb/fuzztest/rdbrdutils_fuzzer/transfergrderrno_fuzzer/transfergrderrno_fuzzer.cpp @@ -13,10 +13,10 @@ * limitations under the License. */ -#include "rdb_store_config.h" +#include "rd_utils.h" #include "rdb_errno.h" +#include "rdb_store_config.h" #include "rdb_store_impl.h" -#include "rd_utils.h" using namespace OHOS; using namespace OHOS::NativeRdb; namespace OHOS { @@ -34,13 +34,12 @@ void RdUtilsTransferGrdErrnoFuzz(const uint8_t *data, size_t size) int err = ConvertToUint32(data, size); RdUtils::TransferGrdErrno(err); } -} +} // namespace OHOS /* Fuzzer entry point */ -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ OHOS::RdUtilsTransferGrdErrnoFuzz(data, size); return 0; } - diff --git a/relational_store/test/native/rdb/fuzztest/rdstatement_fuzzer/rdstatement_fuzzer.cpp b/relational_store/test/native/rdb/fuzztest/rdstatement_fuzzer/rdstatement_fuzzer.cpp index 93aa52c9d46628c8cf93b1a2aa6f5b7015d9f01e..fda67db9b08cd3f869c3c3eb1f247c70dd16a3aa 100644 --- a/relational_store/test/native/rdb/fuzztest/rdstatement_fuzzer/rdstatement_fuzzer.cpp +++ b/relational_store/test/native/rdb/fuzztest/rdstatement_fuzzer/rdstatement_fuzzer.cpp @@ -13,10 +13,10 @@ * limitations under the License. */ -#include "rdb_store_config.h" +#include "rd_statement.h" #include "rdb_errno.h" +#include "rdb_store_config.h" #include "rdb_store_impl.h" -#include "rd_statement.h" using namespace OHOS; using namespace OHOS::NativeRdb; namespace OHOS { @@ -26,13 +26,12 @@ void RdStatementPrepareFuzz(const uint8_t *data, size_t size) std::string sqlString(reinterpret_cast(data), size); stmt->Prepare(sqlString); } -} +} // namespace OHOS /* Fuzzer entry point */ -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ OHOS::RdStatementPrepareFuzz(data, size); return 0; } - diff --git a/relational_store/test/native/rdb/unittest/big_integer_test.cpp b/relational_store/test/native/rdb/unittest/big_integer_test.cpp index 7070f9ace9c5d704f8bd39fc424958dbd54b2da3..9fe003c84c5576d1415728da58ef8fb1a96b6a33 100644 --- a/relational_store/test/native/rdb/unittest/big_integer_test.cpp +++ b/relational_store/test/native/rdb/unittest/big_integer_test.cpp @@ -27,8 +27,8 @@ class BigIntegerTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp(void){}; - void TearDown(void){}; + void SetUp(void) {}; + void TearDown(void) {}; }; void BigIntegerTest::SetUpTestCase(void) diff --git a/relational_store/test/native/rdb/unittest/cache_result_set_test.cpp b/relational_store/test/native/rdb/unittest/cache_result_set_test.cpp index a31757388e71034a958559b13de17f286a364a20..8011fd4f7db29647d008a5d61b9ee9d2de4db503 100644 --- a/relational_store/test/native/rdb/unittest/cache_result_set_test.cpp +++ b/relational_store/test/native/rdb/unittest/cache_result_set_test.cpp @@ -16,6 +16,7 @@ #include "cache_result_set.h" #include + #include #include @@ -35,13 +36,21 @@ public: void TearDown(); }; -void CacheResultSetTest::SetUpTestCase(void) {} +void CacheResultSetTest::SetUpTestCase(void) +{ +} -void CacheResultSetTest::TearDownTestCase(void) {} +void CacheResultSetTest::TearDownTestCase(void) +{ +} -void CacheResultSetTest::SetUp() {} +void CacheResultSetTest::SetUp() +{ +} -void CacheResultSetTest::TearDown() {} +void CacheResultSetTest::TearDown() +{ +} /* * * @tc.name: GetRowCountTest_001 @@ -74,7 +83,7 @@ HWTEST_F(CacheResultSetTest, GetAllColumnNamesTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "test"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -122,7 +131,7 @@ HWTEST_F(CacheResultSetTest, GetStringTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "test"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -145,7 +154,7 @@ HWTEST_F(CacheResultSetTest, GetIntTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, 111); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -168,7 +177,7 @@ HWTEST_F(CacheResultSetTest, GetLongTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, 11111111); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -191,7 +200,7 @@ HWTEST_F(CacheResultSetTest, GetDoubleTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, 1111.1111); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -264,7 +273,7 @@ HWTEST_F(CacheResultSetTest, GetTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, 10); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -315,7 +324,7 @@ HWTEST_F(CacheResultSetTest, GetRowTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "1"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -323,7 +332,7 @@ HWTEST_F(CacheResultSetTest, GetRowTest_001, TestSize.Level2) RowEntity rowEntity; EXPECT_EQ(E_OK, cacheResultSet.GetRow(rowEntity)); - for (auto& columnName : columnNames) { + for (auto &columnName : columnNames) { auto value = rowEntity.Get(columnName); string res; EXPECT_EQ(E_OK, value.GetString(res)); @@ -341,7 +350,7 @@ HWTEST_F(CacheResultSetTest, GoToRowTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "1"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -363,7 +372,7 @@ HWTEST_F(CacheResultSetTest, GetColumnTypeTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "1"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -386,7 +395,7 @@ HWTEST_F(CacheResultSetTest, GetRowIndexTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "1"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -409,7 +418,7 @@ HWTEST_F(CacheResultSetTest, GoToTest_001, TestSize.Level2) for (int i = 0; i < 5; i++) { ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "test" + std::to_string(i)); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -442,7 +451,7 @@ HWTEST_F(CacheResultSetTest, GoToFirstRowTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "test"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -464,7 +473,7 @@ HWTEST_F(CacheResultSetTest, GoToLastRowTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "test"); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -487,7 +496,7 @@ HWTEST_F(CacheResultSetTest, GoToNextRowTest_001, TestSize.Level2) for (int i = 0; i < 5; i++) { ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "test" + std::to_string(i)); } valuesBuckets.push_back(std::move(valuesBucket)); @@ -668,7 +677,7 @@ HWTEST_F(CacheResultSetTest, GetColumnNameTest_001, TestSize.Level2) std::vector valuesBuckets; ValuesBucket valuesBucket; std::set columnNames = { "id", "data", "field" }; - for (auto& column : columnNames) { + for (auto &column : columnNames) { valuesBucket.Put(column, "test"); } valuesBuckets.push_back(std::move(valuesBucket)); diff --git a/relational_store/test/native/rdb/unittest/common.cpp b/relational_store/test/native/rdb/unittest/common.cpp index 45f961f5c1b011984d175e6ac56cc57d129d36f9..7aa22377e43d6d1dba8852ece6d59ca1de6cfea3 100644 --- a/relational_store/test/native/rdb/unittest/common.cpp +++ b/relational_store/test/native/rdb/unittest/common.cpp @@ -14,7 +14,9 @@ */ #include "common.h" + #include + #include "rdb_errno.h" namespace OHOS { @@ -90,5 +92,5 @@ const RowDatas UTUtils::gRowDatas[14] = { { 1012, "LiKui", 4, ValueObject(1006), "2001-12-03", 9500.00, ValueObject(), 30 }, { 1013, "XiaoBaiLong", 4, ValueObject(1004), "2001-12-03", 30000.00, ValueObject(), 20 }, { 1014, "GuanYu", 4, ValueObject(1007), "2002-01-23", 13000.00, ValueObject(), 10 } }; -} -} +} // namespace NativeRdb +} // namespace OHOS diff --git a/relational_store/test/native/rdb/unittest/common.h b/relational_store/test/native/rdb/unittest/common.h index 730c4f1aac1b8c8130be02e45d8d4df277cb252b..f51aa4465ccdb3f5fdbac34603682dc911e9201d 100644 --- a/relational_store/test/native/rdb/unittest/common.h +++ b/relational_store/test/native/rdb/unittest/common.h @@ -17,6 +17,7 @@ #define NATIVE_RDB_TEST_COMMON_H #include + #include "values_bucket.h" namespace OHOS { diff --git a/relational_store/test/native/rdb/unittest/connection_test.cpp b/relational_store/test/native/rdb/unittest/connection_test.cpp index 2b8ea5612719a2c1db78968ceac9071503f5c585..dbe45772cee1aba026e08bce601d0d133c35a860 100644 --- a/relational_store/test/native/rdb/unittest/connection_test.cpp +++ b/relational_store/test/native/rdb/unittest/connection_test.cpp @@ -32,8 +32,8 @@ class ConnectionTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp(void){}; - void TearDown(void){}; + void SetUp(void) {}; + void TearDown(void) {}; }; void ConnectionTest::SetUpTestCase(void) diff --git a/relational_store/test/native/rdb/unittest/rd_utils_test.cpp b/relational_store/test/native/rdb/unittest/rd_utils_test.cpp index 2a204a3bc8967ed1061232d3f22e5dc03b55aa16..a7f3c32b7b729ce19d5c11d8023fb6f860cae4ab 100644 --- a/relational_store/test/native/rdb/unittest/rd_utils_test.cpp +++ b/relational_store/test/native/rdb/unittest/rd_utils_test.cpp @@ -32,8 +32,8 @@ class RdUtilsTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp(void){}; - void TearDown(void){}; + void SetUp(void) {}; + void TearDown(void) {}; }; void RdUtilsTest::SetUpTestCase(void) diff --git a/relational_store/test/native/rdb/unittest/rdb_bigint_test.cpp b/relational_store/test/native/rdb/unittest/rdb_bigint_test.cpp index 4effadfc2493b87676e08621f8b016974383d4f9..39a939fcf7b5016a905dac30e3aab76b15394c04 100644 --- a/relational_store/test/native/rdb/unittest/rdb_bigint_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_bigint_test.cpp @@ -41,12 +41,12 @@ protected: } }; using Floats = ValueObject::FloatVector; - static constexpr const char* PATH_NAME = "/data/test/bigint_test.db"; - static constexpr const char* DATABASE_NAME = "bigint_test.db"; - static constexpr const char* CREATE_TABLE = + static constexpr const char *PATH_NAME = "/data/test/bigint_test.db"; + static constexpr const char *DATABASE_NAME = "bigint_test.db"; + static constexpr const char *CREATE_TABLE = "CREATE TABLE IF NOT EXISTS bigint_table(id INTEGER PRIMARY KEY AUTOINCREMENT, " "value1 UNLIMITED INT NOT NULL, value2 UNLIMITED INT, value3 FLOATVECTOR)"; - static constexpr const char* DROP_TABLE = "DROP TABLE IF EXISTS bigint_table"; + static constexpr const char *DROP_TABLE = "DROP TABLE IF EXISTS bigint_table"; static std::shared_ptr rdbStore_; }; std::shared_ptr RdbBigIntTest::rdbStore_; diff --git a/relational_store/test/native/rdb/unittest/rdb_double_write_concurrent_test.cpp b/relational_store/test/native/rdb/unittest/rdb_double_write_concurrent_test.cpp index a967c56503d07182259399ae2a8b9075d48c7461..4ab065f3957a7e01f19882f3405c1655e6102eb7 100644 --- a/relational_store/test/native/rdb/unittest/rdb_double_write_concurrent_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_double_write_concurrent_test.cpp @@ -14,21 +14,21 @@ */ #define LOG_TAG "RdbDoubleWriteConcurrentTest" #include +#include +#include #include #include -#include "sys/types.h" -#include -#include -#include "logger.h" #include "common.h" -#include "sqlite_utils.h" #include "file_ex.h" +#include "logger.h" #include "rdb_common.h" #include "rdb_errno.h" #include "rdb_helper.h" #include "rdb_open_callback.h" +#include "sqlite_utils.h" +#include "sys/types.h" using namespace testing::ext; using namespace OHOS::NativeRdb; @@ -40,8 +40,8 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); - void CheckNumber(std::shared_ptr &store, int num, int errCode = E_OK, - const std::string &tableName = "test"); + void CheckNumber( + std::shared_ptr &store, int num, int errCode = E_OK, const std::string &tableName = "test"); void Insert(int64_t start, int count, bool isSlave = false, int dataSize = 0); void WaitForBackupFinish(int32_t expectStatus, int maxTimes = 400); void TryInterruptBackup(); @@ -59,10 +59,9 @@ protected: int OnUpgrade(RdbStore &store, int oldVersion, int newVersion) override; protected: - const std::string 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 std::string CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, age INTEGER, salary " + "REAL, blobType BLOB)"; }; enum SlaveStatus : uint32_t { @@ -133,7 +132,7 @@ void RdbDoubleWriteConcurrentTest::Insert(int64_t start, int count, bool isSlave } else { values.PutString("name", std::string("zhangsan")); } - values.PutInt("age", 18); // 18 is data + values.PutInt("age", 18); // 18 is data values.PutDouble("salary", 100.5); // 100.5 is data values.PutBlob("blobType", std::vector{ 1, 2, 3 }); if (isSlave) { @@ -163,18 +162,17 @@ void RdbDoubleWriteConcurrentTest::TryInterruptBackup() int err = store->InterruptBackup(); int tryTimes = 0; while (err != E_OK && (++tryTimes <= 1000)) { // 1000 is try time - usleep(10000); // 10000 delay + usleep(10000); // 10000 delay err = store->InterruptBackup(); } EXPECT_EQ(err, E_OK); LOG_INFO("----------interrupt backup---------"); } -void RdbDoubleWriteConcurrentTest::CheckNumber(std::shared_ptr &store, int num, int errCode, - const std::string &tableName) +void RdbDoubleWriteConcurrentTest::CheckNumber( + std::shared_ptr &store, int num, int errCode, const std::string &tableName) { - std::shared_ptr resultSet = - store->QuerySql("SELECT * FROM " + tableName); + std::shared_ptr resultSet = store->QuerySql("SELECT * FROM " + tableName); ASSERT_NE(resultSet, nullptr); int countNum; int ret = resultSet->GetRowCount(countNum); diff --git a/relational_store/test/native/rdb/unittest/rdb_double_write_test.cpp b/relational_store/test/native/rdb/unittest/rdb_double_write_test.cpp index 9fb8cfb1a1dbc1d976507953616631710d59c3ca..85d3e8bb7f51c712a19067de778a1b10c4bfc47e 100644 --- a/relational_store/test/native/rdb/unittest/rdb_double_write_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_double_write_test.cpp @@ -14,21 +14,21 @@ */ #define LOG_TAG "RdbDoubleWriteTest" #include +#include +#include #include #include -#include "sys/types.h" -#include -#include -#include "logger.h" #include "common.h" -#include "sqlite_utils.h" #include "file_ex.h" +#include "logger.h" #include "rdb_common.h" #include "rdb_errno.h" #include "rdb_helper.h" #include "rdb_open_callback.h" +#include "sqlite_utils.h" +#include "sys/types.h" using namespace testing::ext; using namespace OHOS::NativeRdb; @@ -44,8 +44,8 @@ public: void CheckAge(std::shared_ptr &resultSet); void CheckSalary(std::shared_ptr &resultSet); void CheckBlob(std::shared_ptr &resultSet); - void CheckNumber(std::shared_ptr &store, int num, int errCode = E_OK, - const std::string &tableName = "test"); + void CheckNumber( + std::shared_ptr &store, int num, int errCode = E_OK, const std::string &tableName = "test"); void Insert(int64_t start, int count, bool isSlave = false, int dataSize = 0); void WaitForBackupFinish(int32_t expectStatus, int maxTimes = 400); void TryInterruptBackup(); @@ -72,7 +72,7 @@ std::shared_ptr RdbDoubleWriteTest::store = nullptr; std::shared_ptr RdbDoubleWriteTest::slaveStore = nullptr; std::shared_ptr RdbDoubleWriteTest::store3 = nullptr; const int BLOB_SIZE = 3; -const uint8_t EXPECTED_BLOB_DATA[] {1, 2, 3}; +const uint8_t EXPECTED_BLOB_DATA[]{ 1, 2, 3 }; const int CHECKAGE = 18; const double CHECKCOLUMN = 100.5; @@ -220,7 +220,7 @@ void RdbDoubleWriteTest::TryInterruptBackup() int err = store->InterruptBackup(); int tryTimes = 0; while (err != E_OK && (++tryTimes <= 1000)) { // 1000 is try time - usleep(10000); // 10000 delay + usleep(10000); // 10000 delay err = store->InterruptBackup(); } EXPECT_EQ(err, E_OK); @@ -329,11 +329,10 @@ void RdbDoubleWriteTest::CheckBlob(std::shared_ptr &resultSet) } } -void RdbDoubleWriteTest::CheckNumber(std::shared_ptr &store, int num, int errCode, - const std::string &tableName) +void RdbDoubleWriteTest::CheckNumber( + std::shared_ptr &store, int num, int errCode, const std::string &tableName) { - std::shared_ptr resultSet = - store->QuerySql("SELECT * FROM " + tableName); + std::shared_ptr resultSet = store->QuerySql("SELECT * FROM " + tableName); ASSERT_NE(resultSet, nullptr); int countNum; int ret = resultSet->GetRowCount(countNum); @@ -495,7 +494,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_008, TestSize.Level1) ASSERT_TRUE(file.is_open() == true); file.seekp(30, std::ios::beg); ASSERT_TRUE(file.good() == true); - char bytes[2] = {0x6, 0x6}; + char bytes[2] = { 0x6, 0x6 }; file.write(bytes, 2); ASSERT_TRUE(file.good() == true); file.close(); @@ -555,7 +554,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_010, TestSize.Level1) ASSERT_TRUE(file.is_open() == true); file.seekp(30, std::ios::beg); ASSERT_TRUE(file.good() == true); - char bytes[2] = {0x6, 0x6}; + char bytes[2] = { 0x6, 0x6 }; file.write(bytes, 2); ASSERT_TRUE(file.good() == true); file.close(); @@ -598,7 +597,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_011, TestSize.Level1) ASSERT_TRUE(file.is_open() == true); file.seekp(30, std::ios::beg); ASSERT_TRUE(file.good() == true); - char bytes[2] = {0x6, 0x6}; + char bytes[2] = { 0x6, 0x6 }; file.write(bytes, 2); ASSERT_TRUE(file.good() == true); file.close(); @@ -755,14 +754,14 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_015, TestSize.Level1) ASSERT_TRUE(file.is_open() == true); file.seekp(30, std::ios::beg); ASSERT_TRUE(file.good() == true); - char bytes[2] = {0x6, 0x6}; + char bytes[2] = { 0x6, 0x6 }; file.write(bytes, 2); ASSERT_TRUE(file.good() == true); file.close(); LOG_INFO("RdbStore_DoubleWrite_015 corrupt db finish"); int errCode = slaveStore->ExecuteSql("CREATE TABLE IF NOT EXISTS xx (id INTEGER PRIMARY KEY AUTOINCREMENT," - "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"); + "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"); EXPECT_EQ(errCode, E_OK); EXPECT_EQ(slaveStore->Insert(id, "xx", values), E_OK); @@ -849,7 +848,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_018, TestSize.Level1) values2.PutBlob("blobType", std::vector{ 1, 2, 3 }); int ret3 = store->Insert(id2, "test", values2); EXPECT_EQ(E_OK, ret3); - std::string failureFlagPath = RdbDoubleWriteTest::DATABASE_NAME + + "-slaveFailure"; + std::string failureFlagPath = RdbDoubleWriteTest::DATABASE_NAME + +"-slaveFailure"; bool isFlagFileExists = OHOS::FileExists(failureFlagPath); ASSERT_TRUE(isFlagFileExists); ASSERT_TRUE(store->IsSlaveDiffFromMaster()); @@ -893,7 +892,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_019, TestSize.Level1) values2.PutBlob("blobType", std::vector{ 1, 2, 3 }); int ret3 = store->Insert(id2, "test", values2); EXPECT_EQ(E_OK, ret3); - std::string failureFlagPath = RdbDoubleWriteTest::DATABASE_NAME + + "-slaveFailure"; + std::string failureFlagPath = RdbDoubleWriteTest::DATABASE_NAME + +"-slaveFailure"; bool isFlagFileExists = OHOS::FileExists(failureFlagPath); ASSERT_TRUE(isFlagFileExists); ASSERT_TRUE(store->IsSlaveDiffFromMaster()); @@ -972,7 +971,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_027, TestSize.Level1) ASSERT_TRUE(file.is_open() == true); file.seekp(30, std::ios::beg); ASSERT_TRUE(file.good() == true); - char bytes[2] = {0x6, 0x6}; + char bytes[2] = { 0x6, 0x6 }; file.write(bytes, 2); ASSERT_TRUE(file.good() == true); file.close(); @@ -1045,7 +1044,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_030, TestSize.Level1) id = 666; Insert(id, 1); - std::string failureFlagPath = RdbDoubleWriteTest::DATABASE_NAME + + "-slaveFailure"; + std::string failureFlagPath = RdbDoubleWriteTest::DATABASE_NAME + +"-slaveFailure"; bool isFlagFileExists = OHOS::FileExists(failureFlagPath); ASSERT_TRUE(isFlagFileExists); @@ -1101,7 +1100,7 @@ HWTEST_F(RdbDoubleWriteTest, RdbStore_DoubleWrite_033, TestSize.Level1) ASSERT_TRUE(file.is_open() == true); file.seekp(30, std::ios::beg); ASSERT_TRUE(file.good() == true); - char bytes[2] = {0x6, 0x6}; + char bytes[2] = { 0x6, 0x6 }; file.write(bytes, 2); ASSERT_TRUE(file.good() == true); file.close(); 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 a33ed90ac4acef1ea654e8f6644ef15873a26bc2..530c711ca0a5860dab115eba2aa978828c4f29e1 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 @@ -18,6 +18,7 @@ #include #include +#include #include #include "common.h" @@ -247,6 +248,7 @@ HWTEST_F(RdbEncryptTest, RdbStore_Encrypt_06, TestSize.Level1) config.SetEncryptKey(wrongKey); store = RdbHelper::GetRdbStore(config, 1, helper, errCode); EXPECT_EQ(store, nullptr); + EXPECT_EQ(errCode, E_SQLITE_CORRUPT); } /** @@ -390,6 +392,79 @@ HWTEST_F(RdbEncryptTest, RdbStore_Encrypt_011, TestSize.Level1) EXPECT_EQ(errCode, E_OK); } +/** + * @tc.name: RdbStore_Encrypt_012 + * @tc.desc: test key damage, open encrypted database ,then E_INVALID_SECRET_KEY + * @tc.type: FUNC + */ +HWTEST_F(RdbEncryptTest, RdbStore_Encrypt_012, TestSize.Level1) +{ + RdbStoreConfig config(RdbEncryptTest::ENCRYPTED_DATABASE_NAME); + config.SetEncryptStatus(true); + EncryptTestOpenCallback helper; + int errCode; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(store, nullptr); + EXPECT_EQ(errCode, E_OK); + RdbSecurityManager::KeyFiles keyFile(RdbEncryptTest::ENCRYPTED_DATABASE_NAME); + std::string file = keyFile.GetKeyFile(RdbSecurityManager::KeyFileType::PUB_KEY_FILE); + RdbHelper::ClearCache(); + + std::ofstream fsDb(file, std::ios_base::binary | std::ios_base::out); + fsDb.seekp(64); + fsDb.write("hello", 5); + fsDb.close(); + + store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_EQ(errCode, E_INVALID_SECRET_KEY); + ASSERT_EQ(store, nullptr); +} + +/** + * @tc.name: RdbStore_Encrypt_013 + * @tc.desc: test key damage, allowing rebuild and open encrypted database ,then E_OK + * @tc.type: FUNC + */ +HWTEST_F(RdbEncryptTest, RdbStore_Encrypt_013, TestSize.Level1) +{ + RdbStoreConfig config(RdbEncryptTest::ENCRYPTED_DATABASE_NAME); + config.SetEncryptStatus(true); + EncryptTestOpenCallback helper; + int errCode; + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(store, nullptr); + EXPECT_EQ(errCode, E_OK); + int64_t rowid; + ValuesBucket values; + values.Put("id", 1); + values.Put("name", "zhangsan"); + values.Put("age", 18); + values.Put("salary", 100.5); + values.Put("blobType", std::vector{ 1, 2, 3 }); + auto ret = store->Insert(rowid, "test", values); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(rowid, 1); + RdbSecurityManager::KeyFiles keyFile(RdbEncryptTest::ENCRYPTED_DATABASE_NAME); + std::string file = keyFile.GetKeyFile(RdbSecurityManager::KeyFileType::PUB_KEY_FILE); + RdbHelper::ClearCache(); + + std::ofstream fsDb(file, std::ios_base::binary | std::ios_base::out); + fsDb.seekp(64); + fsDb.write("hello", 5); + fsDb.close(); + + config.SetAllowRebuild(true); + store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_EQ(errCode, E_OK); + ASSERT_NE(store, nullptr); + + std::shared_ptr resultSet = store->QuerySql("SELECT * FROM test"); + EXPECT_NE(resultSet, nullptr); + int count = 1; + resultSet->GetRowCount(count); + EXPECT_EQ(count, 0); +} + /** * @tc.name: RdbStore_RdbPassword_001 * @tc.desc: Abnomal test RdbStore RdbPassword class diff --git a/relational_store/test/native/rdb/unittest/rdb_execute_rd_test.cpp b/relational_store/test/native/rdb/unittest/rdb_execute_rd_test.cpp index 3339afb6e13ebdf534e5f4be5578ab70ff0e9bda..1587db1767b749524e1848585cfeefd2861e0b0e 100644 --- a/relational_store/test/native/rdb/unittest/rdb_execute_rd_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_execute_rd_test.cpp @@ -121,8 +121,7 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_001, TestSize.Level1) values.PutInt("age", 20); values.PutDouble("salary", 300.5); values.PutBlob("blobType", std::vector{ 7, 8, 9 }); - std::vector bindArgs = - std::vector{ ValueObject(std::string("18")), ValueObject(std ::string("20")) }; + std::vector bindArgs = std::vector{ ValueObject(std::string("18")), ValueObject(std ::string("20")) }; std::string sqlDelNoBind = "DELETE FROM test WHERE age = 19"; std::string sqlSelect = "SELECT * FROM test WHERE age = ? OR age = ?"; @@ -354,8 +353,8 @@ constexpr uint16_t SELECT_RES_NUM = 3; HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_007, TestSize.Level1) { std::string sqlSelect = "SELECT * FROM test ORDER BY repr <-> '" + - GetRandVector(MAX_INT_PART, LARGE_ANN_INDEX_DIM) + "' LIMIT " + - std::to_string(SELECT_RES_NUM) + ";"; + GetRandVector(MAX_INT_PART, LARGE_ANN_INDEX_DIM) + "' LIMIT " + + std::to_string(SELECT_RES_NUM) + ";"; std::shared_ptr resultSet = CreateIdxAndSelect(sqlSelect); int columnIndex = 0; size_t vectSize = 0; @@ -457,7 +456,7 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_009, TestSize.Level1) std::shared_ptr &store = RdbExecuteRdTest::store; std::string sqlCreateTable = - "CREATE TABLE test(id int primary key, repr floatvector(" + std::to_string(LARGE_ANN_INDEX_DIM) + "));"; + "CREATE TABLE test(id int primary key, repr floatvector(" + std::to_string(LARGE_ANN_INDEX_DIM) + "));"; std::string sqlCreateIndex = "CREATE INDEX diskann_l2_idx ON test USING GSIVFFLAT(repr L2);"; std::string sqlSelect = "SELECT * FROM test;"; @@ -471,7 +470,7 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_009, TestSize.Level1) for (uint16_t i = 0; i < EXPEC_INSERT_CNT_FOR; i++) { std::string sqlInsert = "INSERT INTO test VALUES(1000000" + std::to_string(i) + ", '" + - GetRandVector(MAX_INT_PART, LARGE_ANN_INDEX_DIM) + "');"; + GetRandVector(MAX_INT_PART, LARGE_ANN_INDEX_DIM) + "');"; res = store->Execute(sqlInsert.c_str(), {}, trx.second); EXPECT_EQ(res.first, E_OK); } @@ -543,7 +542,7 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_011, TestSize.Level1) std::shared_ptr &store = RdbExecuteRdTest::store; std::string sqlCreateTable = "CREATE TABLE test(id int primary key, day int, repr floatvector(" + - std::to_string(LARGE_ANN_INDEX_DIM) + "));"; + std::to_string(LARGE_ANN_INDEX_DIM) + "));"; std::string sqlCreateIndex = "CREATE INDEX diskann_l2_idx ON test USING GSIVFFLAT(repr L2);"; std::string sqlSelect = "SELECT * FROM test;"; @@ -592,8 +591,8 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_011, TestSize.Level1) EXPECT_EQ(colType, ColumnType::TYPE_INTEGER); EXPECT_EQ( - E_COLUMN_OUT_RANGE, resultSet->GetColumnType(100, colType)); // 100是一个不存在的col, 所以预期返回错误码 - EXPECT_EQ(colType, ColumnType::TYPE_INTEGER); // 值不会被更新 + E_COLUMN_OUT_RANGE, resultSet->GetColumnType(100, colType)); // 100是一个不存在的col, 所以预期返回错误码 + EXPECT_EQ(colType, ColumnType::TYPE_INTEGER); // 值不会被更新 EXPECT_EQ(E_OK, resultSet->GetLong(columnIndex, intVal)); EXPECT_EQ(1, intVal); @@ -698,7 +697,7 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_014, TestSize.Level1) std::shared_ptr &store = RdbExecuteRdTest::store; std::string sqlCreateTable = "CREATE TABLE test(id int primary key, age int, repr floatvector(" + - std::to_string(LARGE_ANN_INDEX_DIM) + "));"; + std::to_string(LARGE_ANN_INDEX_DIM) + "));"; std::string sqlCreateIndex = "CREATE INDEX diskann_l2_idx ON test USING GSIVFFLAT(repr L2);"; std::string sqlSelect = "SELECT * FROM test;"; @@ -798,7 +797,8 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_016, TestSize.Level1) res = store->Execute(sqlCreateIdx.c_str(), {}); EXPECT_EQ(res.first, E_OK); - std::vector> vectorSamples = {{1.0, 2.0, 3.0, 4.0}, {10, 20, 30, 40}, {100, 200, 300, 400}}; + std::vector> vectorSamples = { { 1.0, 2.0, 3.0, 4.0 }, { 10, 20, 30, 40 }, + { 100, 200, 300, 400 } }; for (uint32_t i = 0; i < vectorSamples.size(); i++) { std::pair trx = {}; @@ -813,7 +813,7 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_016, TestSize.Level1) EXPECT_FLOAT_EQ(vectorSamples[i][j], vector[j]); } - res = store->Execute(sqlInsert.c_str(), {ValueObject(std::string("textVal")), floatObj}, trx.second); + res = store->Execute(sqlInsert.c_str(), { ValueObject(std::string("textVal")), floatObj }, trx.second); EXPECT_EQ(res.first, E_OK); EXPECT_EQ(E_OK, store->Commit(trx.second)); } @@ -826,9 +826,9 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_016, TestSize.Level1) std::string primaryStrVal = ""; std::string textStrVal = ""; ValueObject::FloatVector floatVector = {}; - resultSet->GetString(0, primaryStrVal); // 0 is the index of primary String column in select projection - resultSet->GetString(1, textStrVal); // 1 is the index of TEXT column in select projection - resultSet->GetFloat32Array(2, floatVector); // 2 is the index of vector column in select projection + resultSet->GetString(0, primaryStrVal); // 0 is the index of primary String column in select projection + resultSet->GetString(1, textStrVal); // 1 is the index of TEXT column in select projection + resultSet->GetFloat32Array(2, floatVector); // 2 is the index of vector column in select projection EXPECT_STREQ(std::to_string(resCnt).c_str(), primaryStrVal.c_str()); EXPECT_STREQ("textVal", textStrVal.c_str()); EXPECT_EQ(vectorSamples[resCnt].size(), floatVector.size()); @@ -837,7 +837,7 @@ HWTEST_P(RdbExecuteRdTest, RdbStore_Execute_016, TestSize.Level1) } resCnt++; } - EXPECT_EQ(2, resCnt); // Expect 2 result due to limit 2 + EXPECT_EQ(2, resCnt); // Expect 2 result due to limit 2 } /** @@ -955,7 +955,7 @@ HWTEST_P(RdbExecuteRdTest, Rdb_BackupRestoreTest_001, TestSize.Level2) EXPECT_EQ(res.first, E_OK); res = store->Execute(sqlInsert.c_str(), {}); EXPECT_EQ(res.first, E_OK); - + std::vector encryptKey; if (GetParam()) { encryptKey = config.GetEncryptKey(); @@ -987,7 +987,7 @@ HWTEST_P(RdbExecuteRdTest, Rdb_BackupRestoreTest_001, TestSize.Level2) EXPECT_EQ(E_OK, resultSet->Close()); res = store->Execute("DROP TABLE test;"); EXPECT_EQ(E_OK, res.first); - + RdbHelper::DeleteRdbStore(RdbExecuteRdTest::restoreDatabaseName); RdbHelper::DeleteRdbStore(RdbExecuteRdTest::backupDatabaseName); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_helper_test.cpp b/relational_store/test/native/rdb/unittest/rdb_helper_test.cpp index ac7b09da431ecb0e08283f3731a16e4fb6ca769d..4b67b04c4ba44904b1af31e5a19f11a5ae7b878e 100644 --- a/relational_store/test/native/rdb/unittest/rdb_helper_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_helper_test.cpp @@ -243,17 +243,48 @@ HWTEST_F(RdbHelperTest, GetDatabase_003, TestSize.Level0) RdbHelper::DeleteRdbStore(config); - int errCode = E_OK; + // Ensure that the database returns OK when it is successfully opened + int errCode = E_ERROR; RdbHelperTestOpenCallback helper; std::shared_ptr rdbStore1 = RdbHelper::GetRdbStore(config, 1, helper, errCode); EXPECT_EQ(errCode, E_OK); - EXPECT_NE(rdbStore1, nullptr); + ASSERT_NE(rdbStore1, nullptr); config.SetEncryptStatus(false); std::shared_ptr rdbStore2 = RdbHelper::GetRdbStore(config, 1, helper, errCode); + // Ensure that the database can be opened after the encryption parameters are changed EXPECT_EQ(errCode, E_OK); - EXPECT_NE(rdbStore2, nullptr); + ASSERT_NE(rdbStore2, nullptr); + + // Ensure that two databases will not be opened after the encrypt parameters are changed + errCode = rdbStore1->BeginTransaction(); + EXPECT_EQ(errCode, E_OK); + errCode = rdbStore2->BeginTransaction(); + EXPECT_EQ(errCode, E_OK); +} - EXPECT_NE(rdbStore1, rdbStore2); +HWTEST_F(RdbHelperTest, GetDatabase_004, TestSize.Level0) +{ + const std::string dbPath = RDB_TEST_PATH + "GetDatabase.db"; + RdbStoreConfig config(dbPath); + std::string bundleName = "com.ohos.config.GetDatabase"; + config.SetBundleName(bundleName); + config.SetArea(1); + config.SetEncryptStatus(true); + + RdbHelper::DeleteRdbStore(config); + + int errCode = E_OK; + + RdbHelperTestOpenCallback helper; + std::shared_ptr rdbStore1 = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_EQ(errCode, E_OK); + EXPECT_NE(rdbStore1, nullptr); + + config.SetVisitorDir(dbPath); + config.SetRoleType(RoleType::VISITOR_WRITE); + std::shared_ptr rdbStore2 = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(errCode, E_OK); + EXPECT_EQ(rdbStore2, nullptr); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_security_manager_test.cpp b/relational_store/test/native/rdb/unittest/rdb_security_manager_test.cpp index 9d66ac6bab61d0e3dcd6d0ded6d5f9400eb9011a..cf8b1f7a2544a8cb2d3147dabcf0ff3aabfc561a 100644 --- a/relational_store/test/native/rdb/unittest/rdb_security_manager_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_security_manager_test.cpp @@ -17,12 +17,13 @@ #include #include + #include #include "common.h" +#include "file_ex.h" #include "rdb_errno.h" #include "rdb_helper.h" -#include "file_ex.h" using namespace testing::ext; using namespace OHOS::NativeRdb; @@ -141,7 +142,7 @@ HWTEST_F(RdbSecurityManagerTest, LoadSecretKeyFromDiskTest, TestSize.Level1) std::vector content = { 'a' }; bool ret = OHOS::SaveBufferToFile(file, content); ASSERT_TRUE(ret); - + std::vector keyfile2; ASSERT_TRUE(OHOS::LoadBufferFromFile(file, keyfile2)); ASSERT_NE(keyfile1.size(), keyfile2.size()); @@ -156,4 +157,4 @@ HWTEST_F(RdbSecurityManagerTest, LoadSecretKeyFromDiskTest, TestSize.Level1) RdbHelper::DeleteRdbStore(config); } -} \ No newline at end of file +} // namespace Test \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_sql_utils_test.cpp b/relational_store/test/native/rdb/unittest/rdb_sql_utils_test.cpp index 9c66c160a49f9b8803876ebbc5ae661cb20069b0..fbc5630908ba34b7cf6f462cc94d21e9ef037897 100644 --- a/relational_store/test/native/rdb/unittest/rdb_sql_utils_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_sql_utils_test.cpp @@ -30,8 +30,8 @@ class RdbSqlUtilsTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp(void){}; - void TearDown(void){}; + void SetUp(void) {}; + void TearDown(void) {}; }; void RdbSqlUtilsTest::SetUpTestCase(void) diff --git a/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp index 279e7a86cb3293a38d993d4527c14856f6d8063b..ccf8c5eb93247af47e7aa53d1cac7bd43e0df60b 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp @@ -20,6 +20,9 @@ #include #include +#include "types.h" +#include "single_kvstore.h" +#include "distributed_kv_data_manager.h" #include "common.h" #include "rdb_errno.h" #include "rdb_helper.h" @@ -407,6 +410,59 @@ HWTEST_F(RdbStoreImplTest, Rdb_BackupTest_001, TestSize.Level2) RdbHelper::DeleteRdbStore(DATABASE_NAME); } +/* * + * @tc.name: Rdb_BackupTest_009 + * @tc.desc: Abnormal testCase for Backup + * @tc.type: FUNC + */ +HWTEST_F(RdbStoreImplTest, Rdb_BackupTest_009, TestSize.Level2) +{ + OHOS::DistributedKv::AppId appId; + OHOS::DistributedKv::StoreId storeId64; + OHOS::DistributedKv::DistributedKvDataManager manager; + OHOS::DistributedKv::Options create; + + std::shared_ptr executors; + manager.SetExecutors(executors); + appId.appId = "ohos.kvdatamanager.test"; + storeId64.storeId = "a000000000b000000000c000000000d000000000e000000000f000000000g000"; + create.createIfMissing = true; + create.encrypt = false; + create.securityLevel = OHOS::DistributedKv::SecurityLevel::S1; + create.autoSync = true; + create.kvStoreType = OHOS::DistributedKv::KvStoreType::SINGLE_VERSION; + create.area = OHOS::DistributedKv::Area::EL1; + create.baseDir = std::string("/data/service/el1/public/database/") + appId.appId; + mkdir(create.baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); + std::shared_ptr notExistKvStore; + int status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore); + ASSERT_EQ(status, OHOS::DistributedKv::Status::SUCCESS); + EXPECT_NE(notExistKvStore, nullptr); + + const std::string attachedName = "attached"; + int errCode = E_OK; + RdbStoreConfig config1(RDB_TEST_PATH + "stepReSUltSet_lmpl_testA.db"); + config1.SetSecurityLevel(SecurityLevel::S1); + config1.SetEncryptStatus(true); + RdbStoreImplTestOpenCallback helper; + std::shared_ptr storeA = RdbHelper::GetRdbStore(config1, 1, helper, errCode); + ASSERT_NE(storeA, nullptr); + ASSERT_EQ(errCode, E_OK); + + RdbStoreConfig config2(RDB_TEST_PATH + "stepResultSet_lmpl_testB.db"); + config2.SetSecurityLevel(SecurityLevel::S1); + config2.SetEncryptStatus(true); + std::shared_ptr storeB = RdbHelper::GetRdbStore(config2, 1, helper, errCode); + ASSERT_NE(storeB, nullptr); + ASSERT_EQ(errCode, E_OK); + + std::pair results = storeB->Attach(config1, attachedName, 2); + int32_t result1 = results.first; + ASSERT_EQ(result1, E_OK); + manager.CloseAllKvStore(appId); + manager.DeleteAllKvStore(appId, create.baseDir); +} + /* * * @tc.name: Rdb_SqlitConnectionTest_001 * @tc.desc: Abnormal testCase for SetPageSize, @@ -569,7 +625,7 @@ HWTEST_F(RdbStoreImplTest, NotifyDataChangeTest_002, TestSize.Level2) // set TrackerTable DistributedDB::TrackerSchema tracker; tracker.tableName = "test_callback_t2"; - tracker.extendColName = ""; + tracker.extendColNames = { "id" }; tracker.trackerColNames = { "id", "timestamp" }; using Delegate = DistributedDB::RelationalStoreDelegate; DistributedDB::RelationalStoreManager rStoreManager("test_app", "test_user_id", 0); @@ -614,7 +670,7 @@ HWTEST_F(RdbStoreImplTest, NotifyDataChangeTest_003, TestSize.Level2) // set TrackerTable DistributedDB::TrackerSchema tracker; tracker.tableName = "test_callback_t3"; - tracker.extendColName = ""; + tracker.extendColNames = { "id" }; tracker.trackerColNames = { "id", "timestamp" }; using Delegate = DistributedDB::RelationalStoreDelegate; DistributedDB::RelationalStoreManager rStoreManager("test_app", "test_user_id", 0); diff --git a/relational_store/test/native/rdb/unittest/rdb_store_subscribe_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_subscribe_test.cpp index f022abb7be267b01efaad7686670699ca7f349e5..2a8875e8447bddc36bafbfa72dffca8a87521d6a 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_subscribe_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_subscribe_test.cpp @@ -79,7 +79,7 @@ public: virtual ~TestDetailProgressObserver() { } - void ProgressNotification(const Details &details) override{}; + void ProgressNotification(const Details &details) override {}; }; const std::string RdbStoreSubTest::MAIN_DATABASE_NAME = RDB_TEST_PATH + "subscribe.db"; diff --git a/relational_store/test/native/rdb/unittest/rdb_trans_db_test.cpp b/relational_store/test/native/rdb/unittest/rdb_trans_db_test.cpp index ee627051fa56355a1d007d339ced587b7cf16afa..34f513b827e5b06c1cfe41a9755c920281a84f36 100644 --- a/relational_store/test/native/rdb/unittest/rdb_trans_db_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_trans_db_test.cpp @@ -14,6 +14,7 @@ */ #include + #include #include @@ -486,8 +487,8 @@ HWTEST_F(RdbTransDBTest, Update_001, TestSize.Level1) ASSERT_EQ(errCode, E_OK); ASSERT_EQ(rowId, 1); row.Put("name", "xiaohua"); - row.Put("attachment", - ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); + row.Put( + "attachment", ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); std::tie(errCode, changed) = transDB_->Update(TABLE_NAME, row); ASSERT_EQ(errCode, E_OK); auto resultSet = transDB_->QueryByStep("select * from TEST"); @@ -522,8 +523,8 @@ HWTEST_F(RdbTransDBTest, Update_002, TestSize.Level1) ASSERT_EQ(changedNum, 20); auto updateRow = row_; updateRow.values_.erase("id"); - updateRow.Put("attachment", - ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); + updateRow.Put( + "attachment", ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); int32_t updatedNum = -1; std::tie(errCode, updatedNum) = transDB_->Update(TABLE_NAME, updateRow, "id > ? and id < ?", { 0, 10 }); ASSERT_EQ(errCode, E_OK); @@ -566,11 +567,11 @@ HWTEST_F(RdbTransDBTest, Update_003, TestSize.Level1) ASSERT_EQ(changedNum, 20); auto updateRow = row_; updateRow.values_.erase("id"); - updateRow.Put("attachment", - ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); + updateRow.Put( + "attachment", ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); int32_t updatedNum = -1; - std::tie(errCode, updatedNum) = transDB_->Update(TABLE_NAME, updateRow, "id > ? and id < ?", { 0, 10 }, - ConflictResolution::ON_CONFLICT_ROLLBACK); + std::tie(errCode, updatedNum) = transDB_->Update( + TABLE_NAME, updateRow, "id > ? and id < ?", { 0, 10 }, ConflictResolution::ON_CONFLICT_ROLLBACK); ASSERT_EQ(errCode, E_OK); ASSERT_EQ(updatedNum, 9); auto resultSet = transDB_->QueryByStep("select * from TEST where id > ? and id < ? order by id", { 0, 10 }); @@ -603,8 +604,8 @@ HWTEST_F(RdbTransDBTest, Update_004, TestSize.Level1) ASSERT_EQ(errCode, E_OK); ASSERT_EQ(rowId, 1); row.Put("name", "xiaohua"); - row.Put("attachment", - ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); + row.Put( + "attachment", ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); errCode = transDB_->Update(changed, TABLE_NAME, row); ASSERT_EQ(errCode, E_OK); auto resultSet = transDB_->QueryByStep("select * from TEST"); @@ -639,8 +640,8 @@ HWTEST_F(RdbTransDBTest, Update_005, TestSize.Level1) ASSERT_EQ(changedNum, 20); auto updateRow = row_; updateRow.values_.erase("id"); - updateRow.Put("attachment", - ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); + updateRow.Put( + "attachment", ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); int32_t updatedNum = -1; RdbPredicates rdbPredicates(TABLE_NAME); rdbPredicates.GreaterThan("id", 0); @@ -687,8 +688,8 @@ HWTEST_F(RdbTransDBTest, UpdateWithConflictResolution_001, TestSize.Level1) ASSERT_EQ(changedNum, 20); auto updateRow = row_; updateRow.values_.erase("id"); - updateRow.Put("attachment", - ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); + updateRow.Put( + "attachment", ValueObject(AssetValue{ .id = "119", .name = "picture1", .hash = "111", .path = "/data/test" })); int32_t updatedNum = -1; errCode = transDB_->UpdateWithConflictResolution(updatedNum, TABLE_NAME, updateRow, "id > ? and id < ?", { 0, 10 }); @@ -977,8 +978,8 @@ HWTEST_F(RdbTransDBTest, Execute_Insert_002, TestSize.Level1) auto [errCode, value] = transDB_->Execute("INSERT INTO TEST(id, name) VALUES (?,?)", { 100, "xiaohong" }); ASSERT_EQ(errCode, E_OK); ASSERT_EQ(value, ValueObject(1)); - std::tie(errCode, value) = transDB_->Execute( - "INSERT OR IGNORE INTO TEST(id, name) VALUES (?,?)", { 100, "xiaoming" }); + std::tie(errCode, value) = + transDB_->Execute("INSERT OR IGNORE INTO TEST(id, name) VALUES (?,?)", { 100, "xiaoming" }); ASSERT_EQ(errCode, E_OK); ASSERT_EQ(value, ValueObject(-1)); auto resultSet = transDB_->QueryByStep("select * from TEST where id == ?", RdbStore::Values{ 100 }); @@ -1145,8 +1146,8 @@ HWTEST_F(RdbTransDBTest, ExecuteForLastInsertRowId_001, TestSize.Level1) transDB_->ExecuteForLastInsertedRowId(rowId, "INSERT INTO TEST(id, name) VALUES (?,?)", { 100, "xiaohong" }); ASSERT_EQ(errCode, E_OK); ASSERT_EQ(rowId, 1); - errCode = transDB_->ExecuteForLastInsertedRowId(rowId, "INSERT OR IGNORE INTO TEST(id, name) VALUES (?,?)", - { 100, "xiaoming" }); + errCode = transDB_->ExecuteForLastInsertedRowId( + rowId, "INSERT OR IGNORE INTO TEST(id, name) VALUES (?,?)", { 100, "xiaoming" }); ASSERT_EQ(errCode, E_OK); ASSERT_EQ(rowId, -1); auto resultSet = transDB_->QueryByStep("select * from TEST where id == ?", RdbStore::Values{ 100 }); diff --git a/relational_store/test/native/rdb/unittest/rdb_update_test.cpp b/relational_store/test/native/rdb/unittest/rdb_update_test.cpp index f0f581dc615a54c1527887ee3c35fb6d055c366e..84d4f09274aabb9334c1da6d04f8d482363275b4 100644 --- a/relational_store/test/native/rdb/unittest/rdb_update_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_update_test.cpp @@ -758,16 +758,16 @@ HWTEST_F(RdbStoreUpdateTest, RdbStore_UpdateWithConflictResolution_007, TestSize values.PutInt("id", 2); values.PutInt("age", 19); - ret = store->UpdateWithConflictResolution(changedRows, "test", values, "age = ?", std::vector{ "18" }, - static_cast(6)); + ret = store->UpdateWithConflictResolution( + changedRows, "test", values, "age = ?", std::vector{ "18" }, static_cast(6)); EXPECT_EQ(E_INVALID_CONFLICT_FLAG, ret); EXPECT_EQ(0, changedRows); values.Clear(); values.PutInt("id", 2); values.PutInt("age", 19); - ret = store->UpdateWithConflictResolution(changedRows, "test", values, "age = ?", std::vector{ "18" }, - static_cast(-1)); + ret = store->UpdateWithConflictResolution( + changedRows, "test", values, "age = ?", std::vector{ "18" }, static_cast(-1)); EXPECT_EQ(E_INVALID_CONFLICT_FLAG, ret); EXPECT_EQ(0, changedRows); } diff --git a/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp b/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp index a66d7b45d6b67861dfe28c79086a4d68887476c4..bee28ab34d1ffd3b0fab7a6101175d505a26b327 100644 --- a/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_utils_test.cpp @@ -28,8 +28,8 @@ class RdbUtilsTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp(void){}; - void TearDown(void){}; + void SetUp(void) {}; + void TearDown(void) {}; }; void RdbUtilsTest::SetUpTestCase(void) diff --git a/relational_store/test/native/rdb/unittest/sqlite_utils_test.cpp b/relational_store/test/native/rdb/unittest/sqlite_utils_test.cpp index cb89c4dd47cc7e089f98b2964d4a96a5ce20c23f..2b095fbf9d046082797da6848742e1dfac438980 100644 --- a/relational_store/test/native/rdb/unittest/sqlite_utils_test.cpp +++ b/relational_store/test/native/rdb/unittest/sqlite_utils_test.cpp @@ -27,8 +27,8 @@ class SqliteUtilsTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp(void){}; - void TearDown(void){}; + void SetUp(void) {}; + void TearDown(void) {}; }; void SqliteUtilsTest::SetUpTestCase(void) @@ -71,22 +71,21 @@ HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_006, TestSize.Level1) HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_007, TestSize.Level1) { - EXPECT_EQ(SqliteUtils::Anonymous( - "file /data/stage/el2/database/rdb/ddddddd/30005245854585524412855412_rdb_test.db"), + EXPECT_EQ( + SqliteUtils::Anonymous("file /data/stage/el2/database/rdb/ddddddd/30005245854585524412855412_rdb_test.db"), "file /***/el2/***/***5412_rdb_test.db"); } HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_008, TestSize.Level1) { - EXPECT_EQ( - SqliteUtils::Anonymous("file /data/stage/database/rdb/ddddddd/30005245854585524412855412_rdb_test.db"), + EXPECT_EQ(SqliteUtils::Anonymous("file /data/stage/database/rdb/ddddddd/30005245854585524412855412_rdb_test.db"), "file /***/***5412_rdb_test.db"); } HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_009, TestSize.Level1) { - EXPECT_EQ(SqliteUtils::Anonymous( - "file /data/stage/el2/database/rdb/ddddddd/3E00mnj5H54efg5G4K1ABC5412_rdb_test.db"), + EXPECT_EQ( + SqliteUtils::Anonymous("file /data/stage/el2/database/rdb/ddddddd/3E00mnj5H54efg5G4K1ABC5412_rdb_test.db"), "file /***/el2/***/3E00mnj5H54efg5G4K***5412_rdb_test.db"); } @@ -251,9 +250,9 @@ HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0038, TestSize.Level1) HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0039, TestSize.Level1) { EXPECT_EQ(SqliteUtils::AnonySql("CREATE TABLE IF NOT EXISTS TEST (id INT PRIMARY KEY, name TEXT, extend BLOB, " - "code REAL, years UNLIMIT INT, ment ASSET, ments ASSETS)."), + "code REAL, years UNLIMITED INT, ment ASSET, ments ASSETS)."), "CREATE TABLE IF NOT EXISTS *EST (*d INT PRIMARY KEY, *ame TEXT, " - "***end BLOB, *ode REAL, **ars UNLIMIT INT, *ent ASSET, **nts ASSETS)"); + "***end BLOB, *ode REAL, **ars UNLIMITED INT, *ent ASSET, **nts ASSETS)."); } HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0040, TestSize.Level1) @@ -261,7 +260,7 @@ HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0040, TestSize.Level1) EXPECT_EQ(SqliteUtils::AnonySql("CREATE TABLE TEST (id INT PRIMARY KEY, name TEXT, " "extend BLOB, code REAL, years UNLIMITED INT, ment ASSET, ments ASSETS)."), "CREATE TABLE *EST (*d INT PRIMARY KEY, *ame TEXT, " - "***end BLOB, *ode REAL, **ars UNLIMITED INT, *ent ASSET, **nts ASSETS)"); + "***end BLOB, *ode REAL, **ars UNLIMITED INT, *ent ASSET, **nts ASSETS)."); } HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0041, TestSize.Level1) @@ -300,10 +299,34 @@ HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0047, TestSize.Level1) EXPECT_EQ(SqliteUtils::AnonySql("CREATE TABLE TEST (id INT PRIMARY KEY, name TEXT," " extend BLOB, code REAL, years UNLIMITED INT, ment ASSET, ments ASSETS)."), "CREATE TABLE *EST (*d INT PRIMARY KEY, *ame TEXT, " - "***end BLOB, *ode REAL, **ars UNLIMITED INT, *ent ASSET, **nts ASSETS)"); + "***end BLOB, *ode REAL, **ars UNLIMITED INT, *ent ASSET, **nts ASSETS)."); } HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0048, TestSize.Level1) { - EXPECT_EQ(SqliteUtils::AnonySql("ALTER TABLE table DROP COLUMN column;"), "ALTER TABLE **ble DROP COLUMN ***umn;"); + EXPECT_EQ(SqliteUtils::AnonySql("ALTER TABLE test DROP COLUMN name;"), "ALTER TABLE *est DROP COLUMN *ame;"); +} + +HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0049, TestSize.Level1) +{ + EXPECT_EQ(SqliteUtils::AnonySql("CREATE TABLE IF NOT EXISTS name AS SELECT order AS old, " + "order AS new UNION SELECT shot AS old, shot AS new ;"), + "CREATE TABLE IF NOT EXISTS *ame AS SELECT **der AS *ld, **der " + "AS *ew UNION SELECT *hot AS *ld, *hot AS *ew ;"); +} + +HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0050, TestSize.Level1) +{ + EXPECT_EQ(SqliteUtils::AnonySql("CREATE TABLE IF NOT EXISTS name AS SELECT order AS old \r, " + "order AS new UNION SELECT shot AS old, shot AS new ;"), + "CREATE TABLE IF NOT EXISTS *ame AS SELECT **der AS *ld , **der " + "AS *ew UNION SELECT *hot AS *ld, *hot AS *ew ;"); +} + +HWTEST_F(SqliteUtilsTest, SqliteUtils_Test_0051, TestSize.Level1) +{ + EXPECT_EQ(SqliteUtils::AnonySql("CREATE TABLE IF NOT EXISTS name AS SELECT order AS old \r\n, " + "order AS new UNION SELECT shot AS old, shot AS new ;"), + "CREATE TABLE IF NOT EXISTS *ame AS SELECT **der AS *ld , **der " + "AS *ew UNION SELECT *hot AS *ld, *hot AS *ew ;"); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/transaction_test.cpp b/relational_store/test/native/rdb/unittest/transaction_test.cpp index 177fab5c38dcbdf42acab987f0e43a8585f8103e..573babacd3dd95153140d6a674eccdec2cdd6d8f 100644 --- a/relational_store/test/native/rdb/unittest/transaction_test.cpp +++ b/relational_store/test/native/rdb/unittest/transaction_test.cpp @@ -46,7 +46,6 @@ public: }; }; - int TransactionTest::TransactionTestOpenCallback::OnCreate(RdbStore &store) { auto [ret, value] = store.Execute(CREATE_TABLE_SQL); @@ -193,7 +192,7 @@ HWTEST_F(TransactionTest, RdbStore_Transaction_003, TestSize.Level1) ASSERT_EQ(ret, E_OK); ASSERT_NE(transaction, nullptr); - Transaction::Rows rows { + Transaction::Rows rows{ UTUtils::SetRowData(UTUtils::g_rowData[0]), UTUtils::SetRowData(UTUtils::g_rowData[1]), UTUtils::SetRowData(UTUtils::g_rowData[2]), diff --git a/relational_store/test/native/rdb/unittest/value_object_test.cpp b/relational_store/test/native/rdb/unittest/value_object_test.cpp index fc007879ae5e6d2902edebe2044acfe915c3848e..8081b3fe6e3770d7b4f88f3290b608cfbe252bba 100644 --- a/relational_store/test/native/rdb/unittest/value_object_test.cpp +++ b/relational_store/test/native/rdb/unittest/value_object_test.cpp @@ -31,8 +31,8 @@ class ValueObjectTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); - void SetUp(void){}; - void TearDown(void){}; + void SetUp(void) {}; + void TearDown(void) {}; }; void ValueObjectTest::SetUpTestCase(void) diff --git a/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp b/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp index 184151da627008062bac7869ccf35d658cfa716b..1f4b8481563ba8d677fbfeefda39148512e505e3 100644 --- a/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp +++ b/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp @@ -110,15 +110,14 @@ void RdbDataShareAdapterTest::GenerateDefaultTable() std::vector typeBlob; typeBlob.push_back(uValue); store->ExecuteSql(insertSql, std::vector{ ValueObject(std::string("hello")), ValueObject((int)10), - ValueObject((double)1.0), ValueObject((std::vector)typeBlob) - }); + ValueObject((double)1.0), ValueObject((std::vector)typeBlob) }); /* insert second entry data */ typeBlob.clear(); store->ExecuteSql(insertSql, std::vector{ - ValueObject(std::string("2")), ValueObject((int)-5), ValueObject((double)2.5), - ValueObject() // set double value 2.5 - }); + ValueObject(std::string("2")), ValueObject((int)-5), ValueObject((double)2.5), + ValueObject() // set double value 2.5 + }); /* insert third entry data */ store->ExecuteSql(insertSql, std::vector{ diff --git a/relational_store/test/native/relational_store_test/unittest/rdb_store_test.cpp b/relational_store/test/native/relational_store_test/unittest/rdb_store_test.cpp index e898d8e9d5127a2f0d8899d7dea89bb2d3c3f666..dc26564948ae633521a9044c6cff7ba8c9dfa50b 100644 --- a/relational_store/test/native/relational_store_test/unittest/rdb_store_test.cpp +++ b/relational_store/test/native/relational_store_test/unittest/rdb_store_test.cpp @@ -13,8 +13,6 @@ * limitations under the License. */ -#include "rdb_store_impl.h" - #include #include @@ -24,6 +22,7 @@ #include "rdb_errno.h" #include "rdb_helper.h" #include "rdb_open_callback.h" +#include "rdb_store_impl.h" #include "relational_store_delegate.h" #include "relational_store_manager.h" #include "sqlite_connection.h" @@ -109,8 +108,7 @@ HWTEST_F(RdbTest, GetModifyTimeByRowIdTest_001, TestSize.Level2) EXPECT_EQ(1, rowId); std::vector PKey = { 1 }; - std::map result = - store_->GetModifyTime("RdbTest_integer", "ROWID", PKey); + std::map result = store_->GetModifyTime("RdbTest_integer", "ROWID", PKey); int size = result.size(); EXPECT_EQ(1, size); EXPECT_EQ(100000, int64_t(result[1])); @@ -138,8 +136,7 @@ HWTEST_F(RdbTest, GetModifyTimeByRowIdTest_002, TestSize.Level2) // resultSet is empty std::vector PKey = { 1 }; - std::map result = - store_->GetModifyTime("RdbTest_integer", "ROWID", PKey); + std::map result = store_->GetModifyTime("RdbTest_integer", "ROWID", PKey); int size = result.size(); EXPECT_EQ(0, size); @@ -238,8 +235,7 @@ HWTEST_F(RdbTest, GetModifyTime_002, TestSize.Level2) "data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); std::vector PKey = { 1 }; - std::map result = - store_->GetModifyTime("RdbTest_integer", "data3", PKey); + std::map result = store_->GetModifyTime("RdbTest_integer", "data3", PKey); EXPECT_EQ(0, result.size()); store_->ExecuteSql("DROP TABLE IF EXISTS naturalbase_rdb_aux_RdbTest_integer_log"); @@ -867,8 +863,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_001, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int ret = rstSet->GoToRow(1); @@ -966,8 +961,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_002, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int pos = -2; @@ -1052,8 +1046,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_003, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int retF = rstSet->GoToFirstRow(); @@ -1105,8 +1098,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_004, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int64_t valueInt = 0; @@ -1149,8 +1141,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_005, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); std::string valueStr = ""; @@ -1203,8 +1194,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_006, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); double valueDb = 0.0; @@ -1256,8 +1246,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_007, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int retF = rstSet->GoToFirstRow(); @@ -1296,8 +1285,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_008, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); ColumnType colType; @@ -1347,8 +1335,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_009, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int colIndex = 0; @@ -1382,8 +1369,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_010, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); std::vector allColNamesVec; @@ -1423,8 +1409,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_011, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int retF = rstSet->GoToFirstRow(); @@ -1457,8 +1442,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_012, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int64_t valueInt = 0; @@ -1469,7 +1453,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_012, TestSize.Level1) EXPECT_EQ(retF, E_OK); rstSet->GetLong(0, valueInt); EXPECT_EQ(valueInt, 1.0); - std::string valueStr = ""; + std::string valueStr = ""; rstSet->GetString(1, valueStr); EXPECT_EQ(valueStr, "hello"); rstSet->GetLong(2, valueInt); @@ -1507,8 +1491,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_013, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); @@ -1529,8 +1512,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_014, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); @@ -1539,13 +1521,13 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_014, TestSize.Level1) int retF = rstSet->GoToFirstRow(); EXPECT_EQ(retF, E_OK); - OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); + OHOS::AppDataFwk::SharedBlock *pBk = pSqlSharedRstSet->GetBlock(); EXPECT_NE(pBk, nullptr); std::string path = RdbTest::store->GetPath(); std::string path1 = pBk->Name(); - EXPECT_EQ(path, "/data/test/shared_test.db"); + EXPECT_EQ(path, "/data/test/shared_test.db"); EXPECT_EQ(path1, "/data/test/shared_test.db"); rstSet->Close(); @@ -1562,8 +1544,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_015, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); @@ -1574,10 +1555,10 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_015, TestSize.Level1) EXPECT_EQ(retN, E_OK); std::string path = RdbTest::store->GetPath(); - OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); + OHOS::AppDataFwk::SharedBlock *pBk = pSqlSharedRstSet->GetBlock(); std::string path1 = pBk->Name(); - EXPECT_EQ(path, "/data/test/shared_test.db"); + EXPECT_EQ(path, "/data/test/shared_test.db"); EXPECT_EQ(path1, "/data/test/shared_test.db"); rstSet->Close(); @@ -1595,8 +1576,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_016, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); SqliteSharedResultSet *pSqlSharedRstSet = static_cast(rstSet.get()); @@ -1607,12 +1587,12 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_016, TestSize.Level1) pSqlSharedRstSet->SetFillBlockForwardOnly(true); pSqlSharedRstSet->GoToFirstRow(); - OHOS::AppDataFwk::SharedBlock* pBk = pSqlSharedRstSet->GetBlock(); + OHOS::AppDataFwk::SharedBlock *pBk = pSqlSharedRstSet->GetBlock(); EXPECT_NE(pBk, nullptr); std::string path = RdbTest::store->GetPath(); std::string path1 = pBk->Name(); - EXPECT_EQ(path, "/data/test/shared_test.db"); + EXPECT_EQ(path, "/data/test/shared_test.db"); EXPECT_EQ(path1, "/data/test/shared_test.db"); int rowCnt = 0; @@ -1636,8 +1616,7 @@ HWTEST_F(RdbTest, Sqlite_Shared_Result_Set_017, TestSize.Level1) { GenerateDefaultTable(); std::vector selectionArgs; - std::unique_ptr rstSet = - RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); + std::unique_ptr rstSet = RdbTest::store->QuerySql("SELECT * FROM test", selectionArgs); EXPECT_NE(rstSet, nullptr); int rowCnt = 0; diff --git a/relational_store/test/native/relational_store_test/unittest/relational_store_test.cpp b/relational_store/test/native/relational_store_test/unittest/relational_store_test.cpp index 5dd2d3ef76c5c9b9e0a6e5a226108b507c51b4f2..8490f1fabcd06b42e098465ad31e1cd03ca447d3 100644 --- a/relational_store/test/native/relational_store_test/unittest/relational_store_test.cpp +++ b/relational_store/test/native/relational_store_test/unittest/relational_store_test.cpp @@ -53,10 +53,10 @@ public: static const std::string CREATE_TABLE_TEST; }; -std::string const DeleteTestOpenCallback::CREATE_TABLE_TEST = std::string("CREATE TABLE IF NOT EXISTS test ") - + std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, " - "name TEXT NOT NULL, age INTEGER, salary " - "REAL, blobType BLOB)"); +std::string const DeleteTestOpenCallback::CREATE_TABLE_TEST = + std::string("CREATE TABLE IF NOT EXISTS test ") + std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, age INTEGER, salary " + "REAL, blobType BLOB)"); int DeleteTestOpenCallback::OnCreate(RdbStore &store) { @@ -574,8 +574,8 @@ HWTEST_F(RdbTest, RdbStore_Encrypt_06, TestSize.Level1) RdbSecurityManager::GetInstance().CheckKeyDataFileExists(RdbSecurityManager::KeyFileType::PUB_KEY_BAK_FILE); EXPECT_EQ(ret, false); std::vector key = RdbSecurityManager::GetInstance().GenerateRandomNum(RdbSecurityManager::RDB_KEY_SIZE); - bool flag = RdbSecurityManager::GetInstance().SaveSecretKeyToFile( - RdbSecurityManager::KeyFileType::PUB_KEY_BAK_FILE, key); + bool flag = + RdbSecurityManager::GetInstance().SaveSecretKeyToFile(RdbSecurityManager::KeyFileType::PUB_KEY_BAK_FILE, key); EXPECT_EQ(flag, true); } @@ -645,8 +645,8 @@ HWTEST_F(RdbTest, RdbStore_Encrypt_09, TestSize.Level1) RdbSecurityManager::KeyFileType::PUB_KEY_BAK_FILE, distributedStatus); EXPECT_EQ(ret, E_ERROR); EXPECT_EQ(distributedStatus, false); - ret = RdbSecurityManager::GetInstance().SetKeyDistributedStatus( - RdbSecurityManager::KeyFileType::PUB_KEY_FILE, true); + ret = + RdbSecurityManager::GetInstance().SetKeyDistributedStatus(RdbSecurityManager::KeyFileType::PUB_KEY_FILE, true); EXPECT_EQ(ret, E_OK); ret = RdbSecurityManager::GetInstance().GetKeyDistributedStatus( RdbSecurityManager::KeyFileType::PUB_KEY_FILE, distributedStatus); @@ -1316,14 +1316,14 @@ HWTEST_F(RdbTest, RdbStore_InsertWithConflictResolution_006_007, TestSize.Level1 HWTEST_F(RdbTest, RdbStore_BatchInsert_001, TestSize.Level1) { std::shared_ptr &store = RdbTest::store; - + ValuesBucket values; - + values.PutString("name", "zhangsan"); values.PutInt("age", 18); values.PutDouble("salary", 100.5); values.PutBlob("blobType", std::vector{ 1, 2, 3 }); - + std::vector valuesBuckets; for (int i = 0; i < 100; i++) { valuesBuckets.push_back(values); @@ -1889,16 +1889,16 @@ HWTEST_F(RdbTest, RdbStore_UpdateWithConflictResolution_007, TestSize.Level1) values.PutInt("id", 2); values.PutInt("age", 19); - ret = store->UpdateWithConflictResolution(changedRows, "test", values, "age = ?", std::vector{ "18" }, - static_cast(6)); + ret = store->UpdateWithConflictResolution( + changedRows, "test", values, "age = ?", std::vector{ "18" }, static_cast(6)); EXPECT_EQ(E_INVALID_CONFLICT_FLAG, ret); EXPECT_EQ(0, changedRows); values.Clear(); values.PutInt("id", 2); values.PutInt("age", 19); - ret = store->UpdateWithConflictResolution(changedRows, "test", values, "age = ?", std::vector{ "18" }, - static_cast(-1)); + ret = store->UpdateWithConflictResolution( + changedRows, "test", values, "age = ?", std::vector{ "18" }, static_cast(-1)); EXPECT_EQ(E_INVALID_CONFLICT_FLAG, ret); EXPECT_EQ(0, changedRows); } @@ -1925,8 +1925,7 @@ HWTEST_F(RdbTest, RdbStore_UpdateSqlBuilder_001, TestSize.Level1) EXPECT_EQ(updateSql, "UPDATE test SET age=?,name=?,salary=?"); } -void RdbTest::ExpectValue( - const std::shared_ptr &resultSet, const RowData &expect) +void RdbTest::ExpectValue(const std::shared_ptr &resultSet, const RowData &expect) { EXPECT_NE(nullptr, resultSet); int columnIndex; diff --git a/relational_store/test/ndk/unittest/rdb_store_configv2_test.cpp b/relational_store/test/ndk/unittest/rdb_store_configv2_test.cpp index 27e2f3219804a1d47b5ab8b5426e335d30107afb..5101cb41887a4803e2a65df603256d3ab99ca00d 100644 --- a/relational_store/test/ndk/unittest/rdb_store_configv2_test.cpp +++ b/relational_store/test/ndk/unittest/rdb_store_configv2_test.cpp @@ -93,7 +93,6 @@ HWTEST_F(RdbNativeStoreConfigV2Test, RDB_Native_store_test_001, TestSize.Level1) OH_Rdb_DestroyConfig(config); } - void VdbTest002(const OH_Rdb_ConfigV2 *config) { int errCode = OH_Rdb_ErrCode::RDB_OK; @@ -132,7 +131,7 @@ HWTEST_F(RdbNativeStoreConfigV2Test, RDB_Native_store_test_002, TestSize.Level1) auto config = InitRdbConfig(); int errCode = OH_Rdb_SetDbType(config, RDB_CAYLEY); EXPECT_TRUE(((!OHOS::NativeRdb::IsUsingArkData()) && errCode == OH_Rdb_ErrCode::RDB_E_NOT_SUPPORTED) || - (OHOS::NativeRdb::IsUsingArkData() && errCode == OH_Rdb_ErrCode::RDB_OK)); + (OHOS::NativeRdb::IsUsingArkData() && errCode == OH_Rdb_ErrCode::RDB_OK)); if (OHOS::NativeRdb::IsUsingArkData()) { VdbTest002(config); } @@ -172,9 +171,9 @@ HWTEST_F(RdbNativeStoreConfigV2Test, RDB_Native_store_test_004, TestSize.Level1) EXPECT_EQ(OH_Rdb_ErrCode::RDB_OK, OH_Rdb_SetSecurityLevel(config, S2)); EXPECT_EQ(OH_Rdb_ErrCode::RDB_OK, OH_Rdb_SetSecurityLevel(config, S3)); EXPECT_EQ(OH_Rdb_ErrCode::RDB_OK, OH_Rdb_SetSecurityLevel(config, S4)); - EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetSecurityLevel(config, 0)); // 0 is invalid secure level + EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetSecurityLevel(config, 0)); // 0 is invalid secure level EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetSecurityLevel(config, -1)); // -1 is invalid secure level - EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetSecurityLevel(config, 5)); // 5 is invalid secure level + EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetSecurityLevel(config, 5)); // 5 is invalid secure level EXPECT_EQ(OH_Rdb_ErrCode::RDB_OK, OH_Rdb_SetArea(config, RDB_SECURITY_AREA_EL1)); EXPECT_EQ(OH_Rdb_ErrCode::RDB_OK, OH_Rdb_SetArea(config, RDB_SECURITY_AREA_EL2)); @@ -183,12 +182,12 @@ HWTEST_F(RdbNativeStoreConfigV2Test, RDB_Native_store_test_004, TestSize.Level1) EXPECT_EQ(OH_Rdb_ErrCode::RDB_OK, OH_Rdb_SetArea(config, RDB_SECURITY_AREA_EL5)); EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetArea(config, -1)); // -1 is invalid area level - EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetArea(config, 0)); // 0 is invalid area level - EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetArea(config, 8)); // 8 is invalid area level + EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetArea(config, 0)); // 0 is invalid area level + EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetArea(config, 8)); // 8 is invalid area level EXPECT_EQ(OH_Rdb_ErrCode::RDB_OK, OH_Rdb_SetDbType(config, RDB_SQLITE)); - EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetDbType(config, 0)); // 0 is invalid db type level - EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetDbType(config, 6)); // 6 is invalid db type level + EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetDbType(config, 0)); // 0 is invalid db type level + EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetDbType(config, 6)); // 6 is invalid db type level EXPECT_EQ(OH_Rdb_ErrCode::RDB_E_INVALID_ARGS, OH_Rdb_SetDbType(config, -1)); // -1 is invalid db type level const int *supportList = OH_Rdb_GetSupportedDbType(nullptr); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 7abcf717f5257aa637f2e7c426abf93559327189..05ca3ecc3fabe17d016d6dd815224c95d928ef66 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -33,12 +33,14 @@ enable_testing() #************************************************KVDBTest start************************************************# aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/kvdb/test KvStoreTestSrc) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/kvdb/test/mock/src KvStoreTestSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/common/test KvStoreTestSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest KvStoreTestSrc) add_executable(KVDBTest ${KvStoreTestSrc} ${mainSrc} ${serviceSrc}) -target_link_libraries(KVDBTest ${links} gtest_main gcov distributeddb kvdb) +target_link_libraries(KVDBTest ${links} gtest_main gmock_main gcov distributeddb kvdb) target_include_directories(KVDBTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/common) target_include_directories(KVDBTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/kvdb/include) +target_include_directories(KVDBTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/kvdb/test/mock) target_include_directories(KVDBTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/object/include) target_include_directories(KVDBTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/distributeddatafwk/include) target_include_directories(KVDBTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/innerkitsimpl/distributeddatafwk/src) @@ -58,7 +60,7 @@ aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/dis aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/framework/test DataMgrTestSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/adapter/test DataMgrTestSrc) add_executable(DataMgrServiceTest ${DataMgrTestSrc} ${mainSrc} ${serviceSrc}) -target_link_libraries(DataMgrServiceTest ${links} gtest_main gcov relational_store data_share preferences distributeddb data_object kvdb udmf) +target_link_libraries(DataMgrServiceTest ${links} gtest_main gmock_main gcov relational_store data_share preferences distributeddb data_object kvdb udmf) target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/adapter/account/src) target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/adapter/communicator/src) target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/service/backup/include) @@ -83,6 +85,7 @@ target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/app/src/) target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/frameworks/native/rdb/include/) target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/rdb/include/) +target_include_directories(DataMgrServiceTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../udmf/framework/innerkitsimpl/service//) #************************************************DataMgrServiceTest end************************************************# #************************************************RDBTest start************************************************# diff --git a/udmf/framework/common/custom_utd_json_parser.cpp b/udmf/framework/common/custom_utd_json_parser.cpp index 7a8be281d023d58d8ab3b51c410c66d69a33af41..668dc0719d55f4818faeefb1af27127877f37953 100644 --- a/udmf/framework/common/custom_utd_json_parser.cpp +++ b/udmf/framework/common/custom_utd_json_parser.cpp @@ -75,6 +75,10 @@ bool CustomUtdJsonParser::ConvertUtdCfgsToJson(const std::vector belongingToTypes(utdTypeCfg.belongingToTypes.begin(), utdTypeCfg.belongingToTypes.end()); diff --git a/udmf/framework/common/udmf_radar_reporter.cpp b/udmf/framework/common/udmf_radar_reporter.cpp index e93009b3fc8c89f0e889e517329a0feb8f746a7c..e90101f708e09e20593a93bc0140ad62a9e5b7e6 100644 --- a/udmf/framework/common/udmf_radar_reporter.cpp +++ b/udmf/framework/common/udmf_radar_reporter.cpp @@ -19,8 +19,8 @@ namespace OHOS { namespace UDMF { using namespace RadarReporter; -void RadarReporterAdapter::ReportNormal(const std::string &func, int32_t scene, - int32_t stage, int32_t stageRes, int32_t state) +void RadarReporterAdapter::ReportNormal( + std::string func, int32_t scene, int32_t stage, int32_t stageRes, int32_t state) { struct HiSysEventParam params[] = { { .name = { "ORG_PKG" }, @@ -57,8 +57,41 @@ void RadarReporterAdapter::ReportNormal(const std::string &func, int32_t scene, ); } +void RadarReporterAdapter::ReportNormal(std::string func, int32_t scene, int32_t stage, int32_t stageRes) +{ + struct HiSysEventParam params[] = { + { .name = { "ORG_PKG" }, + .t = HISYSEVENT_STRING, + .v = { .s = const_cast(ORG_PKG) }, + .arraySize = 0 }, + { .name = { "FUNC" }, + .t = HISYSEVENT_STRING, + .v = { .s = const_cast(func.c_str()) }, + .arraySize = 0 }, + { .name = { "BIZ_SCENE" }, + .t = HISYSEVENT_INT32, + .v = { .i32 = scene }, + .arraySize = 0 }, + { .name = { "BIZ_STAGE" }, + .t = HISYSEVENT_INT32, + .v = { .i32 = stage }, + .arraySize = 0 }, + { .name = { "STAGE_RES" }, + .t = HISYSEVENT_INT32, + .v = { .i32 = stageRes }, + .arraySize = 0 } + }; + OH_HiSysEvent_Write( + DOMAIN, + EVENT_NAME, + HISYSEVENT_BEHAVIOR, + params, + sizeof(params) / sizeof(params[0]) + ); +} + void RadarReporterAdapter::ReportFail( - const std::string &func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode, int32_t state) + std::string func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode, int32_t state) { struct HiSysEventParam params[] = { { .name = { "ORG_PKG" }, @@ -83,7 +116,7 @@ void RadarReporterAdapter::ReportFail( .arraySize = 0 }, { .name = { "ERROR_CODE" }, .t = HISYSEVENT_INT32, - .v = { .i32 = stageRes }, + .v = { .i32 = errorCode }, .arraySize = 0 }, { .name = { "BIZ_STATE" }, .t = HISYSEVENT_INT32, @@ -100,7 +133,7 @@ void RadarReporterAdapter::ReportFail( } void RadarReporterAdapter::ReportFail( - const std::string &func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode) + std::string func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode) { struct HiSysEventParam params[] = { { .name = { "ORG_PKG" }, diff --git a/udmf/framework/common/udmf_radar_reporter.h b/udmf/framework/common/udmf_radar_reporter.h index 1a21c91a98f69a14d3aa763fdb8eeaa10b215302..7591c0fd079d772c5028aed2c978b8f3607dc276 100644 --- a/udmf/framework/common/udmf_radar_reporter.h +++ b/udmf/framework/common/udmf_radar_reporter.h @@ -62,9 +62,8 @@ enum StageRes : int32_t { }; enum BizState : int32_t { - DFX_BEGIN = 0, - DFX_NORMAL_END = 1, - DFX_ABNORMAL_END = 2 + DFX_BEGIN = 1, + DFX_END = 2 }; const constexpr char DOMAIN[] = "DISTDATAMGR"; const constexpr char EVENT_NAME[] = "DISTRIBUTED_UDMF_BEHAVIOR"; @@ -73,10 +72,11 @@ const constexpr char ORG_PKG[] = "distributeddata"; class API_EXPORT RadarReporterAdapter { public: - static void ReportNormal(const std::string &func, int32_t scene, int32_t stage, int32_t stageRes, int32_t state); - static void ReportFail( - const std::string &func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode, int32_t state); - static void ReportFail(const std::string &func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode); + static void ReportNormal(std::string func, int32_t scene, int32_t stage, int32_t stageRes, int32_t state); + static void ReportNormal(std::string func, int32_t scene, int32_t stage, int32_t stageRes); + static void ReportFail( + std::string func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode, int32_t state); + static void ReportFail(std::string func, int32_t scene, int32_t stage, int32_t stageRes, int32_t errorCode); }; } // namespace UDMF } // namespace OHOS diff --git a/udmf/framework/common/utd_graph.cpp b/udmf/framework/common/utd_graph.cpp index 2fa09f75fe9b7239db1546b33789e7647c53c70c..429826d0fe66059727d963d3ed14bcbc5a226f8d 100644 --- a/udmf/framework/common/utd_graph.cpp +++ b/udmf/framework/common/utd_graph.cpp @@ -59,6 +59,10 @@ void UtdGraph::InitUtdGraph(const std::vector &descriptorCfgs bool UtdGraph::IsLowerLevelType(const std::string &lowerLevelType, const std::string &heigitLevelType) { + if (graph_ == nullptr) { + LOG_ERROR(UDMF_CLIENT, "graph_ is nullptr."); + return false; + } std::unique_lock lock(graphMutex_); bool isFind = false; int32_t start = graph_->GetIndex(lowerLevelType); diff --git a/udmf/framework/innerkitsimpl/client/udmf_client.cpp b/udmf/framework/innerkitsimpl/client/udmf_client.cpp index 3b494222ea47c18038f805b3169e6da578cbba53..e7275dc542a1e1e3277b7ac2991a5aa3759142fd 100644 --- a/udmf/framework/innerkitsimpl/client/udmf_client.cpp +++ b/udmf/framework/innerkitsimpl/client/udmf_client.cpp @@ -46,14 +46,17 @@ Status UdmfClient::SetData(CustomOption &option, UnifiedData &unifiedData, std:: if (service == nullptr) { LOG_ERROR(UDMF_CLIENT, "Service unavailable"); RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SET_DATA, SetDataStage::SET_DATA_BEGIN, StageRes::FAILED, E_IPC, BizState::DFX_ABNORMAL_END); + BizScene::SET_DATA, SetDataStage::SET_DATA_BEGIN, StageRes::FAILED, E_IPC, BizState::DFX_END); return E_IPC; } - + RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), + BizScene::SET_DATA, SetDataStage::SET_DATA_BEGIN, StageRes::SUCCESS); if (option.intention == UD_INTENTION_DRAG) { ShareOptions shareOption = SHARE_OPTIONS_BUTT; auto status = GetAppShareOption(UD_INTENTION_MAP.at(option.intention), shareOption); if (status != E_NOT_FOUND && status != E_OK) { + RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), + BizScene::SET_DATA, SetDataStage::SET_DATA_END, StageRes::FAILED, status, BizState::DFX_END); LOG_ERROR(UDMF_CLIENT, "get appShareOption fail, intention:%{public}s", UD_INTENTION_MAP.at(option.intention).c_str()); return static_cast(status); @@ -66,19 +69,20 @@ Status UdmfClient::SetData(CustomOption &option, UnifiedData &unifiedData, std:: dataCache_.Insert(key, unifiedData); LOG_INFO(UDMF_CLIENT, "SetData in app success, bundleName:%{public}s.", bundleName.c_str()); RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), - BizScene::SET_DATA, SetDataStage::SET_DATA_END, StageRes::SUCCESS, BizState::DFX_NORMAL_END); + BizScene::SET_DATA, SetDataStage::SET_DATA_END, StageRes::SUCCESS, BizState::DFX_END); return E_OK; } } int32_t ret = service->SetData(option, unifiedData, key); if (ret != E_OK) { RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::SET_DATA, SetDataStage::SET_DATA_END, StageRes::FAILED, ret, BizState::DFX_ABNORMAL_END); + BizScene::SET_DATA, SetDataStage::SET_DATA_END, StageRes::FAILED, ret, BizState::DFX_END); LOG_ERROR(UDMF_CLIENT, "failed! ret = %{public}d", ret); + return static_cast(ret); } RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), - BizScene::SET_DATA, SetDataStage::SET_DATA_END, StageRes::SUCCESS, BizState::DFX_NORMAL_END); - return static_cast(ret); + BizScene::SET_DATA, SetDataStage::SET_DATA_END, StageRes::SUCCESS, BizState::DFX_END); + return E_OK; } Status UdmfClient::GetData(const QueryOption &query, UnifiedData &unifiedData) @@ -91,27 +95,30 @@ Status UdmfClient::GetData(const QueryOption &query, UnifiedData &unifiedData) if (service == nullptr) { LOG_ERROR(UDMF_CLIENT, "Service unavailable"); RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::GET_DATA, GetDataStage::GET_DATA_BEGIN, StageRes::FAILED, E_IPC, BizState::DFX_ABNORMAL_END); + BizScene::GET_DATA, GetDataStage::GET_DATA_BEGIN, StageRes::FAILED, E_IPC, BizState::DFX_END); return E_IPC; } + RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), + BizScene::GET_DATA, GetDataStage::GET_DATA_BEGIN, StageRes::SUCCESS); auto it = dataCache_.Find(query.key); if (it.first) { unifiedData = it.second; dataCache_.Erase(query.key); RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), - BizScene::GET_DATA, GetDataStage::GET_DATA_END, StageRes::SUCCESS, BizState::DFX_NORMAL_END); + BizScene::GET_DATA, GetDataStage::GET_DATA_END, StageRes::SUCCESS, BizState::DFX_END); return E_OK; } LOG_WARN(UDMF_CLIENT, "query data from cache failed! key = %{public}s", query.key.c_str()); int32_t ret = service->GetData(query, unifiedData); if (ret != E_OK) { RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), - BizScene::GET_DATA, GetDataStage::GET_DATA_END, StageRes::FAILED, ret, BizState::DFX_ABNORMAL_END); + BizScene::GET_DATA, GetDataStage::GET_DATA_END, StageRes::FAILED, ret, BizState::DFX_END); LOG_ERROR(UDMF_CLIENT, "failed! ret = %{public}d", ret); + return static_cast(ret); } RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), - BizScene::GET_DATA, GetDataStage::GET_DATA_END, StageRes::SUCCESS, BizState::DFX_NORMAL_END); - return static_cast(ret); + BizScene::GET_DATA, GetDataStage::GET_DATA_END, StageRes::SUCCESS, BizState::DFX_END); + return E_OK; } Status UdmfClient::GetBatchData(const QueryOption &query, std::vector &unifiedDataSet) diff --git a/udmf/framework/innerkitsimpl/data/html.cpp b/udmf/framework/innerkitsimpl/data/html.cpp index 3aebd8d0babbf8860aee05615e2f281aae3aa153..324d9acf5dd96edfad50fbd7096a28a9b052898e 100644 --- a/udmf/framework/innerkitsimpl/data/html.cpp +++ b/udmf/framework/innerkitsimpl/data/html.cpp @@ -13,7 +13,9 @@ * limitations under the License. */ +#define LOG_TAG "HTML" #include "html.h" +#include "logger.h" namespace OHOS { namespace UDMF { @@ -25,6 +27,9 @@ Html::Html() Html::Html(const std::string &htmlContent, const std::string &plainContent) { if (plainContent.length() >= MAX_TEXT_LEN || htmlContent.length() >= MAX_TEXT_LEN) { + LOG_ERROR(UDMF_KITS_INNER, + "htmlContent or plainContent is too long, plainContent.length:%{public}zu, htmlContent.length:%{public}zu", + plainContent.length(), htmlContent.length()); return; } SetType(HTML); @@ -62,6 +67,7 @@ std::string Html::GetHtmlContent() const void Html::SetHtmlContent(const std::string &htmlContent) { if (htmlContent.length() >= MAX_TEXT_LEN) { + LOG_ERROR(UDMF_KITS_INNER, "htmlContent is too long, htmlContent.length:%{public}zu", htmlContent.length()); return; } this->htmlContent_ = htmlContent; @@ -78,6 +84,7 @@ std::string Html::GetPlainContent() const void Html::SetPlainContent(const std::string &plainContent) { if (plainContent.length() >= MAX_TEXT_LEN) { + LOG_ERROR(UDMF_KITS_INNER, "plainContent is too long, plainContent.length:%{public}zu", plainContent.length()); return; } this->plainContent_ = plainContent; diff --git a/udmf/framework/innerkitsimpl/data/plain_text.cpp b/udmf/framework/innerkitsimpl/data/plain_text.cpp index da7d2a8b1249e064f730776900cdf092d4787409..9a28b4f9adffdaccf2b455804424171192ea200f 100644 --- a/udmf/framework/innerkitsimpl/data/plain_text.cpp +++ b/udmf/framework/innerkitsimpl/data/plain_text.cpp @@ -13,7 +13,9 @@ * limitations under the License. */ +#define LOG_TAG "PlainText" #include "plain_text.h" +#include "logger.h" namespace OHOS { namespace UDMF { @@ -24,6 +26,7 @@ PlainText::PlainText() : PlainText("", "") PlainText::PlainText(const std::string &content, const std::string &abstract) { if (content.length() >= MAX_TEXT_LEN) { + LOG_ERROR(UDMF_KITS_INNER, "content is too long, content.length:%{public}zu", content.length()); return; } SetType(PLAIN_TEXT); @@ -61,6 +64,7 @@ std::string PlainText::GetContent() const void PlainText::SetContent(const std::string &text) { if (text.length() >= MAX_TEXT_LEN) { + LOG_ERROR(UDMF_KITS_INNER, "text is too long, text.length:%{public}zu", text.length()); return; } this->content_ = text; @@ -78,6 +82,7 @@ std::string PlainText::GetAbstract() const void PlainText::SetAbstract(const std::string &abstract) { if (abstract.length() >= MAX_TEXT_LEN) { + LOG_ERROR(UDMF_KITS_INNER, "abstract is too long!, abstract.length:%{public}zu", abstract.length()); return; } this->abstract_ = abstract; diff --git a/udmf/framework/innerkitsimpl/data/unified_data.cpp b/udmf/framework/innerkitsimpl/data/unified_data.cpp index 866cd9f5298f1a91c248fababf289a678b78826d..c1675881e26c8fc7dc90db27177ef54b6179dcf6 100644 --- a/udmf/framework/innerkitsimpl/data/unified_data.cpp +++ b/udmf/framework/innerkitsimpl/data/unified_data.cpp @@ -29,6 +29,10 @@ UnifiedData::UnifiedData() UnifiedData::UnifiedData(std::shared_ptr properties) { + if (properties == nullptr) { + LOG_ERROR(UDMF_FRAMEWORK, "Invalid properties!"); + return; + } properties_ = properties; auto duration = std::chrono::system_clock::now().time_since_epoch(); properties_->timestamp = std::chrono::duration_cast(duration).count(); diff --git a/udmf/framework/jskitsimpl/data/unified_data_channel_napi.cpp b/udmf/framework/jskitsimpl/data/unified_data_channel_napi.cpp index b942b8b96ca4ce152eec118cc225c9739c72d331..8daaaeaf8f2515d4705fd4614ecf9a09606b4f58 100644 --- a/udmf/framework/jskitsimpl/data/unified_data_channel_napi.cpp +++ b/udmf/framework/jskitsimpl/data/unified_data_channel_napi.cpp @@ -45,6 +45,10 @@ napi_value UnifiedDataChannelNapi::CreateIntention(napi_env env) { napi_value intention = nullptr; napi_create_object(env, &intention); + if (intention == nullptr) { + LOG_ERROR(UDMF_KITS_NAPI, "create intention failed!"); + return nullptr; + } SetNamedProperty(env, intention, JS_UD_INTENTION_NAME_MAP.at(UD_INTENTION_DATA_HUB), UD_INTENTION_MAP.at(UD_INTENTION_DATA_HUB)); SetNamedProperty(env, intention, JS_UD_INTENTION_NAME_MAP.at(UD_INTENTION_DRAG), diff --git a/udmf/framework/jskitsimpl/data/unified_data_napi.cpp b/udmf/framework/jskitsimpl/data/unified_data_napi.cpp index 9c9fb521d53dc5a004afe12d63cb30f5c62e07f1..905e8cae19068950f9ed8afcdbb889c84130ddfd 100644 --- a/udmf/framework/jskitsimpl/data/unified_data_napi.cpp +++ b/udmf/framework/jskitsimpl/data/unified_data_napi.cpp @@ -78,6 +78,7 @@ napi_value UnifiedDataNapi::New(napi_env env, napi_callback_info info) UnifiedDataPropertiesNapi::Constructor(env)); if (propertiesNapi == nullptr) { LOG_ERROR(UDMF_KITS_NAPI, "new UnifiedDataPropertiesNapi failed!"); + delete(uData); return nullptr; } uData->value_ = std::make_shared(propertiesNapi->value_); diff --git a/udmf/framework/ndkimpl/data/data_provider_impl.cpp b/udmf/framework/ndkimpl/data/data_provider_impl.cpp index 1ff6ff501c87fef912d848ddaa8849c1f027b208..cbef6db323a71495269276a8c574e4a94a36835d 100644 --- a/udmf/framework/ndkimpl/data/data_provider_impl.cpp +++ b/udmf/framework/ndkimpl/data/data_provider_impl.cpp @@ -35,6 +35,10 @@ ValueType DataProviderImpl::GetValueByType(const std::string &utdId) if (utdId.empty()) { return std::monostate(); } + if (innerProvider_ == nullptr) { + LOG_ERROR(UDMF_CAPI, "innerprovider_ is null!"); + return std::monostate(); + } auto value = (innerProvider_->callback)(innerProvider_->context, utdId.c_str()); if (value == nullptr) { LOG_ERROR( diff --git a/udmf/framework/ndkimpl/data/udmf.cpp b/udmf/framework/ndkimpl/data/udmf.cpp index cfbd688ee42b4b0ccae13e90bdb22bb916653c5b..4fa1197fb251ef3d48d64db94220514a342cb185 100644 --- a/udmf/framework/ndkimpl/data/udmf.cpp +++ b/udmf/framework/ndkimpl/data/udmf.cpp @@ -83,10 +83,14 @@ static void DestroyUnifiedRecordArray(OH_UdmfRecord**& records, unsigned int& co static char** StrVectorToTypesArray(const std::vector& strVector) { unsigned int vectorSize = strVector.size(); - if (vectorSize > MAX_RECORDS_COUNT) { + if (vectorSize == 0 || vectorSize > MAX_RECORDS_COUNT) { + return nullptr; + } + char** typesArray = new (std::nothrow) char* [vectorSize]; + if (typesArray == nullptr) { + LOG_ERROR(UDMF_CAPI, "create types array failed!"); return nullptr; } - char** typesArray = new (std::nothrow) char* [vectorSize] {nullptr}; for (unsigned int i = 0; i < vectorSize; ++i) { unsigned int strLen = strVector[i].length() + 1; if (strLen > MAX_KEY_STRING_LEN) { diff --git a/udmf/interfaces/innerkits/common/unified_types.h b/udmf/interfaces/innerkits/common/unified_types.h index c01cf89dad6bca9f9f6a90a2f3485e0258b57a26..2ff3af8f7cdf75382b34e217020d64d9a614fa39 100644 --- a/udmf/interfaces/innerkits/common/unified_types.h +++ b/udmf/interfaces/innerkits/common/unified_types.h @@ -92,17 +92,17 @@ struct AsyncProcessInfo { AsyncTaskStatus syncStatus; AsyncTaskStatus permStatus; std::string srcDevName; - uint32_t syncFinished; - uint32_t syncTotal; - uint32_t syncId; - uint32_t permFnished; - uint32_t permTotal; + uint32_t syncFinished = 0; + uint32_t syncTotal = 0; + uint32_t syncId = 0; + uint32_t permFnished = 0; + uint32_t permTotal = 0; }; struct ProgressInfo { std::string srcDevName; AsyncTaskStatus status; - uint32_t progress; + uint32_t progress = 0; }; } // namespace UDMF } // namespace OHOS