diff --git a/distributeddatamgr/data_object_use_cases/data_object_use_case.cpp b/distributeddatamgr/data_object_use_cases/data_object_use_case.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17a3c660c9c60799a4718c07959666260d42cb2e --- /dev/null +++ b/distributeddatamgr/data_object_use_cases/data_object_use_case.cpp @@ -0,0 +1,44 @@ +// 导入模块 +#include +#include +#include + +#include "distributed_object.h" +#include "distributed_objectstore.h" +#include "objectstore_errors.h" + +#define BUNDLENAME "bundle_test" +#define SESSIONNAME "session_test" + +using namespace std; +using namespace OHOS::ObjectStore; + +// 创建对象,该对象包含4个属性类型:string、number、boolean和Object + +int main(int argc, char *argv[]) +{ + DistributedObjectStore *objectStore = DistributedObjectStore::GetInstance(BUNDLENAME); +/*认证*/ + string sessionId="123456"; +/*链接*/ + +/*创建数据库*/ + DistributedObject *object = objectStore->CreateObject(sessionId); +/*使用(增删改查)*/ + double doubleValue; + bool boolValue; + string stringValue; + + object->PutDouble("doubleTest",3.1415926); + object->PutBoolean("boolTest",true); + object->PutString("stringTest","this is a test"); + + object->GetDouble("doubleTest", doubleValue); + object->GetBoolean("boolTest", boolValue); + object->GetString("stringTest",stringValue); + + cout<DeleteObject(sessionId); +} diff --git a/distributeddatamgr/data_object_use_cases/include/distributed_object.h b/distributeddatamgr/data_object_use_cases/include/distributed_object.h new file mode 100644 index 0000000000000000000000000000000000000000..d64039901092d4a09c93e0117599e04ffaed0937 --- /dev/null +++ b/distributeddatamgr/data_object_use_cases/include/distributed_object.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTED_OBJECT_H +#define DISTRIBUTED_OBJECT_H +#include +#include +#include +#include + +namespace OHOS::ObjectStore { +enum Type : uint8_t { + TYPE_STRING = 0, + TYPE_BOOLEAN, + TYPE_DOUBLE, + TYPE_COMPLEX, +}; +class DistributedObject { +public: + virtual ~DistributedObject(){}; + //描述:修改对象属性,编码后用storage.UpdateItems更新属性值 + //入参:key表名,value要赋的值 + //返回值:SUCCESS成功,ERR_DB_NOT_INIT数据库未初始化,ERR_DB_NOT_EXIST表不存在,ERR_STORAGE高斯数据库错误 + virtual uint32_t PutDouble(const std::string &key, double value) = 0; + virtual uint32_t PutBoolean(const std::string &key, bool value) = 0; + virtual uint32_t PutString(const std::string &key, const std::string &value) = 0; + virtual uint32_t PutComplex(const std::string &key, const std::vector &value) = 0; + //描述:读取对象属性,调用storage.GetItems获取属性值,并进行对应解码 + //入参:key表名 + //出参:value获取到的属性 + //返回值:SUCCESS成功,ERR_DB_NOT_INIT数据库未初始化,ERR_DB_NOT_EXIST表不存在,ERR_STORAGE高斯数据库错误 + virtual uint32_t GetDouble(const std::string &key, double &value) = 0; + virtual uint32_t GetBoolean(const std::string &key, bool &value) = 0; + virtual uint32_t GetString(const std::string &key, std::string &value) = 0; + virtual uint32_t GetComplex(const std::string &key, std::vector &value) = 0; + virtual uint32_t GetType(const std::string &key, Type &type) = 0; + virtual std::string &GetSessionId() = 0; + //描述:保存分布式数据对象 + virtual uint32_t Save(const std::string &deviceId) = 0; + //描述:取消保存分布式数据对象 + virtual uint32_t RevokeSave() = 0; +}; + +class ObjectWatcher { +public: + //描述:获取变更的数据 + virtual void OnChanged(const std::string &sessionid, const std::vector &changedData) = 0; +}; +} // namespace OHOS::ObjectStore +#endif // DISTRIBUTED_OBJECT_H diff --git a/distributeddatamgr/data_object_use_cases/include/distributed_objectstore.h b/distributeddatamgr/data_object_use_cases/include/distributed_objectstore.h new file mode 100644 index 0000000000000000000000000000000000000000..782871e2293a79fa2249764e6d208367b6742fc4 --- /dev/null +++ b/distributeddatamgr/data_object_use_cases/include/distributed_objectstore.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTED_OBJECTSTORE_H +#define DISTRIBUTED_OBJECTSTORE_H +#include +#include +#include +#include + +#include "distributed_object.h" + +namespace OHOS::ObjectStore { +class StatusNotifier { +public: + //获取设备上下线状态 + virtual void OnChanged( + const std::string &sessionId, const std::string &networkId, const std::string &onlineStatus) = 0; +}; +class DistributedObjectStore { +public: + virtual ~DistributedObjectStore(){}; + //描述:实例化一个数据对象存储, + static DistributedObjectStore *GetInstance(const std::string &bundleName = ""); + //描述:创建分布式数据对象,调用storage.CreateTable创建表,key是对象类型_sessionId + //返回值:SUCCESS成功,其他失败,错误码见storage + virtual DistributedObject *CreateObject(const std::string &sessionId) = 0; + virtual DistributedObject *CreateObject(const std::string &sessionId, uint32_t &status) = 0; + //描述:获取指定分布式数据对象的组网状态 + virtual uint32_t Get(const std::string &sessionId, DistributedObject **object) = 0; + //描述:删除分布式数据对象,调用storage.DeleteTable删除表,key在object中取 + //返回值:SUCCESS成功,其他失败,错误码见storage + virtual uint32_t DeleteObject(const std::string &sessionId) = 0; + //描述:监听对应对象变化(对端变化通知) + //返回值:SUCCESS成功,REPEAT_WATCH已经监听过 + virtual uint32_t Watch(DistributedObject *object, std::shared_ptr objectWatcher) = 0; + //描述:取消监听对应对象变化(对端变化通知) + //返回值:SUCCESS成功 + virtual uint32_t UnWatch(DistributedObject *object) = 0; + //描述:设置状态通知 + //返回值:SUCCESS成功 + virtual uint32_t SetStatusNotifier(std::shared_ptr notifier) = 0; + //描述:通知缓存状态 + virtual void NotifyCachedStatus(const std::string &sessionId) = 0; +}; +} // namespace OHOS::ObjectStore + +#endif // DISTRIBUTED_OBJECTSTORE_H diff --git a/distributeddatamgr/data_object_use_cases/include/objectstore_errors.h b/distributeddatamgr/data_object_use_cases/include/objectstore_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..6e2557f3d614728f3aa0c1f7ebff0b4e84cb686a --- /dev/null +++ b/distributeddatamgr/data_object_use_cases/include/objectstore_errors.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OBJECTSTORE_ERRORS_H +#define OBJECTSTORE_ERRORS_H + +#include + +namespace OHOS::ObjectStore { +constexpr uint32_t BASE_ERR_OFFSET = 1650; + +/* module defined errors */ +constexpr uint32_t SUCCESS = 0; +constexpr uint32_t ERR_DB_SET_PROCESS = BASE_ERR_OFFSET + 1; +constexpr uint32_t ERR_EXIST = BASE_ERR_OFFSET + 2; +constexpr uint32_t ERR_DATA_LEN = BASE_ERR_OFFSET + 3; +constexpr uint32_t ERR_NOMEM = BASE_ERR_OFFSET + 4; +constexpr uint32_t ERR_DB_NOT_INIT = BASE_ERR_OFFSET + 5; +constexpr uint32_t ERR_DB_GETKV_FAIL = BASE_ERR_OFFSET + 6; +constexpr uint32_t ERR_DB_NOT_EXIST = BASE_ERR_OFFSET + 7; +constexpr uint32_t ERR_DB_GET_FAIL = BASE_ERR_OFFSET + 8; +constexpr uint32_t ERR_DB_ENTRY_FAIL = BASE_ERR_OFFSET + 9; +constexpr uint32_t ERR_CLOSE_STORAGE = BASE_ERR_OFFSET + 10; +constexpr uint32_t ERR_NULL_OBJECT = BASE_ERR_OFFSET + 11; +constexpr uint32_t ERR_REGISTER = BASE_ERR_OFFSET + 12; +constexpr uint32_t ERR_NULL_OBJECTSTORE = BASE_ERR_OFFSET + 13; +constexpr uint32_t ERR_GET_OBJECT = BASE_ERR_OFFSET + 14; +constexpr uint32_t ERR_NO_OBSERVER = BASE_ERR_OFFSET + 15; +constexpr uint32_t ERR_UNRIGSTER = BASE_ERR_OFFSET + 16; +constexpr uint32_t ERR_SINGLE_DEVICE = BASE_ERR_OFFSET + 17; +constexpr uint32_t ERR_NULL_PTR = BASE_ERR_OFFSET + 18; +constexpr uint32_t ERR_PROCESSING = BASE_ERR_OFFSET + 19; +constexpr uint32_t ERR_RESULTSET = BASE_ERR_OFFSET + 20; +constexpr uint32_t ERR_INVALID_ARGS = BASE_ERR_OFFSET + 21; +} // namespace OHOS::ObjectStore + +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/appdatafwk/BUILD.gn b/distributeddatamgr/relational_store_use_cases/include/appdatafwk/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..688674b0392e4592fb422e9b625642575d6c0884 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/appdatafwk/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/relational_store/relational_store.gni") + +config("appdatafwk_config") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +config("appdatafwk_public_config") { + visibility = [ ":*" ] + include_dirs = [ "include" ] +} + +ohos_shared_library("native_appdatafwk") { + sources = + [ "${relational_store_native_path}/appdatafwk/src/shared_block.cpp" ] + + configs = [ ":appdatafwk_config" ] + + subsystem_name = "distributeddatamgr" + part_name = "relational_store" + + public_deps = [ + "//foundation/communication/ipc/interfaces/innerkits/ipc_core:ipc_core", + ] + + external_deps = [ + "c_utils:utils", + "hilog_native:libhilog", + ] + + public_configs = [ ":appdatafwk_public_config" ] +} diff --git a/distributeddatamgr/relational_store_use_cases/include/appdatafwk/include/logger.h b/distributeddatamgr/relational_store_use_cases/include/appdatafwk/include/logger.h new file mode 100644 index 0000000000000000000000000000000000000000..3cf9fb9d715ab5b12c2ca9db35d1e41edca8d080 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/appdatafwk/include/logger.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LOGGER_H +#define LOGGER_H + +#include "hilog/log.h" + +namespace OHOS { +namespace AppDataFwk { +static const OHOS::HiviewDFX::HiLogLabel APP_DATA_FWK_LABEL = { LOG_CORE, 0xD001650, "APP_DATA_FWK_NATIVE" }; + +#define LOG_DEBUG(...) ((void)OHOS::HiviewDFX::HiLog::Debug(APP_DATA_FWK_LABEL, __VA_ARGS__)) +#define LOG_INFO(...) ((void)OHOS::HiviewDFX::HiLog::Info(APP_DATA_FWK_LABEL, __VA_ARGS__)) +#define LOG_WARN(...) ((void)OHOS::HiviewDFX::HiLog::Warn(APP_DATA_FWK_LABEL, __VA_ARGS__)) +#define LOG_ERROR(...) ((void)OHOS::HiviewDFX::HiLog::Error(APP_DATA_FWK_LABEL, __VA_ARGS__)) +#define LOG_FATAL(...) ((void)OHOS::HiviewDFX::HiLog::Fatal(APP_DATA_FWK_LABEL, __VA_ARGS__)) +} // namespace AppDataFwk +} // namespace OHOS + +#endif // LOGGER_H \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/appdatafwk/include/shared_block.h b/distributeddatamgr/relational_store_use_cases/include/appdatafwk/include/shared_block.h new file mode 100644 index 0000000000000000000000000000000000000000..24916102928c947003dcea906e829c9d72cb3e34 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/appdatafwk/include/shared_block.h @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SHARED_BLOCK_H +#define SHARED_BLOCK_H + +#include + +#include +#include +#include "message_parcel.h" +#include "parcel.h" +#include "securec.h" + +namespace OHOS { +namespace AppDataFwk { +static const uint32_t INVALID_ROW_RECORD = 0xFFFFFFFF; +/** + * This class stores a set of rows from a database in a buffer, + * which is used as the set of query result. + */ +class SharedBlock { +public: + /* Cell Unit types. */ + enum { + CELL_UNIT_TYPE_NULL = 0, + CELL_UNIT_TYPE_INTEGER = 1, + CELL_UNIT_TYPE_FLOAT = 2, + CELL_UNIT_TYPE_STRING = 3, + CELL_UNIT_TYPE_BLOB = 4, + }; + + /* SharedBlock error types. */ + enum { + SHARED_BLOCK_OK = 0, + SHARED_BLOCK_BAD_VALUE = 1, + SHARED_BLOCK_NO_MEMORY = 2, + SHARED_BLOCK_INVALID_OPERATION = 3, + SHARED_BLOCK_ASHMEM_ERROR = 4, + SHARED_BLOCK_SET_PORT_ERROR = 5, + }; + + /* Cell Unit */ + struct CellUnit { + int32_t type; + union { + double doubleValue; + int64_t longValue; + struct { + uint32_t offset; + uint32_t size; + } stringOrBlobValue; + } cell; + } __attribute((packed)); + + /** + * SharedBlock constructor. + */ + SharedBlock(const std::string &name, sptr ashmem, size_t size, bool readOnly); + + /** + * SharedBlock constructor. + */ + ~SharedBlock(); + + /** + * Init current shared block. + */ + bool Init(); + + /** + * Create a shared block. + */ + static int Create(const std::string &name, size_t size, SharedBlock *&outSharedBlock); + + /** + * Clear current shared block. + */ + int Clear(); + + /** + * Set a shared block column. + */ + int SetColumnNum(uint32_t numColumns); + + /** + * Allocate a row unit and its directory. + */ + int AllocRow(); + + /** + * Release the value of the last row. + */ + int FreeLastRow(); + + /** + * Put blob data to the shared block. + */ + int PutBlob(uint32_t row, uint32_t column, const void *value, size_t Size); + + /** + * Put string data to the shared block. + */ + int PutString(uint32_t row, uint32_t column, const char *value, size_t sizeIncludingNull); + + /** + * Put long data to the shared block. + */ + int PutLong(uint32_t row, uint32_t column, int64_t value); + + /** + * Put Double data to the shared block. + */ + int PutDouble(uint32_t row, uint32_t column, double value); + + /** + * Put Null data to the shared block. + */ + int PutNull(uint32_t row, uint32_t column); + + /** + * Gets the cell unit at the specified row and column. + */ + CellUnit *GetCellUnit(uint32_t row, uint32_t column); + + /** + * Get string type data from cell unit. + */ + const char *GetCellUnitValueString(CellUnit *cellUnit, size_t *outSizeIncludingNull) + { + *outSizeIncludingNull = cellUnit->cell.stringOrBlobValue.size; + return static_cast( + OffsetToPtr(cellUnit->cell.stringOrBlobValue.offset, cellUnit->cell.stringOrBlobValue.size)); + } + + /** + * Get blob type data from cell unit. + */ + const void *GetCellUnitValueBlob(CellUnit *cellUnit, size_t *outSize) + { + *outSize = cellUnit->cell.stringOrBlobValue.size; + return OffsetToPtr(cellUnit->cell.stringOrBlobValue.offset, cellUnit->cell.stringOrBlobValue.size); + } + + /** + * The mHeader of the current result set. + */ + const void *GetHeader() + { + return mHeader; + } + + /** + * Size of the used byte in the block. + */ + size_t GetUsedBytes() + { + return mHeader->unusedOffset; + } + + /** + * The name of the current result set. + */ + std::string Name() + { + return mName; + } + + /** + * The size of the current result set. + */ + size_t Size() + { + return mSize; + } + + /** + * The row number of the current result set. + */ + uint32_t GetRowNum() + { + return mHeader->rowNums; + } + + /** + * The column number of the current result set. + */ + uint32_t GetColumnNum() + { + return mHeader->columnNums; + } + + int WriteMessageParcel(MessageParcel &parcel); + + static int ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block); + /** + * Write raw data in block. + */ + size_t SetRawData(const void *rawData, size_t size); + /** + * The fd of shared memory + */ + int GetFd() + { + if (ashmem_ == nullptr) { + return -1; + } + return ashmem_->GetAshmemFd(); + } + + uint32_t GetStartPos() + { + return mHeader->startPos_; + } + + uint32_t GetLastPos() + { + return mHeader->lastPos_; + } + + uint32_t GetBlockPos() + { + return mHeader->blockPos_; + } + + void SetStartPos(uint32_t startPos) + { + mHeader->startPos_ = startPos; + } + + void SetLastPos(uint32_t lastPos) + { + mHeader->lastPos_ = lastPos; + } + + void SetBlockPos(uint32_t blockPos) + { + mHeader->blockPos_ = blockPos; + } + +private: + std::string mName; + sptr ashmem_; + void *mData; + size_t mSize; + bool mReadOnly; + static const size_t ROW_OFFSETS_NUM = 100; + /** + * Default setting for SQLITE_MAX_COLUMN is 2000. + * We can set it at compile time to as large as 32767 + */ + static const size_t COL_MAX_NUM = 32767; + + struct SharedBlockHeader { + /* Offset of the lowest unused byte in the block. */ + uint32_t unusedOffset; + /* Offset of the first row group. */ + uint32_t firstRowGroupOffset; + /* Row numbers of the row group block. */ + uint32_t rowNums; + /* Column numbers of the row group block. */ + uint32_t columnNums; + /* start position of the current block. */ + uint32_t startPos_; + /* last position of the current block. */ + uint32_t lastPos_; + /* current position of the current block. */ + uint32_t blockPos_; + }; + + struct RowGroupHeader { + uint32_t rowOffsets[ROW_OFFSETS_NUM]; + uint32_t nextGroupOffset; + }; + + SharedBlockHeader *mHeader; + + /** + * Allocate a portion of the block. Returns the offset of the allocation. + * Returns 0 if there isn't enough space. + */ + uint32_t Alloc(size_t size, bool aligned = false); + + uint32_t *GetRowOffset(uint32_t row); + + uint32_t *AllocRowOffset(); + + int PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type); + + static int CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, + SharedBlock *&outSharedBlock); + + uint32_t OffsetFromPtr(void *ptr); + + void *OffsetToPtr(uint32_t offset, uint32_t bufferSize = 0); + + /** + * Convert utf8 string to utf16. + */ + static std::u16string ToUtf16(std::string str); + + /** + * Convert utf16 string to utf8. + */ + static std::string ToUtf8(std::u16string str16); +}; +} // namespace AppDataFwk +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/dataability/BUILD.gn b/distributeddatamgr/relational_store_use_cases/include/dataability/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..bd4c5c4367a42c852216b3d1a91df22aa08f25ff --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/dataability/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/relational_store/relational_store.gni") + +config("native_dataability_config") { + visibility = [ ":*" ] + + cflags = [ "-Wc99-designator" ] + cflags_cc = [ "-Wc99-designator" ] + include_dirs = [ + "include", + "${relational_store_native_path}/dataability/include", + "${relational_store_native_path}/dataability/src", + ] +} + +config("native_dataability_public_config") { + visibility = [ "//foundation/distributeddatamgr/relational_store:*" ] + include_dirs = [ "include" ] +} + +ohos_shared_library("native_dataability") { + part_name = "relational_store" + sources = [ + "${relational_store_native_path}/dataability/src/data_ability_predicates.cpp", + "${relational_store_native_path}/dataability/src/ishared_result_set.cpp", + "${relational_store_native_path}/dataability/src/ishared_result_set_proxy.cpp", + "${relational_store_native_path}/dataability/src/ishared_result_set_stub.cpp", + "${relational_store_native_path}/dataability/src/logger.h", + "${relational_store_native_path}/dataability/src/predicates_utils.cpp", + ] + + configs = [ ":native_dataability_config" ] + + external_deps = [ + "c_utils:utils", + "hilog_native:libhilog", + "ipc:ipc_core", + "relational_store:native_rdb", + ] + + public_configs = [ ":native_dataability_public_config" ] + + subsystem_name = "distributeddatamgr" +} diff --git a/distributeddatamgr/relational_store_use_cases/include/dataability/include/data_ability_predicates.h b/distributeddatamgr/relational_store_use_cases/include/dataability/include/data_ability_predicates.h new file mode 100644 index 0000000000000000000000000000000000000000..49ea9eb3b7260d86d50b9e3f39dbc20fe8bfab03 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/dataability/include/data_ability_predicates.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_DATD_ABILITY_PREDICATES_H +#define NATIVE_RDB_DATD_ABILITY_PREDICATES_H + +#include + +#include "abs_predicates.h" +#include "parcel.h" + +namespace OHOS { +namespace NativeRdb { +class DataAbilityPredicates : public AbsPredicates, public virtual OHOS::Parcelable { +public: + DataAbilityPredicates(); + explicit DataAbilityPredicates(std::string rawSelection); + explicit DataAbilityPredicates(OHOS::Parcel *source); + ~DataAbilityPredicates() override; + bool IsRawSelection() const; + bool GetJudgeSource() const; + bool Marshalling(OHOS::Parcel &parcel) const override; + static DataAbilityPredicates *Unmarshalling(OHOS::Parcel &parcel); + static bool result; + +private: + void MarshallingString(std::string value, OHOS::Parcel &parcel) const; + void MarshallingStringList(std::vector list, OHOS::Parcel &parcel) const; + + bool isRawSelection; + bool judgeSource; +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/dataability/include/ishared_result_set.h b/distributeddatamgr/relational_store_use_cases/include/dataability/include/ishared_result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..5361272c506c77589c0b2d21c90951ef853191b6 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/dataability/include/ishared_result_set.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATAABILITY_I_SHARED_RESULT_SET_H +#define DATAABILITY_I_SHARED_RESULT_SET_H +#include +#include "iremote_broker.h" +#include "abs_shared_result_set.h" +namespace OHOS::NativeRdb { +class ISharedResultSet : public AbsSharedResultSet, public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.NativeRdb.ISharedResultSet") + static std::shared_ptr ReadFromParcel(MessageParcel &parcel); + static sptr WriteToParcel(std::shared_ptr resultSet, MessageParcel &parcel); + +protected: + enum { + FUNC_GET_ROW_COUNT, + FUNC_GET_ALL_COLUMN_NAMES, + FUNC_ON_GO, + FUNC_CLOSE, + FUNC_GET_BLOB, + FUNC_GET_STRING, + FUNC_GET_INT, + FUNC_GET_LONG, + FUNC_GET_DOUBLE, + FUNC_IS_COLUMN_NULL, + FUNC_GO_TO, + FUNC_GO_TO_ROW, + FUNC_GO_TO_FISTR_ROW, + FUNC_GO_TO_LAST_ROW, + FUNC_GO_TO_NEXT_ROW, + FUNC_GO_TO_PREV_ROW, + FUNC_IS_AT_FIRST_ROW, + FUNC_IS_AT_LAST_ROW, + FUNC_IS_STARTED_ROW, + FUNC_IS_ENDED_ROW, + FUNC_IS_CLOSED, + FUNC_GET_COLUMN_COUNT, + FUNC_GET_COLUMN_INDEX, + FUNC_GET_COLUMN_NAME, + FUNC_GET_COLUMN_TYPE, + FUNC_GET_ROW_INDEX, + FUNC_BUTT + }; + +private: + static std::function(MessageParcel &parcel)> consumerCreator_; + static std::function(std::shared_ptr, MessageParcel &)> providerCreator_; +}; +} // namespace OHOS::NativeRdb + +#endif // DATAABILITY_I_SHARED_RESULT_SET_H diff --git a/distributeddatamgr/relational_store_use_cases/include/dataability/include/predicates_utils.h b/distributeddatamgr/relational_store_use_cases/include/dataability/include/predicates_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..fcad37c82305d37caa7448e363d5da814aed77ef --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/dataability/include/predicates_utils.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef NATIVE_RDB_PREDICATES_UTILS_H +#define NATIVE_RDB_PREDICATES_UTILS_H + +#include +#include + +#include "abs_predicates.h" +namespace OHOS { +namespace NativeRdb { +class PredicatesUtils { +public: + PredicatesUtils(); + ~PredicatesUtils() {} + static void SetWhereClauseAndArgs(AbsPredicates *predicates, std::string whereClause, + std::vector whereArgs); + static void SetAttributes(AbsPredicates *predicates, bool isDistinct, std::string index, std::string group, + std::string order, int limit, int offset); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/BUILD.gn b/distributeddatamgr/relational_store_use_cases/include/rdb/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2c0f22326aca748c74561d28c242d918e8ea3df4 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/BUILD.gn @@ -0,0 +1,160 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/relational_store/relational_store.gni") + +config("native_rdb_config") { + visibility = [ ":*" ] + + if (is_mingw || is_mac) { + include_dirs = [ + "mock/include", + "${relational_store_native_path}/rdb/mock/include", + "//commonlibrary/c_utils/base/include", + "include", + ] + } else { + include_dirs = [ + "include", + "//base/security/huks/frameworks/huks_standard/main/common/include", + "${relational_store_native_path}/rdb/include", + ] + } + + defines = [ + "RELATIONAL_STORE", + "SQLITE_HAS_CODEC", + ] + + if (relational_store_rdb_support_icu) { + include_dirs += [ + "//third_party/icu/icu4c/source", + "//third_party/icu/icu4c/source/i18n", + "//third_party/icu/icu4c/source/common", + ] + defines += [ "RDB_SUPPORT_ICU" ] + } + + if (is_mingw) { + defines += [ "WINDOWS_PLATFORM" ] + include_dirs += [ "//third_party/sqlite/include" ] + + libs = [ "//prebuilts/mingw-w64/ohos/linux-x86_64/clang-mingw/x86_64-w64-mingw32/lib/libws2_32.a" ] + + cflags_cc = [ "-std=c++17" ] + } else if (is_mac) { + defines += [ "MAC_PLATFORM" ] + include_dirs += [ "//third_party/sqlite/include" ] + cflags_cc = [ "-std=c++17" ] + } else { + defines += [ "SQLITE_DISTRIBUTE_RELATIONAL" ] + } +} + +config("native_rdb_public_config") { + visibility = [ "//foundation/distributeddatamgr/relational_store:*" ] + + if (is_mingw || is_mac) { + include_dirs = [ + "mock/include", + "include", + ] + } else { + include_dirs = [ + "include", + "//foundation/distributeddatamgr/distributedfile/interfaces/kits/js/src/mod_securitylabel", + ] + } + + defines = [ "SQLITE_HAS_CODEC" ] +} + +ohos_shared_library("native_rdb") { + part_name = "relational_store" + sources = [ + "${relational_store_native_path}/rdb/src/abs_predicates.cpp", + "${relational_store_native_path}/rdb/src/abs_rdb_predicates.cpp", + "${relational_store_native_path}/rdb/src/abs_result_set.cpp", + "${relational_store_native_path}/rdb/src/base_transaction.cpp", + "${relational_store_native_path}/rdb/src/base_transaction.h", + "${relational_store_native_path}/rdb/src/logger.h", + "${relational_store_native_path}/rdb/src/rdb_helper.cpp", + "${relational_store_native_path}/rdb/src/rdb_predicates.cpp", + "${relational_store_native_path}/rdb/src/rdb_store_config.cpp", + "${relational_store_native_path}/rdb/src/rdb_store_impl.cpp", + "${relational_store_native_path}/rdb/src/sqlite_config.cpp", + "${relational_store_native_path}/rdb/src/sqlite_connection.cpp", + "${relational_store_native_path}/rdb/src/sqlite_connection_pool.cpp", + "${relational_store_native_path}/rdb/src/sqlite_database_utils.cpp", + "${relational_store_native_path}/rdb/src/sqlite_global_config.cpp", + "${relational_store_native_path}/rdb/src/sqlite_sql_builder.cpp", + "${relational_store_native_path}/rdb/src/sqlite_statement.cpp", + "${relational_store_native_path}/rdb/src/sqlite_utils.cpp", + "${relational_store_native_path}/rdb/src/step_result_set.cpp", + "${relational_store_native_path}/rdb/src/store_session.cpp", + "${relational_store_native_path}/rdb/src/string_utils.cpp", + "${relational_store_native_path}/rdb/src/value_object.cpp", + "${relational_store_native_path}/rdb/src/values_bucket.cpp", + ] + + configs = [ ":native_rdb_config" ] + + deps = [ + "//third_party/icu/icu4c:shared_icui18n", + "//third_party/icu/icu4c:shared_icuuc", + ] + + if (is_mingw) { + deps += [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog_windows", + "//third_party/sqlite:sqlite_sdk", + ] + } else if (is_mac) { + deps += [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog_mac", + "//third_party/sqlite:sqlite_sdk", + ] + } else { + deps += [ "//third_party/sqlite:sqlite" ] + ldflags = [ "-Wl,--exclude-libs,ALL" ] + + sources += [ + "${relational_store_native_path}/rdb/src/abs_shared_result_set.cpp", + "${relational_store_native_path}/rdb/src/rdb_security_manager.cpp", + "${relational_store_native_path}/rdb/src/result_set_proxy.cpp", + "${relational_store_native_path}/rdb/src/security_policy.cpp", + "${relational_store_native_path}/rdb/src/share_block.cpp", + "${relational_store_native_path}/rdb/src/shared_block_serializer_info.cpp", + "${relational_store_native_path}/rdb/src/sqlite_shared_result_set.cpp", + ] + public_deps = [ + "${relational_store_innerapi_path}/appdatafwk:native_appdatafwk", + "//base/security/huks/frameworks/huks_standard/main/os_dependency:libhuks_os_dependency_standard_static", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner", + ] + + external_deps = [ + "c_utils:utils", + "hilog_native:libhilog", + "hitrace_native:hitrace_meter", + "hitrace_native:libhitracechain", + "huks:libhukssdk", + "ipc:ipc_core", + ] + } + + public_configs = [ ":native_rdb_public_config" ] + + subsystem_name = "distributeddatamgr" +} diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_predicates.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_predicates.h new file mode 100644 index 0000000000000000000000000000000000000000..95c13a17cb6d07cb538015d453932e09f00d5f4b --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_predicates.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_ABSPREDICATES_H +#define NATIVE_RDB_ABSPREDICATES_H + +#include +#include + +namespace OHOS { +namespace NativeRdb { +class AbsPredicates { +public: + AbsPredicates(); + virtual ~AbsPredicates(); + + enum JoinType { + INNER, + LEFT, + CROSS + }; + + std::string GetWhereClause() const; + void SetWhereClause(std::string whereClause); + std::vector GetWhereArgs() const; + void SetWhereArgs(std::vector whereArgs); + std::string GetOrder() const; + void SetOrder(std::string order); + int GetLimit() const; + int GetOffset() const; + bool IsDistinct() const; + std::string GetGroup() const; + std::string GetIndex() const; + bool IsNeedAnd() const; + bool IsSorted() const; + +public: + virtual void Clear(); + virtual AbsPredicates *EqualTo(std::string field, std::string value); + virtual AbsPredicates *NotEqualTo(std::string field, std::string value); + virtual AbsPredicates *BeginWrap(); + virtual AbsPredicates *EndWrap(); + virtual AbsPredicates *Or(); + virtual AbsPredicates *And(); + virtual AbsPredicates *Contains(std::string field, std::string value); + virtual AbsPredicates *BeginsWith(std::string field, std::string value); + virtual AbsPredicates *EndsWith(std::string field, std::string value); + virtual AbsPredicates *IsNull(std::string field); + virtual AbsPredicates *IsNotNull(std::string field); + virtual AbsPredicates *Like(std::string field, std::string value); + virtual AbsPredicates *Glob(std::string field, std::string value); + virtual AbsPredicates *Between(std::string field, std::string low, std::string high); + virtual AbsPredicates *NotBetween(std::string field, std::string low, std::string high); + virtual AbsPredicates *GreaterThan(std::string field, std::string value); + virtual AbsPredicates *LessThan(std::string field, std::string value); + virtual AbsPredicates *GreaterThanOrEqualTo(std::string field, std::string value); + virtual AbsPredicates *LessThanOrEqualTo(std::string field, std::string value); + virtual AbsPredicates *OrderByAsc(std::string field); + virtual AbsPredicates *OrderByDesc(std::string field); + virtual AbsPredicates *Distinct(); + virtual AbsPredicates *Limit(int value); + virtual AbsPredicates *Offset(int rowOffset); + virtual AbsPredicates *GroupBy(std::vector fields); + virtual AbsPredicates *IndexedBy(std::string indexName); + virtual AbsPredicates *In(std::string field, std::vector values); + virtual AbsPredicates *NotIn(std::string field, std::vector values); + +private: + std::string whereClause; + std::vector whereArgs; + std::string order; + std::string group; + std::string index; + int limit; + int offset; + bool distinct; + bool isNeedAnd; + bool isSorted; + + void Initial(); + bool CheckParameter(std::string methodName, std::string field, std::initializer_list args) const; + std::string RemoveQuotes(std::string source) const; + std::string Normalized(std::string source); + void CheckIsNeedAnd(); + void AppendWhereClauseWithInOrNotIn(std::string methodName, std::string field, + std::vector replaceValues); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_rdb_predicates.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_rdb_predicates.h new file mode 100644 index 0000000000000000000000000000000000000000..4e3c45c7bed1181818c1f007ff5209060617de62 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_rdb_predicates.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef NATIVE_RDB_ABSRDBPREDICATES_H +#define NATIVE_RDB_ABSRDBPREDICATES_H + +#include "abs_predicates.h" +#include "rdb_types.h" + +namespace OHOS::NativeRdb { +class AbsRdbPredicates : public AbsPredicates { +public: + explicit AbsRdbPredicates(std::string tableName); + + ~AbsRdbPredicates() override {} + + void Clear() override; + + std::string ToString() const; + + std::string GetTableName() const; + + AbsRdbPredicates *InDevices(std::vector& devices); + + AbsRdbPredicates *InAllDevices(); + + AbsRdbPredicates* EqualTo(std::string field, std::string value) override; + AbsRdbPredicates* NotEqualTo(std::string field, std::string value) override; + AbsRdbPredicates* And() override; + AbsRdbPredicates* Or() override; + AbsRdbPredicates* OrderByAsc(std::string field) override; + AbsRdbPredicates* OrderByDesc(std::string field) override; + + const DistributedRdb::RdbPredicates& GetDistributedPredicates() const; + + virtual void InitialParam(); + virtual std::vector GetJoinTypes(); + virtual void SetJoinTypes(const std::vector joinTypes); + virtual std::vector GetJoinTableNames(); + virtual void SetJoinTableNames(const std::vector joinTableNames); + virtual std::vector GetJoinConditions(); + virtual void SetJoinConditions(const std::vector joinConditions); + virtual std::string GetJoinClause() const; + virtual int GetJoinCount() const; + virtual void SetJoinCount(int joinCount); + +protected: + std::vector joinTypes; + std::vector joinTableNames; + std::vector joinConditions; + int joinCount = 0; + +private: + std::string tableName; + mutable DistributedRdb::RdbPredicates predicates_; +}; +} // namespace OHOS::NativeRdb + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_result_set.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..b530925efc7f9a8eae0c63a671024fa0f59a0fb2 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_result_set.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_ABS_RESULT_SET_H +#define NATIVE_RDB_ABS_RESULT_SET_H + +#include +#include +#include +#include + +#include "result_set.h" + +namespace OHOS { +namespace NativeRdb { +class AbsResultSet : public ResultSet { +public: + AbsResultSet(); + virtual ~AbsResultSet(); + int GetRowCount(int &count) override; + int GetAllColumnNames(std::vector &columnNames) override; + int GetBlob(int columnIndex, std::vector &blob) override; + int GetString(int columnIndex, std::string &value) override; + int GetInt(int columnIndex, int &value) override; + int GetLong(int columnIndex, int64_t &value) override; + int GetDouble(int columnIndex, double &value) override; + int IsColumnNull(int columnIndex, bool &isNull) override; + int GoToRow(int position) override; + int GetColumnType(int columnIndex, ColumnType &columnType) override; + int GetRowIndex(int &position) const override; + int GoTo(int offset) override; + int GoToFirstRow() override; + int GoToLastRow() override; + int GoToNextRow() override; + int GoToPreviousRow() override; + int IsAtFirstRow(bool &result) const override; + int IsAtLastRow(bool &result) override; + int IsStarted(bool &result) const override; + int IsEnded(bool &result) override; + int GetColumnCount(int &count) override; + int GetColumnIndex(const std::string &columnName, int &columnIndex) override; + int GetColumnName(int columnIndex, std::string &columnName) override; + bool IsClosed() const override; + int Close() override; + +protected: + std::map columnMap_; + // The default position of the result set + static const int INIT_POS = -1; + /* + * The value can be in the range [-1 ~ n], where -1 represents the start flag position and N represents the data end + * flag position, and [0, n-1] represents the real data index. + */ + int rowPos_; + std::vector columnNames_; + // Indicates whether the result set is closed + bool isClosed; +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_shared_result_set.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_shared_result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..616f729f99cadffc787779d1f6c72a79d4965faa --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/abs_shared_result_set.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_ABS_SHARED_RESULT_SET_H +#define NATIVE_RDB_ABS_SHARED_RESULT_SET_H + +#include +#include +#include +#include + +#include "abs_result_set.h" +#include "message_parcel.h" +#include "parcel.h" +#include "shared_block.h" +#include "shared_result_set.h" + +namespace OHOS { +namespace NativeRdb { +class AbsSharedResultSet : public AbsResultSet, public SharedResultSet { +public: + AbsSharedResultSet(); + explicit AbsSharedResultSet(std::string name); + virtual ~AbsSharedResultSet(); + int GetBlob(int columnIndex, std::vector &blob) override; + int GetString(int columnIndex, std::string &value) override; + int GetInt(int columnIndex, int &value) override; + int GetLong(int columnIndex, int64_t &value) override; + int GetDouble(int columnIndex, double &value) override; + int IsColumnNull(int columnIndex, bool &isNull) override; + int GetColumnType(int columnIndex, ColumnType &columnType) override; + int GoToRow(int position) override; + int GetAllColumnNames(std::vector &columnNames) override; + int GetRowCount(int &count) override; + AppDataFwk::SharedBlock *GetBlock() const override; + bool OnGo(int oldRowIndex, int newRowIndex) override; + void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) override; + virtual void SetBlock(AppDataFwk::SharedBlock *block); + int Close() override; + bool HasBlock() const; + +protected: + int CheckState(int columnIndex); + void ClearBlock(); + void ClosedBlock(); + virtual void Finalize(); + + friend class ISharedResultSetStub; + friend class ISharedResultSetProxy; + bool Unmarshalling(MessageParcel &parcel); + bool Marshalling(MessageParcel &parcel); + +private: + // The default position of the cursor + static const int INIT_POS = -1; + static const size_t DEFAULT_BLOCK_SIZE = 2 * 1024 * 1024; + + // The SharedBlock owned by this AbsSharedResultSet + AppDataFwk::SharedBlock *sharedBlock_ = nullptr; +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_errno.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_errno.h new file mode 100644 index 0000000000000000000000000000000000000000..1e1f72ac2b809ad06e20002fca5a63f6ce61d013 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_errno.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_ERRNO_H +#define NATIVE_RDB_RDB_ERRNO_H + +namespace OHOS { +namespace NativeRdb { + +constexpr int E_OK = 0; +constexpr int E_BASE = 1000; +constexpr int E_ERROR = (E_BASE + 1); +constexpr int E_CANNOT_UPDATE_READONLY = (E_BASE + 2); +constexpr int E_REMOVE_FILE = (E_BASE + 3); +constexpr int E_EMPTY_FILE_NAME = (E_BASE + 4); +constexpr int E_EMPTY_TABLE_NAME = (E_BASE + 5); +constexpr int E_EMPTY_VALUES_BUCKET = (E_BASE + 6); +constexpr int E_INVALID_STATEMENT = (E_BASE + 7); +constexpr int E_INVALID_COLUMN_INDEX = (E_BASE + 8); +constexpr int E_INVALID_COLUMN_TYPE = (E_BASE + 9); +constexpr int E_INVALID_COLUMN_NAME = (E_BASE + 10); +constexpr int E_QUERY_IN_EXECUTE = (E_BASE + 11); +constexpr int E_TRANSACTION_IN_EXECUTE = (E_BASE + 12); +constexpr int E_EXECUTE_IN_STEP_QUERY = (E_BASE + 13); +constexpr int E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14); +constexpr int E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15); +constexpr int E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16); +constexpr int E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17); +constexpr int E_NO_ROW_IN_QUERY = (E_BASE + 18); +constexpr int E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19); +constexpr int E_INVALID_OBJECT_TYPE = (E_BASE + 20); +constexpr int E_INVALID_CONFLICT_FLAG = (E_BASE + 21); +constexpr int E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22); +constexpr int E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23); +constexpr int E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24); +constexpr int E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25); +constexpr int E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26); +constexpr int E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27); +constexpr int E_STATEMENT_NOT_PREPARED = (E_BASE + 28); +constexpr int E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29); +constexpr int E_STEP_RESULT_CLOSED = (E_BASE + 30); +constexpr int E_RELATIVE_PATH = (E_BASE + 31); +constexpr int E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32); +constexpr int E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33); +constexpr int E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34); +constexpr int E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35); +constexpr int E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36); +constexpr int E_CREATE_FOLDER_FAIL = (E_BASE + 37); +constexpr int E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38); +constexpr int E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39); +constexpr int E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40); +constexpr int E_NOT_SUPPORT = (E_BASE + 41); +constexpr int E_INVALID_PARCEL = (E_BASE + 42); +constexpr int E_INVALID_FILE_PATH = (E_BASE + 43); +constexpr int E_SET_PERSIST_WAL = (E_BASE + 44); +constexpr int E_DB_NOT_EXIST = (E_BASE + 45); +} // namespace NativeRdb +} // namespace OHOS + +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_helper.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..640b235a81df6a04e902591d3fc9d1019f1c042d --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_helper.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_HELPER_H +#define NATIVE_RDB_RDB_HELPER_H + +#include +#include +#include +#include "rdb_open_callback.h" +#include "rdb_store.h" +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +class RdbHelper final { +public: + static std::shared_ptr GetRdbStore( + const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode); + static int DeleteRdbStore(const std::string &path); + static void ClearCache(); + +private: + static int ProcessOpenCallback( + RdbStore &rdbStore, const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback); + static std::mutex mutex_; + static std::map> storeCache_; +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_open_callback.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_open_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..74c1b75e7f42aa80fee7cf9a4f04c6285ec059f0 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_open_callback.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_OPEN_CALLBACK_H +#define NATIVE_RDB_RDB_OPEN_CALLBACK_H + +#include "rdb_store.h" + +namespace OHOS { +namespace NativeRdb { + +class RdbOpenCallback { +public: + /** + * Called when the database associate whit this RdbStore is created with the first time. + * This is where the creation of tables and insert the initial data of tables should happen. + * + * param store The RdbStore object. + */ + virtual int OnCreate(RdbStore &rdbStore) = 0; + + /** + * Called when the database associate whit this RdbStore needs to be upgrade. + * + * param store The RdbStore object. + * param oldVersion The old database version. + * param newVersion The new database version. + */ + virtual int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) = 0; + + /** + * Called when the database associate whit this RdbStore needs to be downgrade. + * + * param store The RdbStore object. + * param oldVersion The old database version. + * param newVersion The new database version. + */ + virtual int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) + { + return 0; + } + + /** + * Called when the RdbStore has been opened. + * + * param store The RdbStore object. + */ + virtual int OnOpen(RdbStore &rdbStore) + { + return 0; + } + + virtual int onCorruption(std::string databaseFile) + { + return 0; + } +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_predicates.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_predicates.h new file mode 100644 index 0000000000000000000000000000000000000000..4eac92d2b029510736847f6abe5fc056a7930e94 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_predicates.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDBPREDICATES_H +#define NATIVE_RDB_RDBPREDICATES_H + + +#include "abs_rdb_predicates.h" + +namespace OHOS { +namespace NativeRdb { +class RdbPredicates : public AbsRdbPredicates { +public: + explicit RdbPredicates(std::string tableName); + ~RdbPredicates() override {} + + std::string GetJoinClause() const override; + RdbPredicates *CrossJoin(std::string tableName); + RdbPredicates *InnerJoin(std::string tableName); + RdbPredicates *LeftOuterJoin(std::string tableName); + RdbPredicates *Using(std::vector fields); + RdbPredicates *On(std::vector clauses); + +private: + std::string ProcessJoins() const; + std::string GetGrammar(int type) const; + RdbPredicates *Join(int join, std::string tableName); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_store.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_store.h new file mode 100644 index 0000000000000000000000000000000000000000..c8d06d54e6b7bdafb8ac4b57cf6c09f14fe2cc58 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_store.h @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_STORE_H +#define NATIVE_RDB_RDB_STORE_H + +#include +#include +#include + +#include "abs_rdb_predicates.h" +#include "abs_shared_result_set.h" +#include "result_set.h" +#include "value_object.h" +#include "values_bucket.h" +#include "rdb_types.h" + +namespace OHOS::NativeRdb { +enum class ConflictResolution { + ON_CONFLICT_NONE = 0, + ON_CONFLICT_ROLLBACK, + ON_CONFLICT_ABORT, + ON_CONFLICT_FAIL, + ON_CONFLICT_IGNORE, + ON_CONFLICT_REPLACE, +}; + +class RdbStore { +public: + using SyncOption = DistributedRdb::SyncOption; + using SyncCallback = DistributedRdb::SyncCallback; + using SubscribeMode = DistributedRdb::SubscribeMode; + using SubscribeOption = DistributedRdb::SubscribeOption; + using DropOption = DistributedRdb::DropOption; + using RdbStoreObserver = DistributedRdb::RdbStoreObserver; + + virtual ~RdbStore() {} + virtual int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) = 0; + virtual int BatchInsert(int64_t &outInsertNum, const std::string &table, + const std::vector &initialBatchValues) = 0; + virtual int Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) = 0; + virtual int InsertWithConflictResolution(int64_t &outRowId, const std::string &table, + const ValuesBucket &initialValues, + ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; + virtual int Update(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause = "", + const std::vector &whereArgs = std::vector()) = 0; + virtual int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause = "", const std::vector &whereArgs = std::vector(), + ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; + virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause = "", + const std::vector &whereArgs = std::vector()) = 0; + virtual std::unique_ptr Query(int &errCode, bool distinct, const std::string &table, + const std::vector &columns, const std::string &selection = "", + const std::vector &selectionArgs = std::vector(), const std::string &groupBy = "", + const std::string &having = "", const std::string &orderBy = "", const std::string &limit = "") = 0; + virtual std::unique_ptr QuerySql( + const std::string &sql, const std::vector &selectionArgs = std::vector()) = 0; + virtual std::unique_ptr QueryByStep( + const std::string &sql, const std::vector &selectionArgs = std::vector()) = 0; + virtual int ExecuteSql( + const std::string &sql, const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteAndGetString(std::string &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int Backup(const std::string databasePath, const std::vector destEncryptKey) = 0; + virtual int Attach( + const std::string &alias, const std::string &pathName, const std::vector destEncryptKey) = 0; + + virtual int Count(int64_t &outValue, const AbsRdbPredicates &predicates) = 0; + virtual std::unique_ptr Query( + const AbsRdbPredicates &predicates, const std::vector columns) = 0; + virtual std::unique_ptr QueryByStep( + const AbsRdbPredicates &predicates, const std::vector columns) = 0; + virtual std::shared_ptr RemoteQuery(const std::string &device, + const AbsRdbPredicates &predicates, const std::vector &columns) = 0; + virtual int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) = 0; + virtual int Delete(int &deletedRows, const AbsRdbPredicates &predicates) = 0; + + virtual int GetVersion(int &version) = 0; + virtual int SetVersion(int version) = 0; + virtual int BeginTransaction() = 0; + virtual int RollBack() = 0; + virtual int Commit() = 0; + virtual int MarkAsCommit() = 0; + virtual int EndTransaction() = 0; + virtual bool IsInTransaction() = 0; + virtual std::string GetPath() = 0; + virtual bool IsHoldingConnection() = 0; + virtual bool IsOpen() const = 0; + virtual bool IsReadOnly() const = 0; + virtual bool IsMemoryRdb() const = 0; + virtual int Restore(const std::string backupPath, const std::vector &newKey) = 0; + virtual int ChangeDbFileForRestore(const std::string newPath, const std::string backupPath, + const std::vector &newKey) = 0; + + virtual bool SetDistributedTables(const std::vector& tables) = 0; + + virtual std::string ObtainDistributedTableName(const std::string& device, const std::string& table) = 0; + + virtual bool Sync(const SyncOption& option, const AbsRdbPredicates& predicate, const SyncCallback& callback) = 0; + + virtual bool Subscribe(const SubscribeOption& option, RdbStoreObserver *observer) = 0; + + virtual bool UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer) = 0; + + // user must use UDID + virtual bool DropDeviceData(const std::vector& devices, const DropOption& option) = 0; +}; +} // namespace OHOS::NativeRdb +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_store_config.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_store_config.h new file mode 100644 index 0000000000000000000000000000000000000000..0aa89dce1f960f72c25177dd373ad89f4f09eaea --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/rdb_store_config.h @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_STORE_CONFIG_H +#define NATIVE_RDB_RDB_STORE_CONFIG_H + +#include +#include +#include + +namespace OHOS::NativeRdb { +// indicates the type of the storage +enum class StorageMode { + MODE_MEMORY = 101, + MODE_DISK, +}; + +enum class JournalMode { + MODE_DELETE, + MODE_TRUNCATE, + MODE_PERSIST, + MODE_MEMORY, + MODE_WAL, + MODE_OFF, +}; + +enum class SyncMode { + MODE_OFF, + MODE_NORMAL, + MODE_FULL, + MODE_EXTRA, +}; + +enum class DatabaseFileType { + NORMAL, + BACKUP, + CORRUPT, +}; + +enum class SecurityLevel : int32_t { + S1 = 1, + S2, + S3, + S4, + LAST +}; + + +using DistributedType = OHOS::DistributedRdb::RdbDistributedType; + +class RdbStoreConfig { +public: + RdbStoreConfig(const RdbStoreConfig &config); + RdbStoreConfig(const std::string &path, StorageMode storageMode = StorageMode::MODE_DISK, bool readOnly = false, + const std::vector &encryptKey = std::vector(), const std::string &journalMode = "", + const std::string &syncMode = "", const std::string &databaseFileType = "", + SecurityLevel securityLevel = SecurityLevel::LAST, bool isCreateNecessary = true); + ~RdbStoreConfig(); + std::string GetName() const; + std::string GetPath() const; + StorageMode GetStorageMode() const; + std::string GetJournalMode() const; + std::string GetSyncMode() const; + bool IsReadOnly() const; + bool IsMemoryRdb() const; + std::string GetDatabaseFileType() const; + SecurityLevel GetSecurityLevel() const; + void SetEncryptStatus(const bool status); + bool IsEncrypt() const; + bool IsCreateNecessary() const; + // set the journal mode, if not set, the default mode is WAL + void SetName(std::string name); + void SetJournalMode(JournalMode journalMode); + void SetPath(std::string path); + void SetReadOnly(bool readOnly); + void SetStorageMode(StorageMode storageMode); + void SetDatabaseFileType(DatabaseFileType type); + void SetSecurityLevel(SecurityLevel secLevel); + void SetCreateNecessary(bool isCreateNecessary); + + // distributed rdb + int SetBundleName(const std::string &bundleName); + std::string GetBundleName() const; + int SetDistributedType(DistributedType type); + DistributedType GetDistributedType() const; + void SetModuleName(const std::string& moduleName); + std::string GetModuleName() const; + void SetServiceName(const std::string& serviceName); + void SetArea(int32_t area); + int32_t GetArea() const; + std::string GetUri() const; + void SetUri(const std::string& uri); + std::string GetReadPermission() const; + void SetReadPermission(const std::string& permission); + std::string GetWritePermission() const; + void SetWritePermission(const std::string& permission); + + static std::string GetJournalModeValue(JournalMode journalMode); + static std::string GetSyncModeValue(SyncMode syncMode); + static std::string GetDatabaseFileTypeValue(DatabaseFileType databaseFileType); + +private: + std::string name; + std::string path; + StorageMode storageMode; + std::string journalMode; + std::string syncMode; + bool readOnly; + std::string databaseFileType; + + // distributed rdb + DistributedType distributedType_ = DistributedRdb::RdbDistributedType::RDB_DEVICE_COLLABORATION; + int32_t area_ = 0; + std::string bundleName_; + std::string moduleName_; + + bool isEncrypt_ = false; + SecurityLevel securityLevel = SecurityLevel::LAST; + std::string uri_; + std::string readPermission_; + std::string writePermission_; + bool isCreateNecessary_; +}; +} // namespace OHOS::NativeRdb + +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/result_set.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..f4845b4a372de6f1cc28bd9191c337c73db902ee --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/result_set.h @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RESULT_SET_H +#define NATIVE_RDB_RESULT_SET_H + +#include +#include +namespace OHOS { +namespace NativeRdb { + +/* Value returned by getColumnType(int) */ +enum class ColumnType { + TYPE_NULL = 0, + TYPE_INTEGER, + TYPE_FLOAT, + TYPE_STRING, + TYPE_BLOB, +}; + +class ResultSet { +public: + enum { + CMD_GET_ALL_COLUMN_NAMES, + CMD_GET_COLUMN_COUNT, + CMD_GET_COLUMN_TYPE, + CMD_GET_COLUMN_INDEX, + CMD_GET_COLUMN_NAME, + CMD_GET_ROW_COUNT, + CMD_GET_ROW_INDEX, + CMD_GO_TO, + CMD_GO_TO_ROW, + CMD_GO_TO_FIRST_ROW, + CMD_GO_TO_LAST_ROW, + CMD_GO_TO_NEXT_ROW, + CMD_GO_TO_PREV_ROW, + CMD_IS_ENDED_ROW, + CMD_IS_STARTED_ROW, + CMD_IS_AT_FIRST_ROW, + CMD_IS_AT_LAST_ROW, + CMD_GET_BLOB, + CMD_GET_STRING, + CMD_GET_INT, + CMD_GET_LONG, + CMD_GET_DOUBLE, + CMD_IS_COLUMN_NULL, + CMD_IS_CLOSED, + CMD_CLOSE, + CMD_MAX + }; + + virtual ~ResultSet() {} + + /** + * Returns a string array holding the names of all of the columns in the + * result set. + * + * return the names of the columns contains in this query result. + */ + virtual int GetAllColumnNames(std::vector &columnNames) = 0; + + /** + * Return the total number of columns + * + * return the number of columns + */ + virtual int GetColumnCount(int &count) = 0; + + /** + * Returns data type of the given column's value. + * + * param columnIndex the zero-based index of the target column. + * return column value type. + */ + virtual int GetColumnType(int columnIndex, ColumnType &columnType) = 0; + + /** + * Returns the zero-based index for the given column name. + * + * param columnName the name of the column. + * return the column index for the given column, or -1 if + * the column does not exist. + */ + virtual int GetColumnIndex(const std::string &columnName, int &columnIndex) = 0; + + /** + * Returns the column name at the given column index. + * + * param columnIndex the zero-based index. + * return the column name for the given index. + */ + virtual int GetColumnName(int columnIndex, std::string &columnName) = 0; + + /** + * return the numbers of rows in the result set. + */ + virtual int GetRowCount(int &count) = 0; + + /** + * Returns the current position of the cursor in the result set. + * The value is zero-based. When the result set is first returned the cursor + * will be at position -1, which is before the first row. + * After the last row is returned another call to next() will leave the cursor past + * the last entry, at a position of count(). + * + * return the current cursor position. + */ + virtual int GetRowIndex(int &position) const = 0; + + /** + * Move the cursor a relative amount from current position. Positive offset move forward, + * negative offset move backward. + * + * param offset the offset to be applied from the current position. + * return whether the requested move succeeded. + */ + virtual int GoTo(int offset) = 0; + + /** + * Move the cursor to an absolute position. + * + * param position the zero-based position to move to. + * return whether the requested move succeeded. + */ + virtual int GoToRow(int position) = 0; + + /** + * Move the cursor to the first row. + * + * return whether the requested move succeeded. + */ + virtual int GoToFirstRow() = 0; + + /** + * Move the cursor to the last row. + * + * return whether the requested move succeeded. + */ + virtual int GoToLastRow() = 0; + + /** + * Move the cursor to the next row. + * + * return whether the requested move succeeded. + */ + virtual int GoToNextRow() = 0; + + /** + * Move the cursor to the previous row. + * + * return whether the requested move succeeded. + */ + virtual int GoToPreviousRow() = 0; + + /** + * Returns whether the cursor is pointing to the position after the last + * row. + * + * return whether the cursor is before the first row. + */ + virtual int IsEnded(bool &result) = 0; + + /** + * Returns whether the cursor is pointing to the position before the first + * row. + * + * return whether the cursor is before the first row. + */ + virtual int IsStarted(bool &result) const = 0; + + /** + * Returns whether the cursor is pointing to the first row. + * + * return whether the cursor is pointing at the first entry. + */ + virtual int IsAtFirstRow(bool &result) const = 0; + + /** + * Returns whether the cursor is pointing to the last row. + * + * return whether the cursor is pointing at the last entry. + */ + virtual int IsAtLastRow(bool &result) = 0; + + /** + * Returns the value of the requested column as a byte array. + * + * param columnIndex the zero-based index of the target column. + * return the value of the requested column as a byte array. + */ + virtual int GetBlob(int columnIndex, std::vector &blob) = 0; + + /** + * Returns the value of the requested column as a String. + * + * param columnIndex the zero-based index of the target column. + * return the value of the requested column as a String. + */ + virtual int GetString(int columnIndex, std::string &value) = 0; + + /** + * Returns the value of the requested column as a int. + * + * param columnIndex the zero-based index of the target column. + * return the value of the requested column as a int. + */ + virtual int GetInt(int columnIndex, int &value) = 0; + + /** + * Returns the value of the requested column as a long. + * + * param columnIndex the zero-based index of the target column. + * return the value of the requested column as a long. + */ + virtual int GetLong(int columnIndex, int64_t &value) = 0; + + /** + * Returns the value of the requested column as a double. + * + * param columnIndex the zero-based index of the target column. + * return the value of the requested column as a double. + */ + virtual int GetDouble(int columnIndex, double &value) = 0; + + /** + * Whether the value of the requested column is null. + * + * param columnIndex the zero-based index of the target column. + * return whether the column value is null. + */ + virtual int IsColumnNull(int columnIndex, bool &isNull) = 0; + + /** + * Return true if the result set is closed. + * + * return true if the result set is closed. + */ + virtual bool IsClosed() const = 0; + + /** + * Closes the result set, releasing all of its resources and making it + * completely invalid. + */ + virtual int Close() = 0; +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/shared_result_set.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/shared_result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..49483ccb5e57c436568bafeb9f4d413e8d1d1cdd --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/shared_result_set.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_SHARED_RESULT_SET_H +#define NATIVE_RDB_SHARED_RESULT_SET_H + +#include +#include "shared_block.h" + +namespace OHOS { +namespace NativeRdb { +class SharedResultSet { +public: + SharedResultSet() {} + ~SharedResultSet() {} + /** + * Obtains a block from the {@link SharedResultSet} + */ + virtual AppDataFwk::SharedBlock *GetBlock() const = 0; + /** + * Adds the data of a {@code SharedResultSet} to a {@link SharedBlock} + */ + virtual void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) = 0; + /** + * Called when the position of the result set changes + */ + virtual bool OnGo(int oldRowIndex, int newRowIndex) = 0; +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/sqlite_database_utils.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/sqlite_database_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..88fdd4fe5382c7c50da7df4d7edec5d73836b2c6 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/sqlite_database_utils.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_SQLITE_DATABASE_UTILS_H +#define NATIVE_RDB_SQLITE_DATABASE_UTILS_H + +#include +#include +#include + +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +enum Type { + STATEMENT_SELECT = 1, + STATEMENT_UPDATE = 2, + STATEMENT_ATTACH = 3, + STATEMENT_DETACH = 4, + STATEMENT_BEGIN = 5, + STATEMENT_COMMIT = 6, + STATEMENT_ROLLBACK = 7, + STATEMENT_PRAGMA = 8, + STATEMENT_DDL = 9, + STATEMENT_OTHER = 99, + DATA_TYPE_BOOLEAN = 5, + DATA_TYPE_BLOB = 4, + DATA_TYPE_STRING = 3, + DATA_TYPE_FLOAT = 2, + DATA_TYPE_INTEGER = 1, + DATA_TYPE_NULL = 0, + SQL_FIRST_CHARACTER = 3 +}; + +class SqliteDatabaseUtils { +public: + static std::map MapInit(); + static int GetSqlStatementType(std::string sql); + static void DeleteFile(std::string &fileName); + static bool RenameFile(std::string &oldFileName, std::string &newFileName); + static std::string GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode); + static std::string GetCorruptPath(std::string &path, int &errorCode); + +private: + static std::map g_statementType; + static std::mutex g_locker; + static int g_mkdirMode; + + SqliteDatabaseUtils(); + ~SqliteDatabaseUtils(); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/transaction_observer.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/transaction_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..0814635201afcc4dfb64bc35bf2369a422df56ae --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/transaction_observer.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef APPDATAMGR_TRANSACTION_OBSERVER_H +#define APPDATAMGR_TRANSACTION_OBSERVER_H +namespace OHOS { +namespace NativeRdb { +class TransactionObserver { +public: + virtual ~TransactionObserver() {} + virtual void OnBegin() const; + virtual void OnCommit() const; + virtual void OnRollback() const; +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/value_object.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/value_object.h new file mode 100644 index 0000000000000000000000000000000000000000..92792ddeb27415ecb39549d92b341fa64fa47bc8 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/value_object.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_VALUE_OBJECT_H +#define NATIVE_RDB_VALUE_OBJECT_H + +#include +#include +#include +#include + +namespace OHOS { +namespace NativeRdb { + +enum class ValueObjectType { + TYPE_NULL = 0, + TYPE_INT, + TYPE_INT64, + TYPE_DOUBLE, + TYPE_STRING, + TYPE_BLOB, + TYPE_BOOL, +}; + +class ValueObject : public virtual OHOS::Parcelable { +public: + ValueObject(); + ~ValueObject(); + ValueObject(ValueObject &&valueObject) noexcept; + ValueObject(const ValueObject &valueObject); + explicit ValueObject(int val); + explicit ValueObject(int64_t val); + explicit ValueObject(double val); + explicit ValueObject(bool val); + explicit ValueObject(const std::string &val); + explicit ValueObject(const std::vector &blob); + ValueObject &operator=(ValueObject &&valueObject) noexcept; + ValueObject &operator=(const ValueObject &valueObject); + + ValueObjectType GetType() const; + int GetInt(int &val) const; + int GetLong(int64_t &val) const; + int GetDouble(double &val) const; + int GetBool(bool &val) const; + int GetString(std::string &val) const; + int GetBlob(std::vector &val) const; + + bool Marshalling(Parcel &parcel) const override; + static ValueObject *Unmarshalling(Parcel &parcel); + + operator int () const + { + return static_cast(std::get(value)); + } + operator int64_t () const + { + return std::get(value); + } + operator double () const + { + return std::get(value); + } + operator bool () const + { + return std::get(value); + } + operator std::string () const + { + return std::get(value); + } + operator std::vector () const + { + return std::get>(value); + } + +private: + ValueObjectType type; + std::variant> value; +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/include/values_bucket.h b/distributeddatamgr/relational_store_use_cases/include/rdb/include/values_bucket.h new file mode 100644 index 0000000000000000000000000000000000000000..ff99cbe030caec9c40919c9d7be41514299cecfe --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/include/values_bucket.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_VALUES_BUCKET_H +#define NATIVE_RDB_VALUES_BUCKET_H + +#include +#include +#include + +#include "value_object.h" + +namespace OHOS { +namespace NativeRdb { + +class ValuesBucket : public virtual OHOS::Parcelable { +public: + ValuesBucket(); + explicit ValuesBucket(std::map &valuesMap); + ~ValuesBucket(); + void PutString(const std::string &columnName, const std::string &value); + void PutInt(const std::string &columnName, int value); + void PutLong(const std::string &columnName, int64_t value); + void PutDouble(const std::string &columnName, double value); + void PutBool(const std::string &columnName, bool value); + void PutBlob(const std::string &columnName, const std::vector &value); + void PutNull(const std::string &columnName); + void Delete(const std::string &columnName); + void Clear(); + int Size() const; + bool IsEmpty() const; + bool HasColumn(const std::string &columnName) const; + bool GetObject(const std::string &columnName, ValueObject &value) const; + void GetAll(std::map &valuesMap) const; + + bool Marshalling(Parcel &parcel) const override; + static ValuesBucket *Unmarshalling(Parcel &parcel); +private: + std::map valuesMap; +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/abs_rdb_predicates.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/abs_rdb_predicates.h new file mode 100644 index 0000000000000000000000000000000000000000..a010d6801d1560a1285672c029eaef2410c8bb64 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/abs_rdb_predicates.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef NATIVE_RDB_ABSRDBPREDICATES_H +#define NATIVE_RDB_ABSRDBPREDICATES_H + +#include "abs_predicates.h" + +namespace OHOS::NativeRdb { +class AbsRdbPredicates : public AbsPredicates { +public: + explicit AbsRdbPredicates(std::string tableName); + + ~AbsRdbPredicates() override {} + + void Clear() override; + + std::string ToString() const; + + std::string GetTableName() const; + + virtual void InitialParam(); + virtual std::vector GetJoinTypes(); + virtual void SetJoinTypes(const std::vector joinTypes); + virtual std::vector GetJoinTableNames(); + virtual void SetJoinTableNames(const std::vector joinTableNames); + virtual std::vector GetJoinConditions(); + virtual void SetJoinConditions(const std::vector joinConditions); + virtual std::string GetJoinClause() const; + virtual int GetJoinCount() const; + virtual void SetJoinCount(int joinCount); + +protected: + std::vector joinTypes; + std::vector joinTableNames; + std::vector joinConditions; + int joinCount = 0; + +private: + std::string tableName; +}; +} // namespace OHOS::NativeRdb + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_helper.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..640b235a81df6a04e902591d3fc9d1019f1c042d --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_helper.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_HELPER_H +#define NATIVE_RDB_RDB_HELPER_H + +#include +#include +#include +#include "rdb_open_callback.h" +#include "rdb_store.h" +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +class RdbHelper final { +public: + static std::shared_ptr GetRdbStore( + const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode); + static int DeleteRdbStore(const std::string &path); + static void ClearCache(); + +private: + static int ProcessOpenCallback( + RdbStore &rdbStore, const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback); + static std::mutex mutex_; + static std::map> storeCache_; +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_open_callback.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_open_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..25a72d6ea7fa82bfc21e50f2a8c37e64525d0999 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_open_callback.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_OPEN_CALLBACK_H +#define NATIVE_RDB_RDB_OPEN_CALLBACK_H + +#include "rdb_store.h" + +namespace OHOS { +namespace NativeRdb { +class RdbOpenCallback { +public: + /** + * Called when the database associate whit this RdbStore is created with the first time. + * This is where the creation of tables and insert the initial data of tables should happen. + * + * param store The RdbStore object. + */ + virtual int OnCreate(RdbStore &rdbStore) = 0; + + /** + * Called when the database associate whit this RdbStore needs to be upgrade. + * + * param store The RdbStore object. + * param oldVersion The old database version. + * param newVersion The new database version. + */ + virtual int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) = 0; + + /** + * Called when the database associate whit this RdbStore needs to be downgrade. + * + * param store The RdbStore object. + * param oldVersion The old database version. + * param newVersion The new database version. + */ + virtual int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) + { + return 0; + } + + /** + * Called when the RdbStore has been opened. + * + * param store The RdbStore object. + */ + virtual int OnOpen(RdbStore &rdbStore) + { + return 0; + } + + virtual int onCorruption(std::string databaseFile) + { + return 0; + } +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_predicates.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_predicates.h new file mode 100644 index 0000000000000000000000000000000000000000..4eac92d2b029510736847f6abe5fc056a7930e94 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_predicates.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDBPREDICATES_H +#define NATIVE_RDB_RDBPREDICATES_H + + +#include "abs_rdb_predicates.h" + +namespace OHOS { +namespace NativeRdb { +class RdbPredicates : public AbsRdbPredicates { +public: + explicit RdbPredicates(std::string tableName); + ~RdbPredicates() override {} + + std::string GetJoinClause() const override; + RdbPredicates *CrossJoin(std::string tableName); + RdbPredicates *InnerJoin(std::string tableName); + RdbPredicates *LeftOuterJoin(std::string tableName); + RdbPredicates *Using(std::vector fields); + RdbPredicates *On(std::vector clauses); + +private: + std::string ProcessJoins() const; + std::string GetGrammar(int type) const; + RdbPredicates *Join(int join, std::string tableName); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_store.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_store.h new file mode 100644 index 0000000000000000000000000000000000000000..ccfe3bd3ca855d873003637e4e28190fdf270486 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_store.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_STORE_H +#define NATIVE_RDB_RDB_STORE_H + +#include +#include +#include + +#include "abs_rdb_predicates.h" +#include "result_set.h" +#include "value_object.h" +#include "values_bucket.h" + +namespace OHOS::NativeRdb { +enum class ConflictResolution { + ON_CONFLICT_NONE = 0, + ON_CONFLICT_ROLLBACK, + ON_CONFLICT_ABORT, + ON_CONFLICT_FAIL, + ON_CONFLICT_IGNORE, + ON_CONFLICT_REPLACE, +}; + +class RdbStore { +public: + virtual ~RdbStore() {} +#ifdef WINDOWS_PLATFORM + virtual void Clear(); +#endif + virtual int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) = 0; + virtual int BatchInsert(int64_t &outInsertNum, const std::string &table, + const std::vector &initialBatchValues) = 0; + virtual int Replace(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) = 0; + virtual int InsertWithConflictResolution(int64_t &outRowId, const std::string &table, + const ValuesBucket &initialValues, + ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; + virtual int Update(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause = "", + const std::vector &whereArgs = std::vector()) = 0; + virtual int UpdateWithConflictResolution(int &changedRows, const std::string &table, const ValuesBucket &values, + const std::string &whereClause = "", const std::vector &whereArgs = std::vector(), + ConflictResolution conflictResolution = ConflictResolution::ON_CONFLICT_NONE) = 0; + virtual int Delete(int &deletedRows, const std::string &table, const std::string &whereClause = "", + const std::vector &whereArgs = std::vector()) = 0; + virtual std::unique_ptr QueryByStep( + const std::string &sql, const std::vector &selectionArgs = std::vector()) = 0; + virtual int ExecuteSql( + const std::string &sql, const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteAndGetLong(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteAndGetString(std::string &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteForLastInsertedRowId(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int ExecuteForChangedRowCount(int64_t &outValue, const std::string &sql, + const std::vector &bindArgs = std::vector()) = 0; + virtual int Backup(const std::string databasePath, const std::vector destEncryptKey) = 0; + virtual int Attach( + const std::string &alias, const std::string &pathName, const std::vector destEncryptKey) = 0; + + virtual int Count(int64_t &outValue, const AbsRdbPredicates &predicates) = 0; + virtual std::unique_ptr Query( + const AbsRdbPredicates &predicates, const std::vector columns) = 0; + virtual int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) = 0; + virtual int Delete(int &deletedRows, const AbsRdbPredicates &predicates) = 0; + + virtual int GetVersion(int &version) = 0; + virtual int SetVersion(int version) = 0; + virtual int BeginTransaction() = 0; + virtual int RollBack() = 0; + virtual int Commit() = 0; + virtual int MarkAsCommit() = 0; + virtual int EndTransaction() = 0; + virtual bool IsInTransaction() = 0; + virtual std::string GetPath() = 0; + virtual bool IsHoldingConnection() = 0; + virtual bool IsOpen() const = 0; + virtual bool IsReadOnly() const = 0; + virtual bool IsMemoryRdb() const = 0; + virtual int Restore(const std::string backupPath, const std::vector &newKey) = 0; + virtual int ChangeDbFileForRestore(const std::string newPath, const std::string backupPath, + const std::vector &newKey) = 0; +}; +} // namespace OHOS::NativeRdb +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_store_config.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_store_config.h new file mode 100644 index 0000000000000000000000000000000000000000..afb32fb4edc52c7200ee35a523a4843ec2da6534 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/rdb_store_config.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RDB_STORE_CONFIG_H +#define NATIVE_RDB_RDB_STORE_CONFIG_H + +#include +#include + +namespace OHOS::NativeRdb { +// indicates the type of the storage +enum class StorageMode { + MODE_MEMORY = 101, + MODE_DISK, +}; + +enum class JournalMode { + MODE_DELETE, + MODE_TRUNCATE, + MODE_PERSIST, + MODE_MEMORY, + MODE_WAL, + MODE_OFF, +}; + +enum class SyncMode { + MODE_OFF, + MODE_NORMAL, + MODE_FULL, + MODE_EXTRA, +}; + +enum class DatabaseFileType { + NORMAL, + BACKUP, + CORRUPT, +}; + +enum class SecurityLevel : int32_t { + S1 = 1, + S2, + S3, + S4, + LAST +}; + + +class RdbStoreConfig { +public: + RdbStoreConfig(const RdbStoreConfig &config); + RdbStoreConfig(const std::string &path, StorageMode storageMode = StorageMode::MODE_DISK, bool readOnly = false, + const std::vector &encryptKey = std::vector(), const std::string &journalMode = "", + const std::string &syncMode = "", const std::string &databaseFileType = "", + SecurityLevel securityLevel = SecurityLevel::LAST, bool isCreateNecessary = true); + ~RdbStoreConfig(); + std::string GetName() const; + std::string GetPath() const; + StorageMode GetStorageMode() const; + std::string GetJournalMode() const; + std::string GetSyncMode() const; + std::vector GetEncryptKey() const; + bool IsReadOnly() const; + bool IsMemoryRdb() const; + std::string GetDatabaseFileType() const; + SecurityLevel GetSecurityLevel() const; + void SetEncryptStatus(const bool status); + bool IsEncrypt() const; + bool IsCreateNecessary() const; + + // set the journal mode, if not set, the default mode is WAL + void SetName(std::string name); + void SetJournalMode(JournalMode journalMode); + void SetPath(std::string path); + void SetReadOnly(bool readOnly); + void SetStorageMode(StorageMode storageMode); + void SetDatabaseFileType(DatabaseFileType type); + void SetEncryptKey(const std::vector &encryptKey); + void SetSecurityLevel(SecurityLevel secLevel); + void ClearEncryptKey(); + + // distributed rdb + int SetBundleName(const std::string &bundleName); + std::string GetBundleName() const; + void SetModuleName(const std::string& moduleName); + std::string GetModuleName() const; + void SetServiceName(const std::string& serviceName); + void SetArea(int32_t area); + int32_t GetArea() const; + std::string GetUri() const; + void SetUri(const std::string& uri); + std::string GetReadPermission() const; + void SetReadPermission(const std::string& permission); + std::string GetWritePermission() const; + void SetWritePermission(const std::string& permission); + void SetCreateNecessary(bool isCreateNecessary); + + static std::string GetJournalModeValue(JournalMode journalMode); + static std::string GetSyncModeValue(SyncMode syncMode); + static std::string GetDatabaseFileTypeValue(DatabaseFileType databaseFileType); + +private: + std::string name; + std::string path; + StorageMode storageMode; + std::string journalMode; + std::string syncMode; + std::vector encryptKey; + bool readOnly; + std::string databaseFileType; + + int32_t area_ = 0; + std::string bundleName_; + std::string moduleName_; + + bool isEncrypt_ = false; + SecurityLevel securityLevel = SecurityLevel::LAST; + std::string uri_; + std::string readPermission_; + std::string writePermission_; + bool isCreateNecessary_; + +}; +} // namespace OHOS::NativeRdb + +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/sqlite_database_utils.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/sqlite_database_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..88fdd4fe5382c7c50da7df4d7edec5d73836b2c6 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/sqlite_database_utils.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_SQLITE_DATABASE_UTILS_H +#define NATIVE_RDB_SQLITE_DATABASE_UTILS_H + +#include +#include +#include + +#include "rdb_store_config.h" + +namespace OHOS { +namespace NativeRdb { +enum Type { + STATEMENT_SELECT = 1, + STATEMENT_UPDATE = 2, + STATEMENT_ATTACH = 3, + STATEMENT_DETACH = 4, + STATEMENT_BEGIN = 5, + STATEMENT_COMMIT = 6, + STATEMENT_ROLLBACK = 7, + STATEMENT_PRAGMA = 8, + STATEMENT_DDL = 9, + STATEMENT_OTHER = 99, + DATA_TYPE_BOOLEAN = 5, + DATA_TYPE_BLOB = 4, + DATA_TYPE_STRING = 3, + DATA_TYPE_FLOAT = 2, + DATA_TYPE_INTEGER = 1, + DATA_TYPE_NULL = 0, + SQL_FIRST_CHARACTER = 3 +}; + +class SqliteDatabaseUtils { +public: + static std::map MapInit(); + static int GetSqlStatementType(std::string sql); + static void DeleteFile(std::string &fileName); + static bool RenameFile(std::string &oldFileName, std::string &newFileName); + static std::string GetDefaultDatabasePath(std::string &baseDir, std::string &name, int &errorCode); + static std::string GetCorruptPath(std::string &path, int &errorCode); + +private: + static std::map g_statementType; + static std::mutex g_locker; + static int g_mkdirMode; + + SqliteDatabaseUtils(); + ~SqliteDatabaseUtils(); +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/value_object.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/value_object.h new file mode 100644 index 0000000000000000000000000000000000000000..fbe6f7ed330cec7c0b09bbdac0b22477dead114d --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/value_object.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_VALUE_OBJECT_H +#define NATIVE_RDB_VALUE_OBJECT_H + +#include +#include +#include + +namespace OHOS { +namespace NativeRdb { +enum class ValueObjectType { + TYPE_NULL = 0, + TYPE_INT, + TYPE_INT64, + TYPE_DOUBLE, + TYPE_STRING, + TYPE_BLOB, + TYPE_BOOL, +}; +class ValueObject { +public: + ValueObject(); + ~ValueObject(); + ValueObject(ValueObject &&valueObject) noexcept; + ValueObject(const ValueObject &valueObject); + explicit ValueObject(int val); + explicit ValueObject(int64_t val); + explicit ValueObject(double val); + explicit ValueObject(bool val); + explicit ValueObject(const std::string &val); + explicit ValueObject(const std::vector &blob); + ValueObject &operator=(ValueObject &&valueObject) noexcept; + ValueObject &operator=(const ValueObject &valueObject); + + ValueObjectType GetType() const; + int GetInt(int &val) const; + int GetLong(int64_t &val) const; + int GetDouble(double &val) const; + int GetBool(bool &val) const; + int GetString(std::string &val) const; + int GetBlob(std::vector &val) const; + +private: + ValueObjectType type; + std::variant> value; +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/values_bucket.h b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/values_bucket.h new file mode 100644 index 0000000000000000000000000000000000000000..6fdf7bb00f6d06d0f92a3338aab3b787541606f6 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb/mock/include/values_bucket.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_VALUES_BUCKET_H +#define NATIVE_RDB_VALUES_BUCKET_H + +#include +#include + +#include "value_object.h" + +namespace OHOS { +namespace NativeRdb { +class ValuesBucket { +public: + ValuesBucket(); + explicit ValuesBucket(std::map &valuesMap); + ~ValuesBucket(); + void PutString(const std::string &columnName, const std::string &value); + void PutInt(const std::string &columnName, int value); + void PutLong(const std::string &columnName, int64_t value); + void PutDouble(const std::string &columnName, double value); + void PutBool(const std::string &columnName, bool value); + void PutBlob(const std::string &columnName, const std::vector &value); + void PutNull(const std::string &columnName); + void Delete(const std::string &columnName); + void Clear(); + int Size() const; + bool IsEmpty() const; + bool HasColumn(const std::string &columnName) const; + bool GetObject(const std::string &columnName, ValueObject &value) const; + void GetAll(std::map &valuesMap) const; + +private: + std::map valuesMap; +}; +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/BUILD.gn b/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c45f376e9deaa4b985d0e9b89b4176c852d81a29 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/data_share/datashare.gni") +import("//foundation/distributeddatamgr/relational_store/relational_store.gni") + +config("rdb_data_ability_adapter_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${datashare_base_path}/interfaces/inner_api/common/include", + "${datashare_base_path}/interfaces/inner_api/consumer/include", + "${datashare_base_path}/interfaces/inner_api/provider/include", + "${relational_store_innerapi_path}/rdb/include", + "${datashare_common_native_path}/include", + ] +} + +config("rdb_data_ability_adapter_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${datashare_base_path}/interfaces/inner_api/provider/include", + ] +} + +ohos_shared_library("rdb_data_ability_adapter") { + sources = [ + "${relational_store_native_path}/rdb_data_ability_adapter/src/rdb_data_ability_utils.cpp", + "${relational_store_native_path}/rdb_data_ability_adapter/src/result_set_utils.cpp", + ] + + configs = [ ":rdb_data_ability_adapter_config" ] + + subsystem_name = "distributeddatamgr" + part_name = "relational_store" + + external_deps = [ + "c_utils:utils", + "relational_store:native_dataability", + "relational_store:native_rdb", + ] + + public_configs = [ ":rdb_data_ability_adapter_public_config" ] +} diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/include/rdb_data_ability_utils.h b/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/include/rdb_data_ability_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..c6ba22becd176dd066b8e17bf2e34529179f934e --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/include/rdb_data_ability_utils.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RDB_DATA_ABILITY_UTILS_H +#define RDB_DATA_ABILITY_UTILS_H + +#include +#include +#include +#include + +#include "result_set.h" +#include "data_ability_predicates.h" +#include "datashare_predicates.h" +#include "datashare_values_bucket.h" +#include "values_bucket.h" + +namespace OHOS { +namespace DataShare { +class ResultSet; +} +namespace NativeRdb { +class AbsSharedResultSet; +} +namespace RdbDataAbilityAdapter { +class RdbDataAbilityUtils { +public: + using ValuesBucket = NativeRdb::ValuesBucket; + using DataShareValuesBucket = DataShare::DataShareValuesBucket; + using DSResultSet = DataShare::ResultSet; + using DataSharePredicates = DataShare::DataSharePredicates; + using DataAbilityPredicates = NativeRdb::DataAbilityPredicates; + using AbsSharedResultSet = NativeRdb::AbsSharedResultSet; + + static DataShareValuesBucket ToDataShareValuesBucket(const ValuesBucket &valuesBucket); + + static DataSharePredicates ToDataSharePredicates(const DataAbilityPredicates &predicates); + + static std::shared_ptr ToAbsSharedResultSet(std::shared_ptr resultSet); + +private: + RdbDataAbilityUtils(); + ~RdbDataAbilityUtils(); +}; +} // namespace RdbDataAbilityAdapter +} // namespace OHOS +#endif // RDB_DATA_ABILITY_UTILS_H + diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/include/result_set_utils.h b/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/include/result_set_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..ae37fb7ef3f26971861e81d9a6a90979acc90650 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb_data_ability_adapter/include/result_set_utils.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_NATIVE_RDB_DATA_ABILITY_ADAPTER_SRC_RESULT_SET_UTILS_H +#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" + +namespace OHOS::RdbDataAbilityAdapter { +class ResultSetUtils : public NativeRdb::AbsSharedResultSet { + using DSResultSet = DataShare::ResultSet; +public: + ResultSetUtils(std::shared_ptr dbResultSet); + int GetAllColumnNames(std::vector &columnNames) override; + int GetColumnCount(int &count) override; + int GetColumnType(int columnIndex, NativeRdb::ColumnType &columnType) override; + int GetColumnIndex(const std::string &columnName, int &columnIndex) override; + int GetColumnName(int columnIndex, std::string &columnName) override; + int GetRowCount(int &count) override; + int GetRowIndex(int &position) const override; + int GoTo(int offset) override; + int GoToRow(int position) override; + int GoToFirstRow() override; + int GoToLastRow() override; + int GoToNextRow() override; + int GoToPreviousRow() override; + int IsEnded(bool &result) override; + int IsStarted(bool &result) const override; + int IsAtFirstRow(bool &result) const override; + int IsAtLastRow(bool &result) override; + int GetBlob(int columnIndex, std::vector &blob) override; + int GetString(int columnIndex, std::string &value) override; + int GetInt(int columnIndex, int &value) override; + int GetLong(int columnIndex, int64_t &value) override; + int GetDouble(int columnIndex, double &value) override; + int IsColumnNull(int columnIndex, bool &isNull) override; + bool IsClosed() const override; + int Close() override; + +private: + std::shared_ptr resultSet_; +}; +} +#endif // OHOS_DISTRIBUTED_DATA_RELATIONAL_STORE_FRAMEWORKS_NATIVE_RDB_DATA_ABILITY_ADAPTER_SRC_RESULT_SET_UTILS_H diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/BUILD.gn b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8af6b42e46e89182cdb8e8cd9455ba80c1c6aeca --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/data_share/datashare.gni") +import("//foundation/distributeddatamgr/relational_store/relational_store.gni") + +config("rdb_data_share_adapter_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${datashare_base_path}/interfaces/inner_api/common/include", + "${datashare_base_path}/interfaces/inner_api/consumer/include", + "${datashare_base_path}/interfaces/inner_api/provider/include", + "${relational_store_innerapi_path}/rdb/include", + "${datashare_common_native_path}/include", + ] +} + +config("rdb_data_share_adapter_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${datashare_base_path}/interfaces/inner_api/provider/include", + ] +} + +ohos_shared_library("rdb_data_share_adapter") { + sources = [ + "${relational_store_native_path}/rdb_data_share_adapter/src/rdb_result_set_bridge.cpp", + "${relational_store_native_path}/rdb_data_share_adapter/src/rdb_utils.cpp", + ] + + configs = [ ":rdb_data_share_adapter_config" ] + + subsystem_name = "distributeddatamgr" + part_name = "relational_store" + + external_deps = [ + "c_utils:utils", + "hilog_native:libhilog", + "relational_store:native_rdb", + ] + + public_configs = [ ":rdb_data_share_adapter_public_config" ] +} diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_logger.h b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_logger.h new file mode 100644 index 0000000000000000000000000000000000000000..b2b2aead7f9aa9804169e68e2c77cafc26e67c37 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_logger.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_SHARE_ADAPTER_LOGGER_H +#define DATA_SHARE_ADAPTER_LOGGER_H + +#include "hilog/log.h" + +namespace OHOS { +namespace RdbDataShareAdapter { +static const OHOS::HiviewDFX::HiLogLabel DATA_SHARE_ADAPTER_LABEL = { LOG_CORE, 0xD001650, + "DATA_SHARE_ADAPTER" }; + +#define LOG_DEBUG(...) ((void)OHOS::HiviewDFX::HiLog::Debug(DATA_SHARE_ADAPTER_LABEL, __VA_ARGS__)) +#define LOG_INFO(...) ((void)OHOS::HiviewDFX::HiLog::Info(DATA_SHARE_ADAPTER_LABEL, __VA_ARGS__)) +#define LOG_WARN(...) ((void)OHOS::HiviewDFX::HiLog::Warn(DATA_SHARE_ADAPTER_LABEL, __VA_ARGS__)) +#define LOG_ERROR(...) ((void)OHOS::HiviewDFX::HiLog::Error(DATA_SHARE_ADAPTER_LABEL, __VA_ARGS__)) +#define LOG_FATAL(...) ((void)OHOS::HiviewDFX::HiLog::Fatal(DATA_SHARE_ADAPTER_LABEL, __VA_ARGS__)) +} // namespace RdbDataShareAdapter +} // namespace OHOS + +#endif // DATA_SHARE_ADAPTER_LOGGER_H \ No newline at end of file diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_result_set_bridge.h b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_result_set_bridge.h new file mode 100644 index 0000000000000000000000000000000000000000..c26898932f1d8d1678a785b8719b0826fee7162f --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_result_set_bridge.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RDB_RESULT_SET_BRIDGE_H +#define RDB_RESULT_SET_BRIDGE_H + +#include "../../rdb/include/result_set.h" +#include "rdb_errno.h" +#include "result_set_bridge.h" +#include "string.h" + +namespace OHOS { +namespace NativeRdb { +class ResultSet; +} +namespace RdbDataShareAdapter { +class RdbResultSetBridge : public DataShare::ResultSetBridge { +public: + using ResultSet = NativeRdb::ResultSet; + using ColumnType = NativeRdb::ColumnType; + + RdbResultSetBridge(std::shared_ptr resultSet); + ~RdbResultSetBridge(); + int GetAllColumnNames(std::vector &columnNames) override; + int GetRowCount(int32_t &count) override; + int OnGo(int32_t start, int32_t length, Writer &writer) override; + +private: + void GetColumnTypes(int columnCount, std::vector &columnTypes); + int32_t WriteBlock( + int32_t start, int32_t target, int columnCount, const std::vector &columnTypes, Writer &writer); + bool WriteBlobData(int column, Writer &writer); + void WriteColumn(int columnCount, const std::vector &columnTypes, Writer &writer, int row); + std::shared_ptr rdbResultSet_; +}; +} // namespace RdbDataShareAdapter +} // namespace OHOS +#endif // RDB_RESULT_SET_BRIDGE_H diff --git a/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_utils.h b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1fe8f65ab426010b1995656cc7c0bc02a78d80d6 --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/include/rdb_data_share_adapter/include/rdb_utils.h @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RDB_UTILS_H +#define RDB_UTILS_H + +#include +#include +#include +#include + +#include "../../rdb/include/result_set.h" +#include "abs_predicates.h" +#include "datashare_abs_predicates.h" +#include "datashare_values_bucket.h" +#include "rdb_predicates.h" +#include "rdb_result_set_bridge.h" +#include "result_set_bridge.h" +#include "value_object.h" +#include "values_bucket.h" + +namespace OHOS { +namespace RdbDataShareAdapter { +class RdbUtils { +public: + using RdbPredicates = NativeRdb::RdbPredicates; + using ResultSet = NativeRdb::ResultSet; + using ValuesBucket = NativeRdb::ValuesBucket; + using DataShareValuesBucket = DataShare::DataShareValuesBucket; + using DataShareAbsPredicates = DataShare::DataShareAbsPredicates; + using ResultSetBridge = DataShare::ResultSetBridge; + using OperationItem = DataShare::OperationItem; + using DataSharePredicatesObject = DataShare::DataSharePredicatesObject; + + static ValuesBucket ToValuesBucket(const DataShareValuesBucket &bucket); + + static RdbPredicates ToPredicates(const DataShareAbsPredicates &predicates, const std::string &table); + + static std::shared_ptr ToResultSetBridge(std::shared_ptr resultSet); + +private: + static void NoSupport(const OperationItem &item, RdbPredicates &query); + static void EqualTo(const OperationItem &item, RdbPredicates &predicates); + static void NotEqualTo(const OperationItem &item, RdbPredicates &predicates); + static void GreaterThan(const OperationItem &item, RdbPredicates &predicates); + static void LessThan(const OperationItem &item, RdbPredicates &predicates); + static void GreaterThanOrEqualTo(const OperationItem &item, RdbPredicates &predicates); + static void LessThanOrEqualTo(const OperationItem &item, RdbPredicates &predicates); + static void And(const OperationItem &item, RdbPredicates &predicates); + static void Or(const OperationItem &item, RdbPredicates &predicates); + static void IsNull(const OperationItem &item, RdbPredicates &predicates); + static void IsNotNull(const OperationItem &item, RdbPredicates &predicates); + static void In(const OperationItem &item, RdbPredicates &predicates); + static void NotIn(const OperationItem &item, RdbPredicates &predicates); + static void Like(const OperationItem &item, RdbPredicates &predicates); + static void OrderByAsc(const OperationItem &item, RdbPredicates &predicates); + static void OrderByDesc(const OperationItem &item, RdbPredicates &predicates); + static void Limit(const OperationItem &item, RdbPredicates &predicates); + static void Offset(const OperationItem &item, RdbPredicates &predicates); + static void BeginWrap(const OperationItem &item, RdbPredicates &predicates); + static void EndWrap(const OperationItem &item, RdbPredicates &predicates); + static void BeginsWith(const OperationItem &item, RdbPredicates &predicates); + static void EndsWith(const OperationItem &item, RdbPredicates &predicates); + static void Distinct(const OperationItem &item, RdbPredicates &predicates); + static void GroupBy(const OperationItem &item, RdbPredicates &predicates); + static void IndexedBy(const OperationItem &item, RdbPredicates &predicates); + static void Contains(const OperationItem &item, RdbPredicates &predicates); + static void Glob(const OperationItem &item, RdbPredicates &predicates); + static void Between(const OperationItem &item, RdbPredicates &predicates); + static void NotBetween(const OperationItem &item, RdbPredicates &predicates); + RdbUtils(); + ~RdbUtils(); + static std::string ToString(const DataSharePredicatesObject &predicatesObject); + using OperateHandler = void (*)(const OperationItem &, RdbPredicates &); + static constexpr OperateHandler HANDLERS[DataShare::LAST_TYPE] = { + [DataShare::INVALID_OPERATION] = &RdbUtils::NoSupport, + [DataShare::EQUAL_TO] = &RdbUtils::EqualTo, + [DataShare::NOT_EQUAL_TO] = &RdbUtils::NotEqualTo, + [DataShare::GREATER_THAN] = &RdbUtils::GreaterThan, + [DataShare::LESS_THAN] = &RdbUtils::LessThan, + [DataShare::GREATER_THAN_OR_EQUAL_TO] = &RdbUtils::GreaterThanOrEqualTo, + [DataShare::LESS_THAN_OR_EQUAL_TO] = &RdbUtils::LessThanOrEqualTo, + [DataShare::AND] = &RdbUtils::And, + [DataShare::OR] = &RdbUtils::Or, + [DataShare::IS_NULL] = &RdbUtils::IsNull, + [DataShare::IS_NOT_NULL] = &RdbUtils::IsNotNull, + [DataShare::SQL_IN] = &RdbUtils::In, + [DataShare::NOT_IN] = &RdbUtils::NotIn, + [DataShare::LIKE] = &RdbUtils::Like, + [DataShare::UNLIKE] = &RdbUtils::NoSupport, + [DataShare::ORDER_BY_ASC] = &RdbUtils::OrderByAsc, + [DataShare::ORDER_BY_DESC] = &RdbUtils::OrderByDesc, + [DataShare::LIMIT] = &RdbUtils::Limit, + [DataShare::OFFSET] = &RdbUtils::Offset, + [DataShare::BEGIN_WARP] = &RdbUtils::BeginWrap, + [DataShare::END_WARP] = &RdbUtils::EndWrap, + [DataShare::BEGIN_WITH] = &RdbUtils::BeginsWith, + [DataShare::END_WITH] = &RdbUtils::EndsWith, + [DataShare::IN_KEY] = &RdbUtils::NoSupport, + [DataShare::DISTINCT] = &RdbUtils::Distinct, + [DataShare::GROUP_BY] = &RdbUtils::GroupBy, + [DataShare::INDEXED_BY] = &RdbUtils::IndexedBy, + [DataShare::CONTAINS] = &RdbUtils::Contains, + [DataShare::GLOB] = &RdbUtils::Glob, + [DataShare::BETWEEN] = &RdbUtils::Between, + [DataShare::NOTBETWEEN] = &RdbUtils::NotBetween, + [DataShare::KEY_PREFIX] = &RdbUtils::NoSupport, + }; +}; +} // namespace RdbDataShareAdapter +} // namespace OHOS +#endif // RDB_UTILS_H diff --git a/distributeddatamgr/relational_store_use_cases/relational_store_use_case.cpp b/distributeddatamgr/relational_store_use_cases/relational_store_use_case.cpp new file mode 100644 index 0000000000000000000000000000000000000000..368aa73ffc4d085aacec0b019d706aa9424428cf --- /dev/null +++ b/distributeddatamgr/relational_store_use_cases/relational_store_use_case.cpp @@ -0,0 +1,86 @@ +#include +#include +#include +// 导入 deviceManager 头文件 +#include "deviceManager.h" +// 导入 relationalStore 头文件 +#include "relationalStore.h" + +int main() { + // 定义 STORE_CONFIG + relationalStore::StoreConfig STORE_CONFIG; + STORE_CONFIG.name = "RdbTest.db"; + STORE_CONFIG.securityLevel = relationalStore::SecurityLevel::S1; + + // 调用 getRdbStore 函数 + relationalStore::getRdbStore(this->context, STORE_CONFIG, [](relationalStore::Error err, relationalStore::RdbStore store) { + // 创建 EMPLOYEE 表 + store.executeSql("CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)", nullptr, [](relationalStore::Error err) { + // 设置分布式同步表 + store.setDistributedTables({"EMPLOYEE"}); + // 进行数据的相关操作 + }); + }); + + // 构造用于同步分布式表的谓词对象 + relationalStore::RdbPredicates predicates("EMPLOYEE"); + + // 调用 sync 函数 + store.sync(relationalStore::SyncMode::SYNC_MODE_PUSH, predicates, [](relationalStore::Error err, std::vector> result) { + // 判断数据同步是否成功 + if (err) { + std::cout << "Failed to sync data. Code:" << err.code << ", message:" << err.message << std::endl; + return; + } + std::cout << "Succeeded in syncing data." << std::endl; + for (int i = 0; i < result.size(); i++) { + std::cout << "device:" << result[i][0] << ", status:" << result[i][1] << std::endl; + } + }); + + // 定义 storeObserver 函数 + auto storeObserver = [](std::vector devices) { + for (int i = 0; i < devices.size(); i++) { + std::cout << "The data of device:" << devices[i] << " has been changed." << std::endl; + } + }; + + try { + // 调用 on 函数,注册数据库的观察者 + // 当分布式数据库中的数据发生更改时,将调用回调 + store.on("dataChange", relationalStore::SubscribeType::SUBSCRIBE_TYPE_REMOTE, storeObserver); + } catch (relationalStore::Error err) { + std::cout << "Failed to register observer. Code:" << err.code << ", message:" << err.message << std::endl; + } + + // 当前不需要订阅数据变化时,可以将其取消 + try { + store.off("dataChange", relationalStore::SubscribeType::SUBSCRIBE_TYPE_REMOTE, storeObserver); + } catch (relationalStore::Error err) { + std::cout << "Failed to register observer. Code:" << err.code << ", message:" << err.message << std::endl; + } + + // 调用 createDeviceManager 函数 + deviceManager::createDeviceManager("com.example.appdatamgrverify", [](deviceManager::Error err, deviceManager::DeviceManager manager) { + if (err) { + std::cout << "Failed to create device manager. Code:" << err.code << ", message:" << err.message << std::endl; + return; + } + std::vector devices = manager.getTrustedDeviceListSync(); + std::string deviceId = devices[0].deviceId; + + // 构造用于查询分布式表的谓词对象 + relationalStore::RdbPredicates predicates("EMPLOYEE"); + + // 调用 remoteQuery 函数,并返回查询结果 + store.remoteQuery(deviceId, "EMPLOYEE", predicates, {"ID", "NAME", "AGE", "SALARY", "CODES"}, [](relationalStore::Error err, relationalStore::ResultSet resultSet) { + if (err) { + std::cout << "Failed to remoteQuery data. Code:" << err.code << ", message:" << err.message << std::endl; + return; + } + std::cout << "ResultSet column names: " << resultSet.columnNames << ", column count: " << resultSet.columnCount << std::endl; + }); + }); + + return 0; +}