appdatamgr分仓relational_store

Signed-off-by: PaDaBoo <xuejianwu@huawei.com>
This commit is contained in:
PaDaBoo 2022-07-29 12:23:38 +08:00
parent 73cd586e66
commit 58c353ba4f
330 changed files with 40 additions and 26207 deletions

66
OAT.xml
View File

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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.
Notes:
This is project config file for OpenHarmony OSS Audit Tool, if you have any questions or concerns, please email chenyaxun.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<filefilterlist>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies" >
<filteritem type="filepath" name=".*.db" desc="Database data file used for test case execution."/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>

110
README.md
View File

@ -1,110 +0,0 @@
# distributeddatamgr\_appdatamgr<a name="EN-US_TOPIC_0000001124534865"></a>
- [Introduction](#section11660541593)
- [RDB](#section1589234172717)
- [Preferences Database](#section1287582752719)
- [Directory Structure](#section161941989596)
- [Relational Database](#section101010894114)
- [Constraints](#section18387142613414)
- [Preferences Database](#section762641474720)
- [Constraints](#section1944481420489)
- [Repositories Involved](#section1371113476307)
## Introduction<a name="section11660541593"></a>
The **relational database \(RDB\)** manages data based on relational models. With the underlying SQLite database, the OpenHarmony RDB provides a complete mechanism for managing local databases.
The **preferences database** provides lightweight key-value operations for local applications to store a small amount of data. As the stored data is already loaded in the memory, the faster data access speed achieves a higher work efficiency. The preferences database is non-relational, and therefore it is not suitable for storing a large amount of data. Instead, the preferences database is usually used to operate data in key-value pairs.
### RDB<a name="section1589234172717"></a>
With the SQLite database as the persistence engine, the OpenHarmony RDB supports all features of the SQLite database , including but not limited to transactions, indices, views, triggers, foreign keys, parameterized queries, and prepared SQL statements.
**Figure 1** How RDB works<a name="fig3330103712254"></a>
![](figures/en-us_How_RDB_works.png)
### Preferences Database<a name="section1287582752719"></a>
1. The preferences database provides operation classes for applications to operate the database.
2. With the **PreferencesHelper**, an app can load the content of a specified file to the **Preferences** instance. Each file has only one **Preferences** instance. The system stores the instance in the memory through a static container until the app removes the instance from the memory or deletes the file.
3. After obtaining the **Preferences** instance, the app can use the functions in **Preferences** to read data from or write data to the **Preferences** instance, and use **flush\(\)** or **flushSync\(\)** to save the modification to the file that stores the preference data.
**Figure 2** How the preferences database works<a name="fig833053712258"></a>
![](figures/en-us_How_the_preferences_database_works.png)
## Directory Structure<a name="section161941989596"></a>
```
//foundation/distributeddatamgr/appdatamgr
├── frameworks # Framework code
│ └── js # JS API implementation
│ │ └── napi # napi implementation
│ └── native # Internal API implementation
└── interfaces # APIs
└── inner_api # Internal APIs
└── native # C/C++ APIs
```
## Relational Database<a name="section101010894114"></a>
Some basic concepts are as follows:
- **Relational database \(RDB\)**
A database created on the basis of relational models. The RDB stores data in rows and columns.
- **Result set**
A set of query results used to access the data. You can access the required data in a result set in flexible modes.
- **SQLite database**
A lightweight RDB in compliance with the atomicity, consistency, isolation, and durability \(ACID\) properties. It is an open-source database.
### Constraints<a name="section18387142613414"></a>
The RDB can use a maximum of four connection pools to manage read and write operations.
To ensure data accuracy, the RDB supports only one writ operation at a time.
## Preferences Database<a name="section762641474720"></a>
Some basic concepts are as follows:
- **Key-value database**
A database that stores data in key-value pairs. The **key** indicates keyword, and **value** indicates the corresponding value.
- **Non-relational database**
A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. Instead, the data in a non-relational database is independent and scalable.
- **Preference** **data**
A type of data that is frequently accessed and used.
### Constraints<a name="section1944481420489"></a>
A key should be a string with a maximum of 80 characters and cannot be an empty string.
A value in the format of string can have a maximum of 8192 characters. A value can be an empty string.
To avoid a high memory cost, it is recommended that the preferences database store no more than ten thousand data entries.
## Repositories Involved<a name="section1371113476307"></a>
- [Distributed Data Management subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/distributed-data-management.md)
- **distributeddatamgr\_appdatamgr**
- [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite)

View File

@ -1,29 +1,54 @@
# 本地数据管理组件
# 关系型数据库Relational DatabaseRDB
## 简介
### [关系型数据库Relational DatabaseRDB](relational_store/README_zh.md)
是一种基于关系模型来管理数据的数据库。OpenHarmony关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制。
### [首选项Preferences](preferences/README_zh.md)
**关系型数据库Relational DatabaseRDB** 是一种基于关系模型来管理数据的数据库。OpenHarmony关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制。
OpenHarmony关系型数据库底层使用SQLite作为持久化存储引擎支持SQLite具有的所有数据库特性包括但不限于事务、索引、视图、触发器、外键、参数化查询和预编译SQL语句。
主要提供轻量级Key-Value操作支持本地应用存储少量数据数据存储在本地文件中同时也加载在内存中所以访问速度更快效率更高。首选项提供非关系型数据存储不宜存储大量数据经常用于操作键值对形式数据的场景。
### [数据共享DataShare](data_share/README_zh.md)
以下是几个基本概念:
- **关系型数据库**
主要用于应用管理其自身数据,同时支持同个设备上不同应用间的数据共享。
### [轻量系统KV数据库Lightweight KV store](kv_store/README_zh.md)
创建在关系模型基础上的数据库,以行和列的形式存储数据。
- **结果集**
指用户查询之后的结果集合,可以对数据进行访问。结果集提供了灵活的数据访问方式,可以更方便的拿到用户想要的数据。
- **SQLite数据库**
一款轻量级的数据库是遵守ACID的关系型数据库组件。它是一个开源的项目。
**图 1** 关系型数据库运作机制
![](figures/zh-cn_关系型数据库运作机制.png)
依托当前公共基础库提供的KV存储能力开发为轻量系统设备应用提供键值对数据管理能力。在有进程的平台上KV存储提供的参数管理供单进程访问不能被其他进程使用。在此类平台上KV存储作为基础库加载在应用进程以保障不被其他进程访问。
## 目录
```
//foundation/distributeddatamgr/appdatamgr
├── data_share # 数据共享DataShare
├── kv_store # 轻量系统KV数据库Lightweight KV store
├── preferences # 首选项Preferences
└── relational_store # 关系型数据库RDB
//foundation/distributeddatamgr/relational_store/
├── frameworks # 框架层代码
│ └── js # JS API的实现
│ │ └── napi # napi代码实现
│ └── native # 内部接口实现
├── interfaces # 接口代码
│ └── inner_api # 内部接口声明
└── test # 测试用例
├── js # js用例
└── native # C++用例
```
## 约束
数据库中连接池的最大数量是4个用以管理用户的读写操作。
为保证数据的准确性,数据库同一时间只能支持一个写操作。
## 相关仓
- [分布式数据管理子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%88%86%E5%B8%83%E5%BC%8F%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md)
- [**distributeddatamgr\_appdatamgr**](https://gitee.com/openharmony/distributeddatamgr_appdatamgr/blob/master/README_zh.md)
- [**distributeddatamgr\_relational_store**](https://gitee.com/openharmony/distributeddatamgr_relational_store/blob/master/README_zh.md)
- [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite)

View File

@ -1,16 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
declare_args() {
relational_store_rdb_support_icu = true
}

View File

@ -1,52 +0,0 @@
# 数据共享
## 简介
**数据共享Data Share** 提供了向其他应用共享以及管理其数据的方法,支持同个设备上不同应用之间的数据共享。
**图 1** 逻辑架构图
![](figures/zh-cn_dataShare.png)
- DataShareExtAbility模块为数据提供方实现跨应用数据共享的相关业务。
- DataShareHelper模块为数据访问方提供各种访问数据的接口包括增删改查等。
- 数据访问方与提供方通过IPC进行通信数据提供方可以通过数据库实现也可以通过其他数据存储方式实现。
- ResultSet模块通过共享内存实现用于存储查询数据得到的结果集并提供了遍历结果集的方法。
## 目录
```
/foundation/distributeddatamgr/data_share
├── frameworks # 框架代码
│   ├── js
│   │   └── napi # NAPI代码存放目录
│   │   ├── common # 公用NAPI代码存放目录
│   │   ├── dataShare # 客户端NAPI代码存放目录
│   │   ├── datashare_ext_ability # DataShareExtentionAbility模块JS代码存放目录
│   │   └── datashare_ext_ability_context # DataShareExtentionAbilityContext模块JS代码存放目录
│   └── native
│   ├── common
│   ├── consumer
│   └── provider
└── interfaces # 对外接口存放目录
└── inner_api # 对内部子系统暴露的头文件存放目录
├── common # 公用对内部子系统暴露的头文件存放目录
├── consumer # 客户端对内部子系统暴露的头文件存放目录
└── provider # 服务端对内部子系统暴露的头文件存放目录
```
## 约束
- DataShare受到数据提供方所使用数据库的一些限制。例如支持的数据模型、Key的长度、Value的长度、每个应用程序支持同时打开数据库的最大数量等都会受到使用的数据库的限制。
- 因DataShare内部实现依赖于IPC通信所以数据集、谓词、结果集等的载荷受到IPC通信的约束与限制。
## 相关仓
[分布式数据管理子系统](https://gitee.com/openharmony/distributeddatamgr_data_share/blob/master/README_zh.md)
[distributeddatamgr_datamgr](https://gitee.com/openharmony/distributeddatamgr_datamgr/blob/master/README_zh.md)
[**distributeddatamgr_data_share**](https://gitee.com/openharmony/distributeddatamgr_data_share/blob/master/README_zh.md)

View File

@ -1,113 +0,0 @@
{
"name": "@ohos/distributeddatamgr_data_share",
"version": "3.1.0",
"description": "Local Data Management",
"homePage": "https://gitee.com/openharmony",
"license": "Apache V2",
"repository": "https://gitee.com/openharmony/distributeddatamgr_data_share",
"domain": "os",
"language": "",
"publishAs": "code-segment",
"private": false,
"scripts": {},
"tags": [
"foundation"
],
"keywords": [
"distributeddatamgr",
"data_share"
],
"envs": [],
"dirs": {},
"author": {
"name": "",
"email": "",
"url": ""
},
"contributors": [
{
"name": "",
"email": "",
"url": ""
}
],
"segment": {
"destPath": "foundation/distributeddatamgr/data_share"
},
"component": {
"name": "data_share",
"subsystem": "distributeddatamgr",
"syscap": [
"SystemCapability.DistributedDataManager.DataShare.Core",
"SystemCapability.DistributedDataManager.DataShare.Consumer",
"SystemCapability.DistributedDataManager.DataShare.Provider"
],
"features": [],
"adapted_system_type": [
"standard"
],
"rom": "",
"ram": "",
"deps": {
"components": [
"relational_store",
"access_token",
"ability_runtime",
"ipc_js",
"napi",
"hiviewdfx_hilog_native",
"libuv",
"ipc",
"bundle_framework",
"utils_base",
"ability_base",
"eventhandler"
],
"third_party": []
},
"build": {
"sub_component": [
"//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_abilitykit",
"//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_ext_ability_module",
"//foundation/distributeddatamgr/data_share/frameworks/js/napi:datashare_napi_packages",
"//foundation/distributeddatamgr/data_share/interfaces/inner_api/common:datashare_common"
],
"inner_kits": [
{
"name": "//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_abilitykit",
"header": {
"header_files": [
"datashare_helper.h",
"datashare_result_set.h"
],
"header_base": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/consumer/include"
}
},
{
"name": "//foundation/distributeddatamgr/data_share/interfaces/inner_api:datashare_abilitykit",
"header": {
"header_files": [
"result_set_bridge.h"
],
"header_base": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/provider/include"
}
},
{
"name": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/common:datashare_common",
"header": {
"header_files": [
"datashare_errno.h",
"datashare_abs_predicates.h",
"datashare_predicates_def.h",
"datashare_predicates_object.h",
"datashare_predicates.h",
"datashare_value_object.h",
"datashare_values_bucket.h"
],
"header_base": "//foundation/distributeddatamgr/data_share/interfaces/inner_api/common/include"
}
}
]
}
}
}

View File

@ -1,38 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
ability_runtime_path = "//foundation/ability/ability_runtime"
ability_runtime_inner_api_path = "${ability_runtime_path}/interfaces/inner_api"
ability_runtime_kits_path = "${ability_runtime_path}/frameworks/kits"
ability_runtime_services_path = "${ability_runtime_path}/services"
ability_runtime_napi_path = "${ability_runtime_path}/frameworks/js/napi"
datashare_base_path = "//foundation/distributeddatamgr/data_share"
datashare_common_native_path = "${datashare_base_path}/frameworks/native/common"
datashare_common_napi_path = "${datashare_base_path}/frameworks/js/napi/common"
datashare_napi_path = "${datashare_base_path}/frameworks/js/napi"
datashare_innerapi_path = "${datashare_base_path}/interfaces/inner_api"
datashare_native_provider_path =
"${datashare_base_path}/frameworks/native/provider"
datashare_native_consumer_path =
"${datashare_base_path}/frameworks/native/consumer"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

View File

@ -1,24 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//foundation/distributeddatamgr/data_share/datashare.gni")
group("datashare_napi_packages") {
deps = [
"${datashare_napi_path}/dataShare:datashare",
"${datashare_napi_path}/dataShare:datasharepredicates",
"${datashare_napi_path}/datashare_ext_ability:datashareextensionability_napi",
"${datashare_napi_path}/datashare_ext_ability_context:datashareextensionabilitycontext_napi",
]
}

View File

@ -1,55 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_JSUTILS_H
#define DATASHARE_JSUTILS_H
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace DataShare {
class DataShareJSUtils final {
public:
static constexpr int32_t DEFAULT_BUF_SIZE = 1024;
static constexpr int32_t ASYNC_RST_SIZE = 2;
static constexpr int32_t SYNC_RESULT_ELEMNT_NUM = 2;
static std::string Convert2String(napi_env env, napi_value jsStr, size_t max = DEFAULT_BUF_SIZE);
static std::vector<std::string> Convert2StrVector(napi_env env, napi_value value, size_t strMax);
static std::vector<uint8_t> Convert2U8Vector(napi_env env, napi_value jsValue);
static std::string ConvertAny2String(napi_env env, const napi_value jsValue);
static std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue = "");
static napi_value Convert2JSValue(napi_env env, const std::vector<std::string> &value);
static napi_value Convert2JSValue(napi_env env, const std::string &value);
static napi_value Convert2JSValue(napi_env env, const std::vector<uint8_t> &value);
static napi_value Convert2JSValue(napi_env env, int32_t value);
static napi_value Convert2JSValue(napi_env env, int64_t value);
static napi_value Convert2JSValue(napi_env env, double value);
static napi_value Convert2JSValue(napi_env env, bool value);
static napi_value Convert2JSValue(napi_env env, const std::map<std::string, int>& value);
static std::vector<uint8_t> ConvertU8Vector(napi_env env, napi_value jsValue);
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_JSUTILS_H

View File

@ -1,84 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_PREDICATES_PROXY_H
#define DATASHARE_PREDICATES_PROXY_H
#include <memory>
#include "datashare_predicates.h"
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace DataShare {
class DataSharePredicatesProxy {
public:
static void Init(napi_env env, napi_value exports);
static napi_value NewInstance(napi_env env, std::shared_ptr<DataSharePredicates> value);
static std::shared_ptr<DataSharePredicates> GetNativePredicates(
const napi_env &env, const napi_value &arg);
static void Destructor(napi_env env, void *nativeObject, void *finalize_hint);
DataSharePredicatesProxy();
std::shared_ptr<DataSharePredicates> GetPredicates() const;
static napi_value GetConstructor(napi_env env);
private:
~DataSharePredicatesProxy();
static napi_value New(napi_env env, napi_callback_info info);
static std::shared_ptr<DataSharePredicates> GetNativePredicates(napi_env env, napi_callback_info info);
static napi_value EqualTo(napi_env env, napi_callback_info info);
static napi_value NotEqualTo(napi_env env, napi_callback_info info);
static napi_value BeginWrap(napi_env env, napi_callback_info info);
static napi_value EndWrap(napi_env env, napi_callback_info info);
static napi_value Or(napi_env env, napi_callback_info info);
static napi_value And(napi_env env, napi_callback_info info);
static napi_value Contains(napi_env env, napi_callback_info info);
static napi_value BeginsWith(napi_env env, napi_callback_info info);
static napi_value EndsWith(napi_env env, napi_callback_info info);
static napi_value IsNull(napi_env env, napi_callback_info info);
static napi_value IsNotNull(napi_env env, napi_callback_info info);
static napi_value Like(napi_env env, napi_callback_info info);
static napi_value Unlike(napi_env env, napi_callback_info info);
static napi_value Glob(napi_env env, napi_callback_info info);
static napi_value Between(napi_env env, napi_callback_info info);
static napi_value NotBetween(napi_env env, napi_callback_info info);
static napi_value GreaterThan(napi_env env, napi_callback_info info);
static napi_value LessThan(napi_env env, napi_callback_info info);
static napi_value GreaterThanOrEqualTo(napi_env env, napi_callback_info info);
static napi_value LessThanOrEqualTo(napi_env env, napi_callback_info info);
static napi_value OrderByAsc(napi_env env, napi_callback_info info);
static napi_value OrderByDesc(napi_env env, napi_callback_info info);
static napi_value Distinct(napi_env env, napi_callback_info info);
static napi_value Limit(napi_env env, napi_callback_info info);
static napi_value GroupBy(napi_env env, napi_callback_info info);
static napi_value IndexedBy(napi_env env, napi_callback_info info);
static napi_value In(napi_env env, napi_callback_info info);
static napi_value NotIn(napi_env env, napi_callback_info info);
static napi_value PrefixKey(napi_env env, napi_callback_info info);
static napi_value InKeys(napi_env env, napi_callback_info info);
std::shared_ptr<DataSharePredicates> predicates_;
napi_env env_;
napi_ref wrapper_;
};
napi_value GetNapiObject(napi_env env, std::shared_ptr<DataSharePredicates> predicates);
DataSharePredicates *GetNativePredicatesObject(const napi_env &env, const napi_value &arg);
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_PREDICATES_PROXY_H

View File

@ -1,68 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_RESULT_SET_PROXY
#define DATASHARE_RESULT_SET_PROXY
#include <memory>
#include "datashare_result_set.h"
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace DataShare {
class DataShareResultSetProxy final {
public:
DataShareResultSetProxy() = default;
~DataShareResultSetProxy();
explicit DataShareResultSetProxy(std::shared_ptr<DataShareResultSet> resultSet);
DataShareResultSetProxy &operator=(std::shared_ptr<DataShareResultSet> resultSet);
static napi_value NewInstance(napi_env env, std::shared_ptr<DataShareResultSet> resultSet);
static std::shared_ptr<DataShareResultSet> GetNativeObject(
const napi_env &env, const napi_value &arg);
static napi_value GetConstructor(napi_env env);
private:
static std::shared_ptr<DataShareResultSet> &GetInnerResultSet(napi_env env, napi_callback_info info);
static napi_value Initialize(napi_env env, napi_callback_info info);
static napi_value GoToFirstRow(napi_env env, napi_callback_info info);
static napi_value GoToLastRow(napi_env env, napi_callback_info info);
static napi_value GoToNextRow(napi_env env, napi_callback_info info);
static napi_value GoToPreviousRow(napi_env env, napi_callback_info info);
static napi_value GoTo(napi_env env, napi_callback_info info);
static napi_value GoToRow(napi_env env, napi_callback_info info);
static napi_value GetBlob(napi_env env, napi_callback_info info);
static napi_value GetString(napi_env env, napi_callback_info info);
static napi_value GetLong(napi_env env, napi_callback_info info);
static napi_value GetDouble(napi_env env, napi_callback_info info);
static napi_value Close(napi_env env, napi_callback_info info);
static napi_value GetColumnIndex(napi_env env, napi_callback_info info);
static napi_value GetColumnName(napi_env env, napi_callback_info info);
static napi_value GetDataType(napi_env env, napi_callback_info info);
static napi_value GetAllColumnNames(napi_env env, napi_callback_info info);
static napi_value GetColumnCount(napi_env env, napi_callback_info info);
static napi_value GetRowCount(napi_env env, napi_callback_info info);
static napi_value IsClosed(napi_env env, napi_callback_info info);
std::shared_ptr<DataShareResultSet> resultSet_;
};
napi_value GetNapiResultSetObject(napi_env env, DataShareResultSet *resultSet);
DataShareResultSet *GetResultSetProxyObject(const napi_env &env, const napi_value &arg);
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_RESULT_SET_PROXY

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NAPI_DATASHARE_VALUES_BUCKET_H
#define NAPI_DATASHARE_VALUES_BUCKET_H
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
#include "datashare_values_bucket.h"
#include "datashare_js_utils.h"
namespace OHOS {
namespace DataShare {
napi_value DataShareValueBucketNewInstance(napi_env env, DataShareValuesBucket &valuesBucket);
void GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg);
} // namespace DataShare
} // namespace OHOS
#endif // NAPI_DATASHARE_VALUES_BUCKET_H

View File

@ -1,259 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_js_utils.h"
#include "datashare_log.h"
#include "securec.h"
namespace OHOS {
namespace DataShare {
std::string DataShareJSUtils::Convert2String(napi_env env, napi_value jsStr, const size_t max)
{
NAPI_ASSERT_BASE(env, max > 0, "failed on max > 0", std::string());
char *buf = new char[max + 1];
size_t len = 0;
napi_get_value_string_utf8(env, jsStr, buf, max, &len);
buf[len] = 0;
std::string value(buf);
delete[] buf;
return value;
}
std::vector<std::string> DataShareJSUtils::Convert2StrVector(napi_env env, napi_value value, const size_t strMax)
{
NAPI_ASSERT_BASE(env, strMax > 0, "failed on strMax > 0", std::vector<std::string>());
uint32_t arrLen = 0;
napi_get_array_length(env, value, &arrLen);
if (arrLen == 0) {
return {};
}
std::vector<std::string> result;
for (size_t i = 0; i < arrLen; ++i) {
napi_value element;
napi_get_element(env, value, i, &element);
result.push_back(ConvertAny2String(env, element));
}
return result;
}
std::vector<uint8_t> DataShareJSUtils::Convert2U8Vector(napi_env env, napi_value input_array)
{
bool isTypedArray = false;
napi_is_typedarray(env, input_array, &isTypedArray);
if (!isTypedArray) {
return {};
}
napi_typedarray_type type;
napi_value input_buffer = nullptr;
size_t byte_offset = 0;
size_t length = 0;
void *data = nullptr;
napi_get_typedarray_info(env, input_array, &type, &length, &data, &input_buffer, &byte_offset);
if (type != napi_uint8_array || data == nullptr) {
return {};
}
return std::vector<uint8_t>((uint8_t *)data, ((uint8_t *)data) + length);
}
std::vector<uint8_t> DataShareJSUtils::ConvertU8Vector(napi_env env, napi_value jsValue)
{
bool isTypedArray = false;
if (napi_is_typedarray(env, jsValue, &isTypedArray) != napi_ok || !isTypedArray) {
return {};
}
napi_typedarray_type type;
size_t length = 0;
napi_value buffer = nullptr;
size_t offset = 0;
NAPI_CALL_BASE(env, napi_get_typedarray_info(env, jsValue, &type, &length, nullptr, &buffer, &offset), {});
if (type != napi_uint8_array) {
return {};
}
uint8_t *data = nullptr;
size_t total = 0;
NAPI_CALL_BASE(env, napi_get_arraybuffer_info(env, buffer, reinterpret_cast<void **>(&data), &total), {});
length = std::min<size_t>(length, total - offset);
std::vector<uint8_t> result(sizeof(uint8_t) + length);
int retCode = memcpy_s(result.data(), result.size(), &data[offset], length);
if (retCode != 0) {
return {};
}
return result;
}
std::string DataShareJSUtils::ConvertAny2String(napi_env env, napi_value jsValue)
{
napi_valuetype valueType = napi_undefined;
NAPI_CALL_BASE(env, napi_typeof(env, jsValue, &valueType), "napi_typeof failed");
if (valueType == napi_string) {
return DataShareJSUtils::Convert2String(env, jsValue, DataShareJSUtils::DEFAULT_BUF_SIZE);
} else if (valueType == napi_number) {
double valueNumber;
napi_get_value_double(env, jsValue, &valueNumber);
return std::to_string(valueNumber);
} else if (valueType == napi_boolean) {
bool valueBool = false;
napi_get_value_bool(env, jsValue, &valueBool);
return std::to_string(valueBool);
} else if (valueType == napi_null) {
return "null";
} else if (valueType == napi_object) {
std::vector<uint8_t> bytes = DataShareJSUtils::Convert2U8Vector(env, jsValue);
std::string ret(bytes.begin(), bytes.end());
return ret;
}
return "invalid type";
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector<std::string> &value)
{
napi_value jsValue;
napi_status status = napi_create_array_with_length(env, value.size(), &jsValue);
if (status != napi_ok) {
return nullptr;
}
for (size_t i = 0; i < value.size(); ++i) {
napi_set_element(env, jsValue, i, Convert2JSValue(env, value[i]));
}
return jsValue;
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::string &value)
{
napi_value jsValue;
napi_status status = napi_create_string_utf8(env, value.c_str(), value.size(), &jsValue);
if (status != napi_ok) {
return nullptr;
}
return jsValue;
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector<uint8_t> &value)
{
napi_value jsValue;
void *native = nullptr;
napi_value buffer = nullptr;
napi_status status = napi_create_arraybuffer(env, value.size(), &native, &buffer);
if (status != napi_ok) {
return nullptr;
}
if (memcpy_s(native, value.size(), value.data(), value.size()) != EOK && value.size() > 0) {
return nullptr;
}
status = napi_create_typedarray(env, napi_uint8_array, value.size(), buffer, 0, &jsValue);
if (status != napi_ok) {
return nullptr;
}
return jsValue;
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, int32_t value)
{
napi_value jsValue;
napi_status status = napi_create_int32(env, value, &jsValue);
if (status != napi_ok) {
return nullptr;
}
return jsValue;
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, int64_t value)
{
napi_value jsValue;
napi_status status = napi_create_int64(env, value, &jsValue);
if (status != napi_ok) {
return nullptr;
}
return jsValue;
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, double value)
{
napi_value jsValue;
napi_status status = napi_create_double(env, value, &jsValue);
if (status != napi_ok) {
return nullptr;
}
return jsValue;
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, bool value)
{
napi_value jsValue;
napi_status status = napi_get_boolean(env, value, &jsValue);
if (status != napi_ok) {
return nullptr;
}
return jsValue;
}
napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::map<std::string, int> &value)
{
napi_value jsValue;
napi_status status = napi_create_array_with_length(env, value.size(), &jsValue);
if (status != napi_ok) {
return nullptr;
}
int index = 0;
for (const auto& [device, result] : value) {
napi_value jsElement;
status = napi_create_array_with_length(env, SYNC_RESULT_ELEMNT_NUM, &jsElement);
if (status != napi_ok) {
return nullptr;
}
napi_set_element(env, jsElement, 0, Convert2JSValue(env, device));
napi_set_element(env, jsElement, 1, Convert2JSValue(env, result));
napi_set_element(env, jsValue, index++, jsElement);
}
return jsValue;
}
std::string DataShareJSUtils::UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue)
{
size_t size = 0;
if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) {
return defaultValue;
}
std::string value("");
if (size == 0) {
return defaultValue;
}
char *buf = new (std::nothrow) char[size + 1];
if (buf == nullptr) {
return value;
}
(void)memset_s(buf, size + 1, 0, size + 1);
bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok;
if (rev) {
value = buf;
} else {
value = defaultValue;
}
delete[] buf;
buf = nullptr;
return value;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,863 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_predicates_proxy.h"
#include "datashare_log.h"
#include "datashare_js_utils.h"
namespace OHOS {
namespace DataShare {
static napi_ref __thread constructor_ = nullptr;
static constexpr int ARGC_ZERO = 0;
static constexpr int ARGC_ONE = 1;
static constexpr int ARGC_TWO = 2;
napi_value DataSharePredicatesProxy::GetConstructor(napi_env env)
{
napi_value cons;
if (constructor_ != nullptr) {
NAPI_CALL(env, napi_get_reference_value(env, constructor_, &cons));
return cons;
}
LOG_INFO("GetConstructor DataSharePredicates constructor");
napi_property_descriptor descriptors[] = {
DECLARE_NAPI_FUNCTION("equalTo", EqualTo),
DECLARE_NAPI_FUNCTION("notEqualTo", NotEqualTo),
DECLARE_NAPI_FUNCTION("beginWrap", BeginWrap),
DECLARE_NAPI_FUNCTION("endWrap", EndWrap),
DECLARE_NAPI_FUNCTION("or", Or),
DECLARE_NAPI_FUNCTION("and", And),
DECLARE_NAPI_FUNCTION("contains", Contains),
DECLARE_NAPI_FUNCTION("beginsWith", BeginsWith),
DECLARE_NAPI_FUNCTION("endsWith", EndsWith),
DECLARE_NAPI_FUNCTION("isNull", IsNull),
DECLARE_NAPI_FUNCTION("isNotNull", IsNotNull),
DECLARE_NAPI_FUNCTION("like", Like),
DECLARE_NAPI_FUNCTION("unlike", Unlike),
DECLARE_NAPI_FUNCTION("glob", Glob),
DECLARE_NAPI_FUNCTION("between", Between),
DECLARE_NAPI_FUNCTION("notBetween", NotBetween),
DECLARE_NAPI_FUNCTION("greaterThan", GreaterThan),
DECLARE_NAPI_FUNCTION("lessThan", LessThan),
DECLARE_NAPI_FUNCTION("greaterThanOrEqualTo", GreaterThanOrEqualTo),
DECLARE_NAPI_FUNCTION("lessThanOrEqualTo", LessThanOrEqualTo),
DECLARE_NAPI_FUNCTION("orderByAsc", OrderByAsc),
DECLARE_NAPI_FUNCTION("orderByDesc", OrderByDesc),
DECLARE_NAPI_FUNCTION("distinct", Distinct),
DECLARE_NAPI_FUNCTION("limit", Limit),
DECLARE_NAPI_FUNCTION("groupBy", GroupBy),
DECLARE_NAPI_FUNCTION("indexedBy", IndexedBy),
DECLARE_NAPI_FUNCTION("in", In),
DECLARE_NAPI_FUNCTION("notIn", NotIn),
DECLARE_NAPI_FUNCTION("prefixKey", PrefixKey),
DECLARE_NAPI_FUNCTION("inKeys", InKeys),
};
NAPI_CALL(env, napi_define_class(env, "DataSharePredicates", NAPI_AUTO_LENGTH, New, nullptr,
sizeof(descriptors) / sizeof(napi_property_descriptor), descriptors, &cons));
NAPI_CALL(env, napi_create_reference(env, cons, 1, &constructor_));
return cons;
}
void DataSharePredicatesProxy::Init(napi_env env, napi_value exports)
{
LOG_INFO("Init DataSharePredicatesProxy in.");
napi_value cons = GetConstructor(env);
NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, exports, "DataSharePredicates", cons));
LOG_DEBUG("Init DataSharePredicatesProxy out.");
}
napi_value DataSharePredicatesProxy::New(napi_env env, napi_callback_info info)
{
napi_value new_target;
NAPI_CALL(env, napi_get_new_target(env, info, &new_target));
bool is_constructor = (new_target != nullptr);
napi_value thiz;
NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr));
if (is_constructor) {
auto *proxy = new DataSharePredicatesProxy();
proxy->env_ = env;
NAPI_CALL(env, napi_wrap(env, thiz, proxy, DataSharePredicatesProxy::Destructor, nullptr, &proxy->wrapper_));
LOG_INFO("DataSharePredicatesProxy::New constructor ref:%{public}p", proxy->wrapper_);
return thiz;
}
napi_value cons;
NAPI_CALL(env, napi_get_reference_value(env, constructor_, &cons));
napi_value output;
NAPI_CALL(env, napi_new_instance(env, cons, 0, nullptr, &output));
return output;
}
napi_value DataSharePredicatesProxy::NewInstance(
napi_env env, std::shared_ptr<DataSharePredicates> value)
{
napi_value cons = GetConstructor(env);
if (cons == nullptr) {
LOG_ERROR("DataSharePredicatesProxy GetConstructor failed.");
return nullptr;
}
napi_value instance = nullptr;
napi_status status = napi_new_instance(env, cons, 0, nullptr, &instance);
if (status != napi_ok) {
LOG_ERROR("DataSharePredicatesProxy napi_new_instance failed! napi_status:%{public}d!", status);
return nullptr;
}
DataSharePredicatesProxy *proxy = nullptr;
status = napi_unwrap(env, instance, reinterpret_cast<void **>(&proxy));
if (status != napi_ok) {
LOG_ERROR("DataSharePredicatesProxy native instance is nullptr! napi_status:%{public}d!", status);
return instance;
}
proxy->predicates_ = std::move(value);
return instance;
}
std::shared_ptr<DataSharePredicates> DataSharePredicatesProxy::GetNativePredicates(
const napi_env &env, const napi_value &arg)
{
LOG_DEBUG("GetNativePredicates on called.");
if (arg == nullptr) {
LOG_ERROR("DataSharePredicatesProxy arg is null.");
return nullptr;
}
DataSharePredicatesProxy *proxy = nullptr;
napi_unwrap(env, arg, reinterpret_cast<void **>(&proxy));
return proxy->predicates_;
}
void DataSharePredicatesProxy::Destructor(napi_env env, void *nativeObject, void *)
{
DataSharePredicatesProxy *proxy = static_cast<DataSharePredicatesProxy *>(nativeObject);
delete proxy;
}
DataSharePredicatesProxy::~DataSharePredicatesProxy()
{
napi_delete_reference(env_, wrapper_);
}
DataSharePredicatesProxy::DataSharePredicatesProxy()
: predicates_(new DataSharePredicates()), env_(nullptr), wrapper_(nullptr)
{
}
std::shared_ptr<DataSharePredicates> DataSharePredicatesProxy::GetNativePredicates(
napi_env env, napi_callback_info info)
{
DataSharePredicatesProxy *predicatesProxy = nullptr;
napi_value thiz;
napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr);
napi_unwrap(env, thiz, reinterpret_cast<void **>(&predicatesProxy));
return predicatesProxy->predicates_;
}
napi_value DataSharePredicatesProxy::EqualTo(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::EqualTo on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::EqualTo Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
napi_valuetype valueType = napi_undefined;
napi_status status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok) {
LOG_ERROR("napi_typeof status : %{public}d", status);
return thiz;
}
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
switch (valueType) {
case napi_number: {
double value;
napi_get_value_double(env, args[1], &value);
nativePredicates->EqualTo(field, value);
break;
}
case napi_boolean: {
bool value = false;
napi_get_value_bool(env, args[1], &value);
nativePredicates->EqualTo(field, value);
break;
}
case napi_string: {
std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
nativePredicates->EqualTo(field, value);
break;
}
default:
break;
}
return thiz;
}
napi_value DataSharePredicatesProxy::NotEqualTo(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::NotEqualTo on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::NotEqualTo Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
napi_valuetype valueType = napi_undefined;
napi_status status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok) {
LOG_ERROR("napi_typeof status : %{public}d", status);
return thiz;
}
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
switch (valueType) {
case napi_number: {
double value;
napi_get_value_double(env, args[1], &value);
nativePredicates->NotEqualTo(field, value);
break;
}
case napi_boolean: {
bool value = false;
napi_get_value_bool(env, args[1], &value);
nativePredicates->NotEqualTo(field, value);
break;
}
case napi_string: {
std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
nativePredicates->NotEqualTo(field, value);
break;
}
default:
break;
}
return thiz;
}
napi_value DataSharePredicatesProxy::BeginWrap(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::BeginWrap on called.");
napi_value thiz;
napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->BeginWrap();
return thiz;
}
napi_value DataSharePredicatesProxy::EndWrap(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::EndWrap on called.");
napi_value thiz;
napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->EndWrap();
return thiz;
}
napi_value DataSharePredicatesProxy::Or(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Or on called.");
napi_value thiz;
napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Or();
return thiz;
}
napi_value DataSharePredicatesProxy::And(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::And on called.");
napi_value thiz;
napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->And();
return thiz;
}
napi_value DataSharePredicatesProxy::Contains(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Contains on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Contains Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Contains(field, value);
return thiz;
}
napi_value DataSharePredicatesProxy::BeginsWith(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::BeginsWith on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::BeginsWith Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->BeginsWith(field, value);
return thiz;
}
napi_value DataSharePredicatesProxy::EndsWith(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::EndsWith on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::EndsWith Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->EndsWith(field, value);
return thiz;
}
napi_value DataSharePredicatesProxy::IsNull(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::IsNull on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::IsNull Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->IsNull(field);
return thiz;
}
napi_value DataSharePredicatesProxy::IsNotNull(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::IsNotNull on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::IsNotNull Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->IsNotNull(field);
return thiz;
}
napi_value DataSharePredicatesProxy::Like(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Like on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Like Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Like(field, value);
return thiz;
}
napi_value DataSharePredicatesProxy::Unlike(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Unlike on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Unlike Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Unlike(field, value);
return thiz;
}
napi_value DataSharePredicatesProxy::Glob(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Glob on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Glob Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string value = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Glob(field, value);
return thiz;
}
napi_value DataSharePredicatesProxy::Between(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Between on called.");
napi_value thiz;
size_t argc = 3;
napi_value args[3] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_TWO, "DataSharePredicatesProxy::Between Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string low = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::string high = DataShareJSUtils::ConvertAny2String(env, args[2]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Between(field, low, high);
return thiz;
}
napi_value DataSharePredicatesProxy::NotBetween(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::NotBetween on called.");
napi_value thiz;
size_t argc = 3;
napi_value args[3] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_TWO, "DataSharePredicatesProxy::NotBetween Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::string low = DataShareJSUtils::ConvertAny2String(env, args[1]);
std::string high = DataShareJSUtils::ConvertAny2String(env, args[2]);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->NotBetween(field, low, high);
return thiz;
}
napi_value DataSharePredicatesProxy::GreaterThan(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::GreaterThan on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::GreaterThan Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
napi_valuetype valueType = napi_undefined;
napi_status status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok) {
LOG_ERROR("napi_typeof status : %{public}d", status);
return thiz;
}
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
switch (valueType) {
case napi_number: {
double value;
napi_get_value_double(env, args[1], &value);
nativePredicates->GreaterThan(field, value);
break;
}
case napi_string: {
std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
nativePredicates->GreaterThan(field, value);
break;
}
default:
break;
}
return thiz;
}
napi_value DataSharePredicatesProxy::LessThan(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::LessThan on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::LessThan Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
napi_valuetype valueType = napi_undefined;
napi_status status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok) {
LOG_ERROR("napi_typeof status : %{public}d", status);
return thiz;
}
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
switch (valueType) {
case napi_number: {
double value;
napi_get_value_double(env, args[1], &value);
nativePredicates->LessThan(field, value);
break;
}
case napi_string: {
std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
nativePredicates->LessThan(field, value);
break;
}
default:
break;
}
return thiz;
}
napi_value DataSharePredicatesProxy::GreaterThanOrEqualTo(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::GreaterThanOrEqualTo on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::GreaterThanOrEqualTo Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
napi_valuetype valueType = napi_undefined;
napi_status status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok) {
LOG_ERROR("napi_typeof status : %{public}d", status);
return thiz;
}
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
switch (valueType) {
case napi_number: {
double value;
napi_get_value_double(env, args[1], &value);
nativePredicates->GreaterThanOrEqualTo(field, value);
break;
}
case napi_string: {
std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
nativePredicates->GreaterThanOrEqualTo(field, value);
break;
}
default:
break;
}
return thiz;
}
napi_value DataSharePredicatesProxy::LessThanOrEqualTo(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::LessThanOrEqualTo on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::LessThanOrEqualTo Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
napi_valuetype valueType = napi_undefined;
napi_status status = napi_typeof(env, args[1], &valueType);
if (status != napi_ok) {
LOG_ERROR("napi_typeof status : %{public}d", status);
return thiz;
}
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
switch (valueType) {
case napi_number: {
double value;
napi_get_value_double(env, args[1], &value);
nativePredicates->LessThanOrEqualTo(field, value);
break;
}
case napi_string: {
std::string value = DataShareJSUtils::Convert2String(env, args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
nativePredicates->LessThanOrEqualTo(field, value);
break;
}
default:
break;
}
return thiz;
}
napi_value DataSharePredicatesProxy::OrderByAsc(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::OrderByAsc on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::OrderByAsc Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->OrderByAsc(field);
return thiz;
}
napi_value DataSharePredicatesProxy::OrderByDesc(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::OrderByDesc on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::OrderByDesc Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->OrderByDesc(field);
return thiz;
}
napi_value DataSharePredicatesProxy::Distinct(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Distinct on called.");
napi_value thiz;
napi_get_cb_info(env, info, nullptr, nullptr, &thiz, nullptr);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Distinct();
return thiz;
}
napi_value DataSharePredicatesProxy::Limit(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::Limit on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::Limit Invalid argvs!");
int number = 0;
napi_status status = napi_get_value_int32(env, args[0], &number);
LOG_INFO("number, napi_get_value_int32 : %{public}d", status);
int offset = 0;
status = napi_get_value_int32(env, args[1], &offset);
LOG_INFO("offset, napi_get_value_int32 : %{public}d", status);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->Limit(number, offset);
return thiz;
}
napi_value DataSharePredicatesProxy::GroupBy(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::GroupBy on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::GroupBy Invalid argvs!");
std::vector<std::string> fields = DataShareJSUtils::Convert2StrVector(env,
args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->GroupBy(fields);
return thiz;
}
napi_value DataSharePredicatesProxy::IndexedBy(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::IndexedBy on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::IndexedBy Invalid argvs!");
std::string indexName = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->IndexedBy(indexName);
return thiz;
}
napi_value DataSharePredicatesProxy::In(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::In on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::In Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::vector<std::string> values = DataShareJSUtils::Convert2StrVector(env,
args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->In(field, values);
return thiz;
}
napi_value DataSharePredicatesProxy::NotIn(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::NotIn on called.");
napi_value thiz;
size_t argc = 2;
napi_value args[2] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ONE, "DataSharePredicatesProxy::NotIn Invalid argvs!");
std::string field = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::vector<std::string> values = DataShareJSUtils::Convert2StrVector(env,
args[1], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->NotIn(field, values);
return thiz;
}
std::shared_ptr<DataSharePredicates> DataSharePredicatesProxy::GetPredicates() const
{
return this->predicates_;
}
napi_value DataSharePredicatesProxy::PrefixKey(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::PrefixKey on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::PrefixKey Invalid argvs!");
std::string prefix = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->KeyPrefix(prefix);
return thiz;
}
napi_value DataSharePredicatesProxy::InKeys(napi_env env, napi_callback_info info)
{
LOG_DEBUG("DataSharePredicatesProxy::InKeys on called.");
napi_value thiz;
size_t argc = 1;
napi_value args[1] = { 0 };
napi_get_cb_info(env, info, &argc, args, &thiz, nullptr);
NAPI_ASSERT(env, argc > ARGC_ZERO, "DataSharePredicatesProxy::InKeys Invalid argvs!");
std::vector<std::string> keys = DataShareJSUtils::Convert2StrVector(env,
args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataSharePredicates> nativePredicates = GetNativePredicates(env, info);
if (nativePredicates == nullptr) {
LOG_ERROR("GetNativePredicates failed.");
return thiz;
}
nativePredicates->InKeys(keys);
return thiz;
}
napi_value GetNapiObject(napi_env env, std::shared_ptr<DataSharePredicates> predicates)
{
return DataSharePredicatesProxy::NewInstance(env, predicates);
}
DataSharePredicates *GetNativePredicatesObject(const napi_env &env, const napi_value &arg)
{
auto predicates = DataSharePredicatesProxy::GetNativePredicates(env, arg);
return predicates.get();
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,492 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_result_set_proxy.h"
#include <functional>
#include "datashare_result_set.h"
#include "datashare_js_utils.h"
#include "string_ex.h"
#include "datashare_log.h"
namespace OHOS {
namespace DataShare {
constexpr int MAX_INPUT_COUNT = 10;
static napi_ref __thread ctorRef_ = nullptr;
napi_value DataShareResultSetProxy::NewInstance(napi_env env, std::shared_ptr<DataShareResultSet> resultSet)
{
napi_value cons = GetConstructor(env);
if (cons == nullptr) {
LOG_ERROR("NewInstance GetConstructor is nullptr!");
return nullptr;
}
napi_value instance;
napi_status status = napi_new_instance(env, cons, 0, nullptr, &instance);
if (status != napi_ok) {
LOG_ERROR("NewInstance napi_new_instance failed! code:%{public}d!", status);
return nullptr;
}
DataShareResultSetProxy *proxy = nullptr;
status = napi_unwrap(env, instance, reinterpret_cast<void **>(&proxy));
if (proxy == nullptr) {
LOG_ERROR("NewInstance native instance is nullptr! code:%{public}d!", status);
return instance;
}
*proxy = std::move(resultSet);
return instance;
}
std::shared_ptr<DataShareResultSet> DataShareResultSetProxy::GetNativeObject(
napi_env const &env, napi_value const &arg)
{
if (arg == nullptr) {
LOG_ERROR("DataShareResultSetProxy GetNativeObject arg is null.");
return nullptr;
}
DataShareResultSetProxy *proxy = nullptr;
napi_unwrap(env, arg, reinterpret_cast<void **>(&proxy));
if (proxy == nullptr) {
LOG_ERROR("DataShareResultSetProxy GetNativeObject proxy is null.");
return nullptr;
}
return proxy->resultSet_;
}
napi_value DataShareResultSetProxy::GetConstructor(napi_env env)
{
napi_value cons;
if (ctorRef_ != nullptr) {
NAPI_CALL(env, napi_get_reference_value(env, ctorRef_, &cons));
return cons;
}
LOG_INFO("GetConstructor result set constructor");
napi_property_descriptor clzDes[] = {
DECLARE_NAPI_FUNCTION("goToFirstRow", GoToFirstRow),
DECLARE_NAPI_FUNCTION("goToLastRow", GoToLastRow),
DECLARE_NAPI_FUNCTION("goToNextRow", GoToNextRow),
DECLARE_NAPI_FUNCTION("goToPreviousRow", GoToPreviousRow),
DECLARE_NAPI_FUNCTION("goTo", GoTo),
DECLARE_NAPI_FUNCTION("goToRow", GoToRow),
DECLARE_NAPI_FUNCTION("getBlob", GetBlob),
DECLARE_NAPI_FUNCTION("getString", GetString),
DECLARE_NAPI_FUNCTION("getLong", GetLong),
DECLARE_NAPI_FUNCTION("getDouble", GetDouble),
DECLARE_NAPI_FUNCTION("close", Close),
DECLARE_NAPI_FUNCTION("getColumnIndex", GetColumnIndex),
DECLARE_NAPI_FUNCTION("getColumnName", GetColumnName),
DECLARE_NAPI_FUNCTION("getDataType", GetDataType),
DECLARE_NAPI_GETTER("columnNames", GetAllColumnNames),
DECLARE_NAPI_GETTER("columnCount", GetColumnCount),
DECLARE_NAPI_GETTER("rowCount", GetRowCount),
DECLARE_NAPI_GETTER("isClosed", IsClosed),
};
NAPI_CALL(env, napi_define_class(env, "DataShareResultSet", NAPI_AUTO_LENGTH, Initialize, nullptr,
sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons));
NAPI_CALL(env, napi_create_reference(env, cons, 1, &ctorRef_));
return cons;
}
napi_value DataShareResultSetProxy::Initialize(napi_env env, napi_callback_info info)
{
napi_value self = nullptr;
NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr));
auto *proxy = new DataShareResultSetProxy();
auto finalize = [](napi_env env, void *data, void *hint) {
DataShareResultSetProxy *proxy = reinterpret_cast<DataShareResultSetProxy *>(data);
delete proxy;
};
napi_status status = napi_wrap(env, self, proxy, finalize, nullptr, nullptr);
if (status != napi_ok) {
LOG_ERROR("DataShareResultSetProxy napi_wrap failed! code:%{public}d!", status);
finalize(env, proxy, nullptr);
return nullptr;
}
return self;
}
DataShareResultSetProxy::~DataShareResultSetProxy()
{
LOG_INFO("DataShareResultSetProxy destructor!");
if (resultSet_ != nullptr && !resultSet_->IsClosed()) {
resultSet_->Close();
}
}
DataShareResultSetProxy::DataShareResultSetProxy(std::shared_ptr<DataShareResultSet> resultSet)
{
if (resultSet_ == resultSet) {
return;
}
resultSet_ = std::move(resultSet);
}
DataShareResultSetProxy &DataShareResultSetProxy::operator=(std::shared_ptr<DataShareResultSet> resultSet)
{
if (resultSet_ == resultSet) {
return *this;
}
resultSet_ = std::move(resultSet);
return *this;
}
std::shared_ptr<DataShareResultSet> &DataShareResultSetProxy::GetInnerResultSet(napi_env env,
napi_callback_info info)
{
DataShareResultSetProxy *resultSet = nullptr;
napi_value self = nullptr;
napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr);
napi_unwrap(env, self, reinterpret_cast<void **>(&resultSet));
return resultSet->resultSet_;
}
napi_value DataShareResultSetProxy::GoToFirstRow(napi_env env, napi_callback_info info)
{
int errCode = E_ERROR;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
errCode = nativeResultSet->GoToFirstRow();
if (errCode != E_OK) {
LOG_ERROR("GoToFirstRow failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK));
}
napi_value DataShareResultSetProxy::GoToLastRow(napi_env env, napi_callback_info info)
{
int errCode = E_ERROR;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
errCode = nativeResultSet->GoToLastRow();
if (errCode != E_OK) {
LOG_ERROR("GoToLastRow failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK));
}
napi_value DataShareResultSetProxy::GoToNextRow(napi_env env, napi_callback_info info)
{
int errCode = E_ERROR;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
errCode = nativeResultSet->GoToNextRow();
if (errCode != E_OK) {
LOG_ERROR("GoToNextRow failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK));
}
napi_value DataShareResultSetProxy::GoToPreviousRow(napi_env env, napi_callback_info info)
{
int errCode = E_ERROR;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
errCode = nativeResultSet->GoToPreviousRow();
if (errCode != E_OK) {
LOG_ERROR("GoToPreviousRow failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK));
}
napi_value DataShareResultSetProxy::GoTo(napi_env env, napi_callback_info info)
{
int32_t offset = -1;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &offset));
int errCode = E_ERROR;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
errCode = nativeResultSet->GoTo(offset);
if (errCode != E_OK) {
LOG_ERROR("GoTo failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK));
}
napi_value DataShareResultSetProxy::GoToRow(napi_env env, napi_callback_info info)
{
int32_t position = -1;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &position));
int errCode = E_ERROR;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
errCode = nativeResultSet->GoToRow(position);
if (errCode != E_OK) {
LOG_ERROR("GoToRow failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK));
}
napi_value DataShareResultSetProxy::GetBlob(napi_env env, napi_callback_info info)
{
int32_t columnIndex = -1;
std::vector<uint8_t> blob;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex));
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetBlob(columnIndex, blob);
if (errCode != E_OK) {
LOG_ERROR("GetBlob failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, blob);
}
napi_value DataShareResultSetProxy::GetString(napi_env env, napi_callback_info info)
{
int32_t columnIndex = -1;
std::string value;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex));
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetString(columnIndex, value);
if (errCode != E_OK) {
LOG_ERROR("GetString failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, value);
}
napi_value DataShareResultSetProxy::GetLong(napi_env env, napi_callback_info info)
{
int32_t columnIndex = -1;
int64_t value = -1;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex));
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetLong(columnIndex, value);
if (errCode != E_OK) {
LOG_ERROR("GetLong failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, value);
}
napi_value DataShareResultSetProxy::GetDouble(napi_env env, napi_callback_info info)
{
int32_t columnIndex = -1;
double value = 0.0;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex));
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetDouble(columnIndex, value);
if (errCode != E_OK) {
LOG_ERROR("GetDouble failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, value);
}
napi_value DataShareResultSetProxy::Close(napi_env env, napi_callback_info info)
{
int errCode = E_ERROR;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
errCode = nativeResultSet->Close();
if (errCode != E_OK) {
LOG_ERROR("Close failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, (errCode == E_OK));
}
napi_value DataShareResultSetProxy::GetColumnIndex(napi_env env, napi_callback_info info)
{
int32_t columnIndex = -1;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
std::string columnName = DataShareJSUtils::Convert2String(env, args[0], DataShareJSUtils::DEFAULT_BUF_SIZE);
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetColumnIndex(columnName, columnIndex);
if (errCode != E_OK) {
LOG_ERROR("GetColumnIndex failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, columnIndex);
}
napi_value DataShareResultSetProxy::GetColumnName(napi_env env, napi_callback_info info)
{
int32_t columnIndex = -1;
std::string columnName;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex));
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetColumnName(columnIndex, columnName);
if (errCode != E_OK) {
LOG_ERROR("GetColumnName failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, columnName);
}
napi_value DataShareResultSetProxy::GetDataType(napi_env env, napi_callback_info info)
{
int32_t columnIndex = -1;
DataType dataType = DataType::TYPE_NULL;
size_t argc = MAX_INPUT_COUNT;
napi_value args[MAX_INPUT_COUNT] = { 0 };
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
NAPI_ASSERT(env, argc > 0, "Invalid argvs!");
NAPI_CALL(env, napi_get_value_int32(env, args[0], &columnIndex));
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetDataType(columnIndex, dataType);
if (errCode != E_OK) {
LOG_ERROR("GetDataType failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, int32_t(dataType));
}
napi_value DataShareResultSetProxy::GetAllColumnNames(napi_env env, napi_callback_info info)
{
std::vector<std::string> columnNames;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetAllColumnNames(columnNames);
if (errCode != E_OK) {
LOG_ERROR("GetAllColumnNames failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, columnNames);
}
napi_value DataShareResultSetProxy::GetColumnCount(napi_env env, napi_callback_info info)
{
int32_t count = -1;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetColumnCount(count);
if (errCode != E_OK) {
LOG_ERROR("GetColumnCount failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, count);
}
napi_value DataShareResultSetProxy::GetRowCount(napi_env env, napi_callback_info info)
{
int32_t count = -1;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
int errCode = nativeResultSet->GetRowCount(count);
if (errCode != E_OK) {
LOG_ERROR("GetRowCount failed code:%{public}d", errCode);
}
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
return DataShareJSUtils::Convert2JSValue(env, count);
}
napi_value DataShareResultSetProxy::IsClosed(napi_env env, napi_callback_info info)
{
bool result = false;
std::shared_ptr<DataShareResultSet> nativeResultSet = GetInnerResultSet(env, info);
if (nativeResultSet != nullptr) {
result = nativeResultSet->IsClosed();
} else {
LOG_ERROR("GetInnerResultSet failed.");
}
napi_value output;
napi_get_boolean(env, result, &output);
return output;
}
napi_value GetNapiResultSetObject(napi_env env, DataShareResultSet *resultSet)
{
return DataShareResultSetProxy::NewInstance(env, std::shared_ptr<DataShareResultSet>(resultSet));
}
DataShareResultSet *GetResultSetProxyObject(const napi_env &env, const napi_value &arg)
{
// the resultSet maybe release.
auto resultSet = DataShareResultSetProxy::GetNativeObject(env, arg);
return resultSet.get();
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,133 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "napi_datashare_values_bucket.h"
#include "datashare_log.h"
#include "datashare_js_utils.h"
#include "datashare_value_object.h"
#include "securec.h"
namespace OHOS {
namespace DataShare {
napi_value DataShareValueBucketNewInstance(napi_env env, DataShareValuesBucket &valuesBucket)
{
napi_value ret;
NAPI_CALL(env, napi_create_object(env, &ret));
std::map<std::string, DataShareValueObject> valuesMap;
valuesBucket.GetAll(valuesMap);
std::map<std::string, DataShareValueObject>::iterator it;
for (it = valuesMap.begin(); it != valuesMap.end(); ++it) {
std::string key = it->first;
auto valueObject = it->second;
napi_value value = nullptr;
switch (valueObject.GetType()) {
case DataShareValueObjectType::TYPE_NULL: {
value = nullptr;
} break;
case DataShareValueObjectType::TYPE_INT: {
int64_t intVal = 0;
valueObject.GetLong(intVal);
value = DataShareJSUtils::Convert2JSValue(env, intVal);
} break;
case DataShareValueObjectType::TYPE_DOUBLE: {
double doubleVal = 0L;
valueObject.GetDouble(doubleVal);
value = DataShareJSUtils::Convert2JSValue(env, doubleVal);
} break;
case DataShareValueObjectType::TYPE_BLOB: {
std::vector<uint8_t> blobVal;
valueObject.GetBlob(blobVal);
value = DataShareJSUtils::Convert2JSValue(env, blobVal);
} break;
case DataShareValueObjectType::TYPE_BOOL: {
bool boolVal = false;
valueObject.GetBool(boolVal);
value = DataShareJSUtils::Convert2JSValue(env, boolVal);
} break;
default: {
std::string strVal = "";
valueObject.GetString(strVal);
value = DataShareJSUtils::Convert2JSValue(env, strVal);
} break;
}
NAPI_CALL(env, napi_set_named_property(env, ret, key.c_str(), value));
}
return ret;
}
void SetValuesBucketObject(
DataShareValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value)
{
napi_valuetype valueType = napi_undefined;
napi_typeof(env, value, &valueType);
if (valueType == napi_string) {
std::string valueString = DataShareJSUtils::UnwrapStringFromJS(env, value);
LOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:%{public}s",
valueType, keyStr.c_str(), valueString.c_str());
valuesBucket.PutString(keyStr, valueString);
} else if (valueType == napi_number) {
double valueNumber = 0;
napi_get_value_double(env, value, &valueNumber);
valuesBucket.PutDouble(keyStr, valueNumber);
LOG_INFO(
"ValueObject type:%{public}d, key:%{public}s, value:%{public}lf", valueType, keyStr.c_str(), valueNumber);
} else if (valueType == napi_boolean) {
bool valueBool = false;
napi_get_value_bool(env, value, &valueBool);
LOG_INFO(
"ValueObject type:%{public}d, key:%{public}s, value:%{public}d", valueType, keyStr.c_str(), valueBool);
valuesBucket.PutBool(keyStr, valueBool);
} else if (valueType == napi_null) {
valuesBucket.PutNull(keyStr);
LOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:null", valueType, keyStr.c_str());
} else if (valueType == napi_object) {
LOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:Uint8Array", valueType, keyStr.c_str());
valuesBucket.PutBlob(keyStr, DataShareJSUtils::Convert2U8Vector(env, value));
} else {
LOG_ERROR("valuesBucket error");
}
}
void AnalysisValuesBucket(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg)
{
napi_value keys = 0;
napi_get_property_names(env, arg, &keys);
uint32_t arrLen = 0;
napi_status status = napi_get_array_length(env, keys, &arrLen);
if (status != napi_ok) {
LOG_ERROR("ValuesBucket errr");
return;
}
LOG_INFO("ValuesBucket num : %{public}u", arrLen);
for (size_t i = 0; i < arrLen; ++i) {
napi_value key = 0;
status = napi_get_element(env, keys, i, &key);
std::string keyStr = DataShareJSUtils::UnwrapStringFromJS(env, key);
napi_value value = 0;
napi_get_property(env, arg, key, &value);
SetValuesBucketObject(valuesBucket, env, keyStr, value);
}
}
void GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg)
{
AnalysisValuesBucket(valuesBucket, env, arg);
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,91 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//foundation/distributeddatamgr/data_share/datashare.gni")
ohos_shared_library("datashare") {
include_dirs = [
"${datashare_napi_path}/dataShare/include",
"${datashare_common_napi_path}/include",
"${datashare_common_native_path}/include",
]
sources = [
"${datashare_napi_path}/dataShare/src/async_call.cpp",
"${datashare_napi_path}/dataShare/src/napi_datashare_helper.cpp",
"${datashare_napi_path}/dataShare/src/napi_datashare_observer.cpp",
"${datashare_napi_path}/dataShare/src/native_datashare_module.cpp",
]
deps = [
"${ability_runtime_inner_api_path}/dataobs_manager:dataobs_manager",
"${ability_runtime_napi_path}/inner/napi_common:napi_common",
"${datashare_innerapi_path}/common:datashare_common",
"//third_party/libuv:uv",
]
external_deps = [
"ability_base:base",
"ability_base:want",
"ability_base:zuri",
"ability_runtime:abilitykit_native",
"ability_runtime:napi_base_context",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"data_share:datashare_abilitykit",
"data_share:datashare_common",
"eventhandler:libeventhandler",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
"relational_store:native_appdatafwk",
"relational_store:native_dataability",
"relational_store:native_rdb",
]
relative_install_dir = "module/data"
subsystem_name = "distributeddatamgr"
part_name = "data_share"
}
ohos_shared_library("datasharepredicates") {
include_dirs = [
"${datashare_common_napi_path}/include",
"${datashare_common_native_path}/include",
]
sources = [
"${datashare_common_napi_path}/src/datashare_predicates_proxy.cpp",
"${datashare_napi_path}/dataShare/src/native_datashare_predicates_module.cpp",
]
deps = [ "${datashare_innerapi_path}/common:datashare_common" ]
external_deps = [
"c_utils:utils",
"data_share:datashare_abilitykit",
"data_share:datashare_common",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
]
relative_install_dir = "module/data"
subsystem_name = "distributeddatamgr"
part_name = "data_share"
}

View File

@ -1,105 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_ASYNC_CALL_H
#define DATASHARE_ASYNC_CALL_H
#include <functional>
#include <memory>
#include "datashare_js_utils.h"
#include "napi/native_common.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS::DataShare {
class AsyncCall final {
public:
class Context {
public:
using InputAction = std::function<napi_status(napi_env, size_t, napi_value *, napi_value)>;
using OutputAction = std::function<napi_status(napi_env, napi_value *)>;
using ExecAction = std::function<void(Context *)>;
Context(InputAction input, OutputAction output): input_(std::move(input)), output_(std::move(output)) {};
virtual ~Context() {};
void SetAction(InputAction input, OutputAction output = nullptr)
{
input_ = input;
output_ = output;
}
void SetAction(OutputAction output)
{
SetAction(nullptr, std::move(output));
}
virtual napi_status operator()(napi_env env, size_t argc, napi_value *argv, napi_value self)
{
if (input_ == nullptr) {
return napi_ok;
}
return input_(env, argc, argv, self);
}
virtual napi_status operator()(napi_env env, napi_value *result)
{
if (output_ == nullptr) {
*result = nullptr;
return napi_ok;
}
return output_(env, result);
}
virtual void Exec()
{
if (exec_ == nullptr) {
return;
}
exec_(this);
};
protected:
friend class AsyncCall;
InputAction input_ = nullptr;
OutputAction output_ = nullptr;
ExecAction exec_ = nullptr;
};
// The default AsyncCallback in the parameters is at the end position.
static constexpr size_t ASYNC_DEFAULT_POS = -1;
AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr<Context> context);
~AsyncCall();
napi_value Call(napi_env env, Context::ExecAction exec = nullptr);
napi_value SyncCall(napi_env env, Context::ExecAction exec = nullptr);
private:
enum {
ARG_ERROR,
ARG_DATA,
ARG_BUTT
};
static void OnExecute(napi_env env, void *data);
static void OnComplete(napi_env env, napi_status status, void *data);
struct AsyncContext {
std::shared_ptr<Context> ctx = nullptr;
napi_ref callback = nullptr;
napi_ref self = nullptr;
napi_deferred defer = nullptr;
napi_async_work work = nullptr;
};
static void DeleteContext(napi_env env, AsyncContext *context);
AsyncContext *context_ = nullptr;
napi_env env_ = nullptr;
};
}
#endif // DATASHARE_ASYNC_CALL_H

View File

@ -1,52 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_COMMON_H
#define DATASHARE_COMMON_H
#include "ability.h"
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
#include "napi_common.h"
#include "datashare_helper.h"
using Ability = OHOS::AppExecFwk::Ability;
namespace OHOS {
namespace DataShare {
using namespace AppExecFwk;
struct CBBase {
CallbackInfo cbInfo;
napi_async_work asyncWork;
napi_deferred deferred;
Ability *ability = nullptr;
AbilityType abilityType = AbilityType::UNKNOWN;
int errCode = 0;
};
class NAPIDataShareObserver;
struct DSHelperOnOffCB {
CBBase cbBase;
DataShareHelper *dataShareHelper = nullptr;
sptr<NAPIDataShareObserver> observer;
std::string uri;
int result = 0;
std::vector<DSHelperOnOffCB *> NotifyList;
std::vector<DSHelperOnOffCB *> DestoryList;
};
} // namespace DataShare
} // namespace OHOS
#endif /* DATASHARE_COMMON_H */

View File

@ -1,88 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NAPI_DATASHARE_HELPER_H
#define NAPI_DATASHARE_HELPER_H
#include "async_call.h"
#include "datashare_helper.h"
#include "data_share_common.h"
#include "napi_datashare_observer.h"
namespace OHOS {
namespace DataShare {
class NapiDataShareHelper {
public:
static napi_value Napi_CreateDataShareHelper(napi_env env, napi_callback_info info);
static napi_value Napi_OpenFile(napi_env env, napi_callback_info info);
static napi_value Napi_On(napi_env env, napi_callback_info info);
static napi_value Napi_Off(napi_env env, napi_callback_info info);
static napi_value Napi_Insert(napi_env env, napi_callback_info info);
static napi_value Napi_Delete(napi_env env, napi_callback_info info);
static napi_value Napi_Query(napi_env env, napi_callback_info info);
static napi_value Napi_Update(napi_env env, napi_callback_info info);
static napi_value Napi_BatchInsert(napi_env env, napi_callback_info info);
static napi_value Napi_GetType(napi_env env, napi_callback_info info);
static napi_value Napi_GetFileTypes(napi_env env, napi_callback_info info);
static napi_value Napi_NormalizeUri(napi_env env, napi_callback_info info);
static napi_value Napi_DenormalizeUri(napi_env env, napi_callback_info info);
static napi_value Napi_NotifyChange(napi_env env, napi_callback_info info);
private:
static napi_value GetConstructor(napi_env env);
static napi_value Initialize(napi_env env, napi_callback_info info);
std::shared_ptr<DataShareHelper> datashareHelper_ = nullptr;
std::map<std::string, sptr<NAPIDataShareObserver>> observerMap_;
struct ContextInfo : public AsyncCall::Context {
NapiDataShareHelper *proxy = nullptr;
napi_status status = napi_generic_failure;
int resultNumber = 0;
std::shared_ptr<DataShareResultSet> resultObject = nullptr;
std::string resultString = "";
std::vector<std::string> resultStrArr;
std::string uri;
std::string mode;
DataShareValuesBucket valueBucket;
DataSharePredicates predicates;
std::vector<std::string> columns;
std::vector<DataShareValuesBucket> values;
std::string mimeTypeFilter;
ContextInfo() : Context(nullptr, nullptr) {};
ContextInfo(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {};
virtual ~ContextInfo() {};
napi_status operator()(napi_env env, size_t argc, napi_value *argv, napi_value self) override
{
NAPI_ASSERT_BASE(env, self != nullptr, "self is nullptr", napi_invalid_arg);
NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast<void **>(&proxy)), napi_invalid_arg);
NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no native upload task", napi_invalid_arg);
return Context::operator()(env, argc, argv, self);
}
napi_status operator()(napi_env env, napi_value *result) override
{
if (status != napi_ok) {
return status;
}
return Context::operator()(env, result);
}
};
};
} // namespace DataShare
} // namespace OHOS
#endif /* NAPI_DATASHARE_HELPER_H */

View File

@ -1,45 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NAPI_DATASHARE_OBSERVER_H
#define NAPI_DATASHARE_OBSERVER_H
#include <uv.h>
#include "data_ability_observer_stub.h"
#include "napi/native_common.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace DataShare {
class NAPIDataShareObserver : public AAFwk::DataAbilityObserverStub {
public:
NAPIDataShareObserver(napi_env env, napi_value callback);
virtual ~NAPIDataShareObserver();
void OnChange() override;
void DeleteReference();
private:
struct ObserverWorker {
const NAPIDataShareObserver *observer_ = nullptr;
ObserverWorker(const NAPIDataShareObserver *observerIn) : observer_(observerIn) {}
};
napi_env env_ = nullptr;
napi_ref ref_ = nullptr;
uv_loop_s *loop_ = nullptr;
};
} // namespace DataShare
} // namespace OHOS
#endif /* DATASHARE_COMMON_H */

View File

@ -1,145 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "async_call.h"
#include "datashare_log.h"
#include "napi_common_data.h"
namespace OHOS::DataShare {
AsyncCall::AsyncCall(napi_env env, napi_callback_info info, std::shared_ptr<Context> context)
: env_(env)
{
context_ = new AsyncContext();
size_t argc = ARGS_MAX_COUNT;
napi_value self = nullptr;
napi_value argv[ARGS_MAX_COUNT] = {nullptr};
NAPI_CALL_RETURN_VOID(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
napi_valuetype valueType = napi_undefined;
napi_typeof(env, argv[argc - 1], &valueType);
if (valueType == napi_function) {
napi_create_reference(env, argv[argc - 1], 1, &context_->callback);
argc = argc - 1;
}
NAPI_CALL_RETURN_VOID(env, (*context)(env, argc, argv, self));
context_->ctx = std::move(context);
napi_create_reference(env, self, 1, &context_->self);
}
AsyncCall::~AsyncCall()
{
if (context_ == nullptr) {
return;
}
DeleteContext(env_, context_);
}
napi_value AsyncCall::Call(napi_env env, Context::ExecAction exec)
{
if ((context_ == nullptr) || (context_->ctx == nullptr)) {
LOG_DEBUG("context_ or context_->ctx is null");
return nullptr;
}
LOG_DEBUG("async call exec");
context_->ctx->exec_ = std::move(exec);
napi_value promise = nullptr;
if (context_->callback == nullptr) {
napi_create_promise(env, &context_->defer, &promise);
} else {
napi_get_undefined(env, &promise);
}
napi_async_work work = context_->work;
napi_value resource = nullptr;
napi_create_string_utf8(env, "AsyncCall", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(env, nullptr, resource, AsyncCall::OnExecute, AsyncCall::OnComplete, context_, &work);
context_->work = work;
context_ = nullptr;
napi_queue_async_work(env, work);
LOG_DEBUG("async call exec");
return promise;
}
napi_value AsyncCall::SyncCall(napi_env env, AsyncCall::Context::ExecAction exec)
{
if ((context_ == nullptr) || (context_->ctx == nullptr)) {
LOG_DEBUG("context_ or context_->ctx is null");
return nullptr;
}
context_->ctx->exec_ = std::move(exec);
napi_value promise = nullptr;
if (context_->callback == nullptr) {
napi_create_promise(env, &context_->defer, &promise);
} else {
napi_get_undefined(env, &promise);
}
AsyncCall::OnExecute(env, context_);
AsyncCall::OnComplete(env, napi_ok, context_);
return promise;
}
void AsyncCall::OnExecute(napi_env env, void *data)
{
LOG_DEBUG("run the async runnable");
AsyncContext *context = reinterpret_cast<AsyncContext *>(data);
context->ctx->Exec();
}
void AsyncCall::OnComplete(napi_env env, napi_status status, void *data)
{
LOG_DEBUG("run the js callback function");
AsyncContext *context = reinterpret_cast<AsyncContext *>(data);
napi_value output = nullptr;
napi_status runStatus = (*context->ctx)(env, &output);
napi_value result[ARG_BUTT] = { 0 };
if (status == napi_ok && runStatus == napi_ok) {
napi_get_undefined(env, &result[ARG_ERROR]);
if (output != nullptr) {
result[ARG_DATA] = output;
} else {
napi_get_undefined(env, &result[ARG_DATA]);
}
} else {
napi_value message = nullptr;
napi_create_string_utf8(env, "async call failed", NAPI_AUTO_LENGTH, &message);
napi_create_error(env, nullptr, message, &result[ARG_ERROR]);
napi_get_undefined(env, &result[ARG_DATA]);
}
if (context->defer != nullptr) {
// promise
if (status == napi_ok && runStatus == napi_ok) {
napi_resolve_deferred(env, context->defer, result[ARG_DATA]);
} else {
napi_reject_deferred(env, context->defer, result[ARG_ERROR]);
}
} else {
// callback
napi_value callback = nullptr;
napi_get_reference_value(env, context->callback, &callback);
napi_value returnValue;
napi_call_function(env, nullptr, callback, ARG_BUTT, result, &returnValue);
}
DeleteContext(env, context);
}
void AsyncCall::DeleteContext(napi_env env, AsyncContext *context)
{
if (env != nullptr) {
napi_delete_reference(env, context->callback);
napi_delete_reference(env, context->self);
napi_delete_async_work(env, context->work);
}
delete context;
}
}

View File

@ -1,753 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "napi_datashare_helper.h"
#include "napi_common_util.h"
#include "datashare_helper.h"
#include "datashare_log.h"
#include "napi_base_context.h"
#include "napi_datashare_values_bucket.h"
#include "datashare_predicates_proxy.h"
#include "datashare_result_set_proxy.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace DataShare {
constexpr int MAX_ARGC = 6;
std::list<std::shared_ptr<DataShareHelper>> g_dataShareHelperList;
void UnwrapDataSharePredicates(DataSharePredicates &predicates, napi_env env, napi_value value)
{
auto tempPredicates = DataSharePredicatesProxy::GetNativePredicates(env, value);
if (tempPredicates == nullptr) {
LOG_ERROR("UnwrapDataSharePredicates GetNativePredicates retval Marshalling failed.");
return;
}
predicates = *tempPredicates;
}
bool UnwrapValuesBucketArrayFromJS(napi_env env, napi_value param, std::vector<DataShareValuesBucket> &value)
{
LOG_INFO("UnwrapValuesBucketArrayFromJS in");
uint32_t arraySize = 0;
napi_value jsValue = nullptr;
std::string strValue = "";
if (!IsArrayForNapiValue(env, param, arraySize)) {
LOG_INFO("IsArrayForNapiValue is false");
return false;
}
value.clear();
for (uint32_t i = 0; i < arraySize; i++) {
jsValue = nullptr;
if (napi_get_element(env, param, i, &jsValue) != napi_ok) {
LOG_INFO("napi_get_element is false");
return false;
}
DataShareValuesBucket valueBucket;
valueBucket.Clear();
GetValueBucketObject(valueBucket, env, jsValue);
value.push_back(valueBucket);
}
LOG_INFO("UnwrapValuesBucketArrayFromJS out");
return true;
}
std::vector<DataShareValuesBucket> GetValuesBucketArray(napi_env env, napi_value param)
{
LOG_INFO("NapiValueObject in");
std::vector<DataShareValuesBucket> result;
UnwrapValuesBucketArrayFromJS(env, param, result);
return result;
}
napi_value NapiDataShareHelper::Napi_CreateDataShareHelper(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_CreateDataShareHelper in");
struct CreateContextInfo {
napi_ref ref = nullptr;
};
auto ctxInfo = std::make_shared<CreateContextInfo>();
auto input = [ctxInfo](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
LOG_DEBUG("CreateDataShareHelper parser to native params %{public}d", static_cast<int>(argc));
NAPI_ASSERT_BASE(env, (argc > 1) && (argc < 4), " need 2 or 3 parameters!", napi_invalid_arg);
napi_value helperProxy = nullptr;
napi_status status = napi_new_instance(env, GetConstructor(env), argc, argv, &helperProxy);
if ((helperProxy == nullptr) || (status != napi_ok)) {
return napi_generic_failure;
}
napi_create_reference(env, helperProxy, 1, &(ctxInfo->ref));
return napi_ok;
};
auto output = [ctxInfo](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_reference_value(env, ctxInfo->ref, result);
napi_delete_reference(env, ctxInfo->ref);
return status;
};
auto context = std::make_shared<AsyncCall::Context>(input, output);
AsyncCall asyncCall(env, info, context);
return asyncCall.Call(env);
}
napi_value NapiDataShareHelper::GetConstructor(napi_env env)
{
napi_value cons = nullptr;
napi_property_descriptor clzDes[] = {
DECLARE_NAPI_FUNCTION("openFile", Napi_OpenFile),
DECLARE_NAPI_FUNCTION("on", Napi_On),
DECLARE_NAPI_FUNCTION("off", Napi_Off),
DECLARE_NAPI_FUNCTION("insert", Napi_Insert),
DECLARE_NAPI_FUNCTION("delete", Napi_Delete),
DECLARE_NAPI_FUNCTION("query", Napi_Query),
DECLARE_NAPI_FUNCTION("update", Napi_Update),
DECLARE_NAPI_FUNCTION("batchInsert", Napi_BatchInsert),
DECLARE_NAPI_FUNCTION("getType", Napi_GetType),
DECLARE_NAPI_FUNCTION("getFileTypes", Napi_GetFileTypes),
DECLARE_NAPI_FUNCTION("normalizeUri", Napi_NormalizeUri),
DECLARE_NAPI_FUNCTION("denormalizeUri", Napi_DenormalizeUri),
DECLARE_NAPI_FUNCTION("notifyChange", Napi_NotifyChange),
};
NAPI_CALL(env, napi_define_class(env, "DataShareHelper", NAPI_AUTO_LENGTH, Initialize, nullptr,
sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons));
g_dataShareHelperList.clear();
return cons;
}
napi_value NapiDataShareHelper::Initialize(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Initialize in");
napi_value self = nullptr;
size_t argc = ARGS_MAX_COUNT;
napi_value argv[ARGS_MAX_COUNT] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
NAPI_ASSERT(env, argc > 1, "Wrong number of arguments");
auto *proxy = new NapiDataShareHelper();
std::string strUri;
bool isStageMode = false;
napi_status status = AbilityRuntime::IsStageContext(env, argv[PARAM0], isStageMode);
if (status != napi_ok || !isStageMode) {
auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env);
strUri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
NAPI_ASSERT(env, ability != nullptr, "DataShareHelperConstructor: failed to get native ability");
LOG_INFO("FA Model: strUri = %{public}s", strUri.c_str());
proxy->datashareHelper_ = DataShareHelper::Creator(ability->GetContext(), strUri);
} else {
auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]);
strUri = DataShareJSUtils::Convert2String(env, argv[PARAM1]);
NAPI_ASSERT(env, context != nullptr, "DataShareHelperConstructor: failed to get native context");
LOG_INFO("Stage Model: strUri = %{public}s", strUri.c_str());
proxy->datashareHelper_ = DataShareHelper::Creator(context, strUri);
}
NAPI_ASSERT(env, proxy->datashareHelper_ != nullptr, "proxy->datashareHelper_ is nullptr");
g_dataShareHelperList.emplace_back(proxy->datashareHelper_);
auto finalize = [](napi_env env, void * data, void * hint) {
NapiDataShareHelper *proxy = reinterpret_cast<NapiDataShareHelper *>(data);
if (proxy != nullptr) {
auto it = proxy->observerMap_.begin();
while (it != proxy->observerMap_.end()) {
if (proxy->datashareHelper_ != nullptr) {
proxy->datashareHelper_->UnregisterObserver(Uri(it->first), it->second);
}
it->second->DeleteReference();
}
proxy->observerMap_.clear();
delete proxy;
}
};
if (napi_wrap(env, self, proxy, finalize, nullptr, nullptr) != napi_ok) {
finalize(env, proxy, nullptr);
return nullptr;
}
return self;
}
napi_value NapiDataShareHelper::Napi_OpenFile(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_OpenFile in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
napi_typeof(env, argv[PARAM1], &valuetype);
if (valuetype == napi_string) {
context->mode = DataShareJSUtils::Convert2String(env, argv[PARAM1]);
LOG_INFO("mode : %{public}s", context->mode.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_int32(env, context->resultNumber, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultNumber = context->proxy->datashareHelper_->OpenFile(uri, context->mode);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_Insert(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_Insert in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
context->valueBucket.Clear();
GetValueBucketObject(context->valueBucket, env, argv[PARAM1]);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_int32(env, context->resultNumber, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultNumber = context->proxy->datashareHelper_->Insert(uri, context->valueBucket);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_Delete(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_Delete in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
UnwrapDataSharePredicates(context->predicates, env, argv[PARAM1]);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_int32(env, context->resultNumber, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultNumber = context->proxy->datashareHelper_->Delete(uri, context->predicates);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_Query(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_Query in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 3 || argc == 4, " should 3 or 4 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
UnwrapDataSharePredicates(context->predicates, env, argv[PARAM1]);
context->columns = DataShareJSUtils::Convert2StrVector(env, argv[PARAM2], DataShareJSUtils::DEFAULT_BUF_SIZE);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
*result = DataShareResultSetProxy::NewInstance(env, context->resultObject);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultObject =
context->proxy->datashareHelper_->Query(uri, context->predicates, context->columns);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_Update(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_Update in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 3 || argc == 4, " should 3 or 4 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
UnwrapDataSharePredicates(context->predicates, env, argv[PARAM1]);
context->valueBucket.Clear();
GetValueBucketObject(context->valueBucket, env, argv[PARAM2]);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_int32(env, context->resultNumber, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultNumber =
context->proxy->datashareHelper_->Update(uri, context->predicates, context->valueBucket);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_BatchInsert(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_BatchInsert in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
context->values = GetValuesBucketArray(env, argv[PARAM1]);
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_int32(env, context->resultNumber, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultNumber = context->proxy->datashareHelper_->BatchInsert(uri, context->values);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_GetType(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_GetType in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_string_utf8(env, context->resultString.c_str(), NAPI_AUTO_LENGTH, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultString = context->proxy->datashareHelper_->GetType(uri);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_GetFileTypes(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_GetFileTypes in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 2 || argc == 3, " should 2 or 3 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
napi_typeof(env, argv[PARAM1], &valuetype);
if (valuetype == napi_string) {
context->mimeTypeFilter = DataShareJSUtils::Convert2String(env, argv[PARAM1]);
LOG_INFO("mimeTypeFilter : %{public}s", context->mimeTypeFilter.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
*result = DataShareJSUtils::Convert2JSValue(env, context->resultStrArr);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->resultStrArr = context->proxy->datashareHelper_->GetFileTypes(uri, context->mimeTypeFilter);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_NormalizeUri(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_NormalizeUri in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_string_utf8(env, context->resultString.c_str(), NAPI_AUTO_LENGTH, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
Uri uriValue = context->proxy->datashareHelper_->NormalizeUri(uri);
context->resultString = uriValue.ToString();
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_DenormalizeUri(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_DenormalizeUri in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_create_string_utf8(env, context->resultString.c_str(), NAPI_AUTO_LENGTH, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
Uri uriValue = context->proxy->datashareHelper_->DenormalizeUri(uri);
context->resultString = uriValue.ToString();
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_NotifyChange(napi_env env, napi_callback_info info)
{
LOG_DEBUG("Napi_NotifyChange in");
auto context = std::make_shared<ContextInfo>();
auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status {
NAPI_ASSERT_BASE(env, argc == 1 || argc == 2, " should 1 or 2 parameters!", napi_invalid_arg);
LOG_DEBUG("argc : %{public}d", static_cast<int>(argc));
napi_valuetype valuetype = napi_undefined;
napi_typeof(env, argv[PARAM0], &valuetype);
if (valuetype == napi_string) {
context->uri = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
LOG_INFO("uri : %{public}s", context->uri.c_str());
} else {
LOG_INFO("wrong type, should be napi_string");
}
return napi_ok;
};
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_get_null(env, result);
return napi_ok;
};
auto exec = [context](AsyncCall::Context *ctx) {
if (context->proxy->datashareHelper_ != nullptr) {
if (!context->uri.empty()) {
OHOS::Uri uri(context->uri);
context->proxy->datashareHelper_->NotifyChange(uri);
context->status = napi_ok;
} else {
LOG_ERROR("context->uri is empty");
}
} else {
LOG_ERROR("dataShareHelper_ == nullptr");
}
};
context->SetAction(std::move(input), std::move(output));
AsyncCall asyncCall(env, info, std::dynamic_pointer_cast<AsyncCall::Context>(context));
return asyncCall.Call(env, exec);
}
napi_value NapiDataShareHelper::Napi_On(napi_env env, napi_callback_info info)
{
LOG_INFO("Napi_On in");
napi_value self = nullptr;
size_t argc = MAX_ARGC;
napi_value argv[MAX_ARGC] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
NAPI_ASSERT(env, argc == ARGS_THREE, "wrong count of args");
NapiDataShareHelper *proxy = nullptr;
NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast<void **>(&proxy)), nullptr);
NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr);
NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr);
napi_valuetype valueType;
NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valueType));
if (valueType != napi_string) {
LOG_ERROR("type is not string");
return nullptr;
}
std::string type = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
if (type != "dataChange") {
LOG_ERROR("wrong register type : %{public}s", type.c_str());
return nullptr;
}
NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valueType));
NAPI_ASSERT_BASE(env, valueType == napi_string, "uri is not string", nullptr);
std::string uri = DataShareJSUtils::Convert2String(env, argv[PARAM1]);
NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType));
NAPI_ASSERT_BASE(env, valueType == napi_function, "callback is not a function", nullptr);
sptr<NAPIDataShareObserver> observer(new (std::nothrow) NAPIDataShareObserver(env, argv[PARAM2]));
auto obs = proxy->observerMap_.find(uri);
if (obs != proxy->observerMap_.end()) {
proxy->datashareHelper_->UnregisterObserver(Uri(uri), obs->second);
obs->second->DeleteReference();
proxy->observerMap_.erase(uri);
}
proxy->datashareHelper_->RegisterObserver(Uri(uri), observer);
proxy->observerMap_.emplace(uri, observer);
return nullptr;
}
napi_value NapiDataShareHelper::Napi_Off(napi_env env, napi_callback_info info)
{
LOG_INFO("Napi_Off in");
napi_value self = nullptr;
size_t argc = MAX_ARGC;
napi_value argv[MAX_ARGC] = {nullptr};
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr));
NAPI_ASSERT(env, argc == ARGS_TWO || argc == ARGS_THREE, "wrong count of args");
NapiDataShareHelper *proxy = nullptr;
NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast<void **>(&proxy)), nullptr);
NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr);
NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr);
napi_valuetype valueType;
NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valueType));
if (valueType != napi_string) {
LOG_ERROR("type is not string");
return nullptr;
}
std::string type = DataShareJSUtils::Convert2String(env, argv[PARAM0]);
if (type != "dataChange") {
LOG_ERROR("wrong register type : %{public}s", type.c_str());
return nullptr;
}
NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valueType));
NAPI_ASSERT_BASE(env, valueType == napi_string, "uri is not string", nullptr);
std::string uri = DataShareJSUtils::Convert2String(env, argv[PARAM1]);
if (argc == ARGS_THREE) {
NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType));
NAPI_ASSERT_BASE(env, valueType == napi_function, "callback is not a function", nullptr);
}
auto obs = proxy->observerMap_.find(uri);
if (obs != proxy->observerMap_.end()) {
proxy->datashareHelper_->UnregisterObserver(Uri(uri), obs->second);
obs->second->DeleteReference();
proxy->observerMap_.erase(uri);
} else {
LOG_DEBUG("this uri hasn't been registered");
}
return nullptr;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,85 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "napi_datashare_observer.h"
#include "datashare_log.h"
namespace OHOS {
namespace DataShare {
NAPIDataShareObserver::NAPIDataShareObserver(napi_env env, napi_value callback)
: env_(env)
{
napi_create_reference(env, callback, 1, &ref_);
napi_get_uv_event_loop(env, &loop_);
}
NAPIDataShareObserver::~NAPIDataShareObserver() {}
void NAPIDataShareObserver::OnChange()
{
LOG_DEBUG("OnChange called");
if (ref_ == nullptr) {
LOG_ERROR("ref_ == nullptr");
return;
}
ObserverWorker *observerWorker = new (std::nothrow)ObserverWorker(this);
if (observerWorker == nullptr) {
LOG_ERROR("Failed to create observerWorker");
return;
}
uv_work_t *work = new (std::nothrow)uv_work_t();
if (work == nullptr) {
LOG_ERROR("Failed to create uv work");
return;
}
work->data = observerWorker;
int ret = uv_queue_work(loop_, work,
[](uv_work_t *work) {},
[](uv_work_t *work, int status) {
LOG_DEBUG("uv_queue_work start");
std::shared_ptr<ObserverWorker> innerWorker(reinterpret_cast<ObserverWorker *>(work->data));
if (innerWorker->observer_->ref_ == nullptr) {
LOG_ERROR("innerWorker->observer_->ref_ is nullptr");
return;
}
napi_value callback = nullptr;
napi_value args[2] = {0};
napi_value global = nullptr;
napi_value result;
napi_get_reference_value(innerWorker->observer_->env_,
innerWorker->observer_->ref_, &callback);
napi_get_global(innerWorker->observer_->env_, &global);
napi_status callStatus =
napi_call_function(innerWorker->observer_->env_, global, callback, 2, args, &result);
if (callStatus != napi_ok) {
LOG_ERROR("napi_call_function failed status : %{public}d", callStatus);
}
});
if (ret != 0) {
LOG_ERROR("uv_queue_work failed");
delete observerWorker;
delete work;
}
}
void NAPIDataShareObserver::DeleteReference()
{
if (ref_ != nullptr) {
napi_delete_reference(env_, ref_);
ref_ = nullptr;
}
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,61 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "datashare_log.h"
#include "napi_datashare_helper.h"
namespace OHOS {
namespace DataShare {
EXTERN_C_START
/*
* The module initialization.
*/
static napi_value Init(napi_env env, napi_value exports)
{
LOG_DEBUG("Init in");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("createDataShareHelper", NapiDataShareHelper::Napi_CreateDataShareHelper),
};
napi_status status = napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc);
LOG_DEBUG("Init napi_define_properties status : %{public}d", status);
return exports;
}
EXTERN_C_END
/*
* The module definition.
*/
static napi_module _module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "data.dataShare",
.nm_priv = ((void *)0),
.reserved = {0}
};
/*
* The module registration.
*/
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&_module);
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "datashare_log.h"
#include "datashare_predicates_proxy.h"
namespace OHOS {
namespace DataShare {
EXTERN_C_START
/*
* The module initialization.
*/
static napi_value Init(napi_env env, napi_value exports)
{
LOG_INFO("DataSharePredicatesProxy module Init in");
DataSharePredicatesProxy::Init(env, exports);
LOG_INFO("DataSharePredicatesProxy module Init out");
return exports;
}
EXTERN_C_END
/*
* The module definition.
*/
static napi_module _module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "data.dataSharePredicates",
.nm_priv = ((void *)0),
.reserved = {0}
};
/*
* The module registration.
*/
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&_module);
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,50 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_datashare_ext_ability_abc") {
src_js = rebase_path("datashare_ext_ability.js")
dst_file = rebase_path(target_out_dir + "/datashare_ext_ability.abc")
in_puts = [ "datashare_ext_ability.js" ]
out_puts = [ target_out_dir + "/datashare_ext_ability.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("datashare_ext_ability_js") {
input = "datashare_ext_ability.js"
output = target_out_dir + "/datashare_ext_ability.o"
}
gen_js_obj("datashare_ext_ability_abc") {
input = get_label_info(":gen_datashare_ext_ability_abc", "target_out_dir") +
"/datashare_ext_ability.abc"
output = target_out_dir + "/datashare_ext_ability_abc.o"
dep = ":gen_datashare_ext_ability_abc"
}
ohos_shared_library("datashareextensionability_napi") {
sources = [ "datashare_ext_ability_module.cpp" ]
deps = [
":datashare_ext_ability_abc",
":datashare_ext_ability_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module/application"
subsystem_name = "distributeddatamgr"
part_name = "data_share"
}

View File

@ -1,66 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class DataShareExtensionAbility {
onCreate(want, callback) {
console.log('onCreate, want:' + want.abilityName);
}
getFileTypes(uri, mimeTypeFilter, callback) {
console.log('getFileTypes, uri:' + uri);
}
openFile(uri, mode, callback) {
console.log('openFile, uri:' + uri);
}
openRawFile(uri, mode, callback) {
console.log('openRawFile, uri:' + uri);
}
insert(uri, value, callback) {
console.log('insert, uri:' + uri);
}
update(uri, predicates, value, callback) {
console.log('update, uri:' + uri);
}
delete(uri, predicates, callback) {
console.log('delete, uri:' + uri);
}
query(uri, predicates, columns, callback) {
console.log('query, uri:' + uri);
}
getType(uri, callback) {
console.log('getType, uri:' + uri);
}
batchInsert(uri, values, callback) {
console.log('batchInsert, uri:' + uri);
}
normalizeUri(uri, callback) {
console.log('normalizeUri, uri:' + uri);
}
denormalizeUri(uri, callback) {
console.log('denormalizeUri, uri:' + uri);
}
}
export default DataShareExtensionAbility

View File

@ -1,57 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "native_engine/native_engine.h"
extern const char _binary_datashare_ext_ability_js_start[];
extern const char _binary_datashare_ext_ability_js_end[];
extern const char _binary_datashare_ext_ability_abc_start[];
extern const char _binary_datashare_ext_ability_abc_end[];
extern "C" __attribute__((constructor))
void NAPI_application_DataShareExtensionAbility_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "application.DataShareExtensionAbility",
.fileName = "application/libdatashareextensionability_napi.so/DataShareExtensionAbility.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_DataShareExtensionAbility_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_datashare_ext_ability_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_datashare_ext_ability_js_end - _binary_datashare_ext_ability_js_start;
}
}
// datashare extension ability JS register
extern "C" __attribute__((visibility("default")))
void NAPI_application_DataShareExtensionAbility_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_datashare_ext_ability_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_datashare_ext_ability_abc_end - _binary_datashare_ext_ability_abc_start;
}
}

View File

@ -1,51 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
ts2abc_gen_abc("gen_datashare_ext_ability_context_abc") {
src_js = rebase_path("datashare_ext_ability_context.js")
dst_file = rebase_path(target_out_dir + "/datashare_ext_ability_context.abc")
in_puts = [ "datashare_ext_ability_context.js" ]
out_puts = [ target_out_dir + "/datashare_ext_ability_context.abc" ]
extra_args = [ "--module" ]
}
gen_js_obj("datashare_ext_ability_context_js") {
input = "datashare_ext_ability_context.js"
output = target_out_dir + "/datashare_ext_ability_context.o"
}
gen_js_obj("datashare_ext_ability_context_abc") {
input =
get_label_info(":gen_datashare_ext_ability_context_abc",
"target_out_dir") + "/datashare_ext_ability_context.abc"
output = target_out_dir + "/datashare_ext_ability_context_abc.o"
dep = ":gen_datashare_ext_ability_context_abc"
}
ohos_shared_library("datashareextensionabilitycontext_napi") {
sources = [ "datashare_ext_ability_context_module.cpp" ]
deps = [
":datashare_ext_ability_context_abc",
":datashare_ext_ability_context_js",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module/application"
subsystem_name = "distributeddatamgr"
part_name = "data_share"
}

View File

@ -1,24 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ExtensionContext = requireNapi("application.ExtensionContext")
class DataShareExtensionAbilityContext extends ExtensionContext {
constructor(obj) {
super(obj);
}
}
export default DataShareExtensionAbilityContext

View File

@ -1,57 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "native_engine/native_engine.h"
extern const char _binary_datashare_ext_ability_context_js_start[];
extern const char _binary_datashare_ext_ability_context_js_end[];
extern const char _binary_datashare_ext_ability_context_abc_start[];
extern const char _binary_datashare_ext_ability_context_abc_end[];
extern "C" __attribute__((constructor))
void NAPI_application_DataShareExtensionAbilityContext_AutoRegister()
{
auto moduleManager = NativeModuleManager::GetInstance();
NativeModule newModuleInfo = {
.name = "application.DataShareExtensionAbilityContext",
.fileName = "application/libdatashareextensionabilitycontext_napi.so/DataShareExtensionAbilityContext.js",
};
moduleManager->Register(&newModuleInfo);
}
extern "C" __attribute__((visibility("default")))
void NAPI_application_DataShareExtensionAbilityContext_GetJSCode(const char **buf, int *bufLen)
{
if (buf != nullptr) {
*buf = _binary_datashare_ext_ability_context_js_start;
}
if (bufLen != nullptr) {
*bufLen = _binary_datashare_ext_ability_context_js_end - _binary_datashare_ext_ability_context_js_start;
}
}
// datashare extension ability context JS register
extern "C" __attribute__((visibility("default")))
void NAPI_application_DataShareExtensionAbilityContext_GetABCCode(const char **buf, int *buflen)
{
if (buf != nullptr) {
*buf = _binary_datashare_ext_ability_context_abc_start;
}
if (buflen != nullptr) {
*buflen = _binary_datashare_ext_ability_context_abc_end - _binary_datashare_ext_ability_context_abc_start;
}
}

View File

@ -1,65 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_ABS_RESULT_SET_H
#define DATASHARE_ABS_RESULT_SET_H
#include <string>
#include "result_set.h"
namespace OHOS {
namespace DataShare {
class DataShareAbsResultSet : public ResultSet {
public:
DataShareAbsResultSet();
virtual ~DataShareAbsResultSet();
virtual int GetRowCount(int &count) override;
virtual int GetAllColumnNames(std::vector<std::string> &columnNames) override;
virtual int GetBlob(int columnIndex, std::vector<uint8_t> &blob) override;
virtual int GetString(int columnIndex, std::string &value) override;
virtual int GetInt(int columnIndex, int &value) override;
virtual int GetLong(int columnIndex, int64_t &value) override;
virtual int GetDouble(int columnIndex, double &value) override;
virtual int IsColumnNull(int columnIndex, bool &isNull) override;
virtual int GoToRow(int position) override;
virtual int GetDataType(int columnIndex, DataType &dataType) override;
int GetRowIndex(int &position) const override;
int GoTo(int offset) override;
int GoToFirstRow() override;
int GoToLastRow() override;
int GoToNextRow() override;
int GoToPreviousRow() override;
int IsAtFirstRow(bool &result) const override;
int IsAtLastRow(bool &result) override;
int IsStarted(bool &result) const override;
int IsEnded(bool &result) override;
int GetColumnCount(int &count) override;
int GetColumnIndex(const std::string &columnName, int &columnIndex) override;
int GetColumnName(int columnIndex, std::string &columnName) override;
bool IsClosed() const override;
int Close() override;
protected:
// The default position of the result set
static const int INIT_POS = -1;
// Current row position
int rowPos_;
// Indicates whether the result set is closed
bool isClosed_;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,155 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_BLOCK_WRITER_IMPL_H
#define DATASHARE_BLOCK_WRITER_IMPL_H
#include "shared_block.h"
#include "result_set_bridge.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DataShare {
/**
* This class stores a set of rows from a database in a buffer
* which is used as the set of query result.
*/
class DataShareBlockWriterImpl : public virtual ResultSetBridge::Writer {
public:
/**
* SharedBlock constructor.
*/
DataShareBlockWriterImpl();
/**
* SharedBlock constructor.
*/
DataShareBlockWriterImpl(const std::string &name, size_t size);
/**
* SharedBlock Deconstruction.
*/
virtual ~DataShareBlockWriterImpl();
/**
* Clear current shared block.
*/
int Clear();
/**
* Set a shared block column.
*/
int SetColumnNum(uint32_t numColumns);
/**
* Allocate a row unit and its directory.
*/
int AllocRow() override;
/**
* Release the value of the last row.
*/
int FreeLastRow();
/**
* Write Null data to the shared block.
*/
virtual int Write(uint32_t column) override;
/**
* Write long data to the shared block.
*/
virtual int Write(uint32_t column, int64_t value) override;
/**
* Write Double data to the shared block.
*/
virtual int Write(uint32_t column, double value) override;
/**
* Write blob data to the shared block.
*/
virtual int Write(uint32_t column, const uint8_t *value, size_t Size) override;
/**
* Write string data to the shared block.
*/
virtual int Write(uint32_t column, const char *value, size_t sizeIncludingNull) override;
/**
* The mHeader of the current result set.
*/
const void *GetHeader();
/**
* Size of the used byte in the block.
*/
size_t GetUsedBytes();
/**
* The name of the current result set.
*/
std::string Name();
/**
* The size of the current result set.
*/
size_t Size();
/**
* The row number of the current result set.
*/
uint32_t GetRowNum();
/**
* The column number of the current result set.
*/
uint32_t GetColumnNum();
/**
* Write raw data in block.
*/
size_t SetRawData(const void *rawData, size_t size);
/**
* The fd of shared memory
*/
int GetFd();
/**
* Get Block
*/
AppDataFwk::SharedBlock *GetBlock() const;
private:
/**
* The fd of shared memory
*/
bool GetCurrentRowIndex(uint32_t &rowIndex);
/**
* Convert ShareBlock error code to DataShare format
*/
int ConvertErrorCode(int shareBlockErr)
{
return shareBlockErr == AppDataFwk::SharedBlock::SHARED_BLOCK_OK ? E_OK : E_ERROR;
}
private:
AppDataFwk::SharedBlock *shareBlock_;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,46 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_LOG_PRINT_H
#define DATASHARE_LOG_PRINT_H
#ifndef LOG_TAG
#define LOG_TAG
#endif
#include "hilog/log.h"
namespace OHOS::DataShare {
static const OHOS::HiviewDFX::HiLogLabel DATASHARE_LABEL = { LOG_CORE, 0xD001651, "DataShare" };
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)
#define LOG_DEBUG(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Debug(DATASHARE_LABEL, \
"[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define LOG_INFO(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Info(DATASHARE_LABEL, \
"[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define LOG_WARN(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Warn(DATASHARE_LABEL, \
"[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define LOG_ERROR(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Error(DATASHARE_LABEL, \
"[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define LOG_FATAL(fmt, ...) \
(void)OHOS::HiviewDFX::HiLog::Fatal(DATASHARE_LABEL, \
"[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__)
} // namespace OHOS::DataShare
#endif

View File

@ -1,166 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_OPERATION_H
#define DATASHARE_OPERATION_H
#include <map>
#include <memory>
#include "datashare_operation_builder.h"
#include "datashare_predicates.h"
#include "datashare_values_bucket.h"
#include "uri.h"
#include "parcel.h"
using Uri = OHOS::Uri;
namespace OHOS {
namespace DataShare {
class DataShareOperationBuilder;
class DataShareOperation final : public Parcelable, public std::enable_shared_from_this<DataShareOperation> {
public:
~DataShareOperation();
DataShareOperation(
const std::shared_ptr<DataShareOperation> &dataShareOperation, const std::shared_ptr<Uri> &withUri);
explicit DataShareOperation(Parcel &in);
explicit DataShareOperation(const std::shared_ptr<DataShareOperationBuilder> &builder);
DataShareOperation();
/**
* @brief Creates an operation for inserting data.
* @param uri Indicates the path of data to operate.
* @return Returns an insert DataShareOperationBuilder object.
*/
static std::shared_ptr<DataShareOperationBuilder> NewInsertBuilder(const std::shared_ptr<Uri> &uri);
/**
* @brief Creates an operation for updating data.
* @param uri Indicates the path of data to operate.
* @return Returns an update DataShareOperationBuilder object.
*/
static std::shared_ptr<DataShareOperationBuilder> NewUpdateBuilder(const std::shared_ptr<Uri> &uri);
/**
* @brief Creates an operation for deleting data.
* @param uri Indicates the path of data to operate.
* @return Returns an delete DataShareOperationBuilder object.
*/
static std::shared_ptr<DataShareOperationBuilder> NewDeleteBuilder(const std::shared_ptr<Uri> &uri);
/**
* @brief Creates an operation for asserting data.
* @param uri Indicates the path of data to operate.
* @return Returns an assert DataShareOperationBuilder object.
*/
static std::shared_ptr<DataShareOperationBuilder> NewAssertBuilder(const std::shared_ptr<Uri> &uri);
/**
* @brief Obtains the value of the type attribute included in this DataShareOperation.
* @return Returns the type included in this DataShareOperation.
*/
int GetType() const;
/**
* @brief Obtains the value of the uri attribute included in this DataShareOperation.
* @return Returns the uri included in this DataShareOperation.
*/
std::shared_ptr<Uri> GetUri() const;
/**
* @brief Obtains the value of the databaseValuesBucket attribute included in this DataShareOperation.
* @return Returns the databaseValuesBucket included in this DataShareOperation.
*/
std::shared_ptr<DataShareValuesBucket> GetValuesBucket() const;
/**
* @brief Obtains the value of the expectedCount attribute included in this DataShareOperation.
* @return Returns the expectedCount included in this DataShareOperation.
*/
int GetExpectedCount() const;
/**
* @brief Obtains the value of the dataBasePredicates attribute included in this DataShareOperation.
* @return Returns the dataBasePredicates included in this DataShareOperation.
*/
std::shared_ptr<DataSharePredicates> GetDataSharePredicates() const;
/**
* @brief Obtains the value of the valuesBucketReferences attribute included in this DataShareOperation.
* @return Returns the valuesBucketReferences included in this DataShareOperation.
*/
std::shared_ptr<DataShareValuesBucket> GetValuesBucketReferences() const;
/**
* @brief Obtains the value of the dataSharePredicatesBackReferences attribute included in this
* DataShareOperation.
* @return Returns the dataSharePredicatesBackReferences included in this DataShareOperation.
*/
std::map<int, int> GetDataSharePredicatesBackReferences() const;
/**
* @brief Checks whether an insert operation is created.
* @return Returns true if it is an insert operation; returns false otherwise.
*/
bool IsInsertOperation() const;
/**
* @brief Checks whether an delete operation is created.
* @return Returns true if it is an delete operation; returns false otherwise.
*/
bool IsDeleteOperation() const;
/**
* @brief Checks whether an update operation is created.
* @return Returns true if it is an update operation; returns false otherwise.
*/
bool IsUpdateOperation() const;
/**
* @brief Checks whether an assert operation is created.
* @return Returns true if it is an assert operation; returns false otherwise.
*/
bool IsAssertOperation() const;
/**
* @brief Checks whether an operation can be interrupted.
* @return Returns true if the operation can be interrupted; returns false otherwise.
*/
bool IsInterruptionAllowed() const;
bool operator==(const DataShareOperation &other) const;
DataShareOperation &operator=(const DataShareOperation &other);
bool Marshalling(Parcel &out) const;
static DataShareOperation *Unmarshalling(Parcel &in);
/**
* @brief Creates a DataShareOperation instance based on the given Parcel object
* @param in Indicates the Parcel object.
* @return Returns the DataShareOperation object.
*/
static std::shared_ptr<DataShareOperation> CreateFromParcel(Parcel &in);
public:
static constexpr int TYPE_INSERT = 1;
static constexpr int TYPE_UPDATE = 2;
static constexpr int TYPE_DELETE = 3;
static constexpr int TYPE_ASSERT = 4;
private:
void PutMap(Parcel &in);
bool ReadFromParcel(Parcel &in);
private:
// no object in parcel
static constexpr int VALUE_NULL = 0;
// object exist in parcel
static constexpr int VALUE_OBJECT = 1;
static constexpr int REFERENCE_THRESHOLD = 3 * 1024 * 1024;
int type_ = -1;
int expectedCount_ = 0;
bool interrupted_ = false;
std::shared_ptr<Uri> uri_ = nullptr;
std::shared_ptr<DataShareValuesBucket> valuesBucket_ = nullptr;
std::shared_ptr<DataSharePredicates> dataSharePredicates_ = nullptr;
std::shared_ptr<DataShareValuesBucket> valuesBucketReferences_ = nullptr;
std::map<int, int> dataSharePredicatesBackReferences_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_OPERATION_H

View File

@ -1,99 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_OPERATION_BUILDER_H
#define DATASHARE_OPERATION_BUILDER_H
#include <map>
#include <memory>
#include "datashare_operation.h"
#include "datashare_predicates.h"
#include "datashare_values_bucket.h"
#include "uri.h"
#include "parcel.h"
using Uri = OHOS::Uri;
namespace OHOS {
namespace DataShare {
class DataShareOperation;
class DataShareOperationBuilder final : public std::enable_shared_from_this<DataShareOperationBuilder> {
friend class DataShareOperation;
public:
DataShareOperationBuilder(const int type, const std::shared_ptr<Uri> &uri);
~DataShareOperationBuilder();
/**
* @brief Creates a DataShareOperation object.
* @return Returns the DataShareOperation object.
*/
std::shared_ptr<DataShareOperation> Build();
/**
* @brief Sets the data records to be inserted or updated.
* @param values Indicates the data values to be set.
* @return Returns a DataShareOperationBuilder object containing the given values parameter.
*/
std::shared_ptr<DataShareOperationBuilder> WithValuesBucket(std::shared_ptr<DataShareValuesBucket> &values);
/**
* @brief Sets filter criteria used for deleting updating or assert query data.
* @param predicates Indicates the filter criteria to set. If this parameter is null, all data records will be
* operated by default.
* @return Returns an object containing the given filter criteria.
*/
std::shared_ptr<DataShareOperationBuilder> WithPredicates(std::shared_ptr<DataSharePredicates> &predicates);
/**
* @brief Sets the expected number of rows to update ,delete or assert query.
* @param count Indicates the expected number of rows to update or delete.
* @return Returns a DataShareOperationBuilder object containing the given count parameter.
*/
std::shared_ptr<DataShareOperationBuilder> WithExpectedCount(int count);
/**
* @brief Adds a back reference to be used as a filter criterion in withPredicates(DataSharePredicates).
* @param requestArgIndex Indicates the index referencing the predicate parameter whose value is to be replaced.
* @param previousResult Indicates the index referencing the historical DataShareResult used to replace the value
* of the specified predicate parameter.
* @return Returns a DataShareOperationBuilder object containing the given requestArgIndex and previousResult
* parameters.
*/
std::shared_ptr<DataShareOperationBuilder> WithPredicatesBackReference(int requestArgIndex, int previousResult);
/**
* @brief Adds a back reference to be used in withValuesBucket(DataShareValuesBucket).
* @param backReferences Indicates the DataShareValuesBucket object containing a set of key-value pairs.
* In each pair, the key specifies the value to be updated and the value specifies.
* In each pair, the replace the specified value. This parameter cannot be null.
* @return Returns a DataShareOperationBuilder object containing the given backReferences parameter.
*/
std::shared_ptr<DataShareOperationBuilder> WithValueBackReferences(
std::shared_ptr<DataShareValuesBucket> &backReferences);
/**
* @brief Sets an interrupt flag bit for a batch operation, which can be insert, update, delete, or assert.
* @param interrupted Specifies whether a batch operation can be interrupted. The value true indicates that the
* operation can be interrupted, and false indicates the opposite.
* @return Returns a DataShareOperationBuilder object containing the given interrupted parameter.
*/
std::shared_ptr<DataShareOperationBuilder> WithInterruptionAllowed(bool interrupted);
private:
int type_;
int expectedCount_;
bool interrupted_;
std::shared_ptr<Uri> uri_;
std::shared_ptr<DataShareValuesBucket> valuesBucket_;
std::shared_ptr<DataSharePredicates> dataSharePredicates_;
std::shared_ptr<DataShareValuesBucket> valuesBucketReferences_;
std::map<int, int> dataSharePredicatesBackReferences_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_OPERATION_BUILDER_H

View File

@ -1,106 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_RESULT_H
#define DATASHARE_RESULT_H
#include "parcel.h"
#include "uri.h"
using Uri = OHOS::Uri;
namespace OHOS {
namespace DataShare {
class DataShareResult final : public Parcelable {
public:
/**
* @brief A constructor used to create a DataShareResult instance
* with the input parameter count specified.
*/
explicit DataShareResult(int count);
/**
* @brief A constructor used to create a DataShareResult instance
* with the input parameter uri specified
*/
explicit DataShareResult(const Uri &uri);
/**
* @brief A constructor used to create a DataShareResult instance
* with a Parcel object specified.
*/
explicit DataShareResult(Parcel &parcel);
/**
* @brief A constructor used to create a DataShareResult instance
* with input parameters uri, count, and failure specified.
*/
DataShareResult(const Uri &uri, int count);
~DataShareResult();
/**
* @brief Obtains the Uri object corresponding to the operation.
* @return Obtains the Uri object corresponding to the operation.
*/
Uri GetUri();
/**
* @brief Obtains the number of rows affected by the operation.
* @return Returns the number of rows affected by the operation.
*/
int GetCount();
/**
* @brief Prints out a string containing the class object information.
* @return Returns object information.
*/
std::string ToString();
/**
* @brief Marshals a DataShareResult object into a Parcel.
* @param parcel Indicates the Parcel object for marshalling.
* @return Returns true if the marshalling is successful; returns false otherwise.
*/
virtual bool Marshalling(Parcel &parcel) const;
/**
* @brief Unmarshals a DataShareResult object from a Parcel.
* @param parcel Indicates the Parcel object for unmarshalling.
* @return Returns true if the unmarshalling is successful; returns false otherwise.
*/
static DataShareResult *Unmarshalling(Parcel &parcel);
/**
* @brief Creates a DataShareResult instance based on the given Parcel object.
* Used to transfer DataShareResult object using Parcel.
* @param parcel Indicates the Parcel object.
* @return Returns the DataShareResult object.
*/
static DataShareResult *CreateFromParcel(Parcel &parcel);
private:
Uri uri_;
int count_;
bool ReadFromParcel(Parcel &parcel);
// no object in parcel
static constexpr int VALUE_NULL = -1;
// object exist in parcel
static constexpr int VALUE_OBJECT = 1;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_RESULT_H

View File

@ -1,44 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_SHARED_RESULT_SET_H
#define DATASHARE_SHARED_RESULT_SET_H
#include <string>
#include "shared_block.h"
namespace OHOS {
namespace DataShare {
class DataShareSharedResultSet {
public:
DataShareSharedResultSet() {}
~DataShareSharedResultSet() {}
/**
* Obtains a block from the {@link SharedResultSet}
*/
virtual AppDataFwk::SharedBlock *GetBlock() const = 0;
/**
* Adds the data of a {@code SharedResultSet} to a {@link SharedBlock}
*/
virtual void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) = 0;
/**
* Called when the position of the result set changes
*/
virtual bool OnGo(int oldRowIndex, int newRowIndex) = 0;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,42 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_STRINGUTILS_H
#define DATASHARE_STRINGUTILS_H
#include <string>
#include <vector>
namespace OHOS {
namespace DataShare {
class DataShareStringUtils {
public:
static std::string SurroundWithQuote(std::string value, std::string quote);
static std::string SurroundWithFunction(std::string function, std::string separator,
std::vector<std::string> array);
static bool IsEmpty(std::string source)
{
return (source.empty());
}
private:
DataShareStringUtils();
~DataShareStringUtils();
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,221 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef I_DATASHARE_H
#define I_DATASHARE_H
#include <string_ex.h>
#include <iremote_broker.h>
#include "uri.h"
#include "datashare_values_bucket.h"
#include "datashare_result.h"
#include "datashare_predicates.h"
#include "datashare_result_set.h"
#include "datashare_operation.h"
namespace OHOS {
namespace AAFwk {
class IDataAbilityObserver;
}
namespace DataShare {
class IDataShare : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DataShare.IDataShare");
enum {
CMD_GET_FILE_TYPES = 1,
CMD_OPEN_FILE = 2,
CMD_OPEN_RAW_FILE = 3,
CMD_INSERT = 4,
CMD_UPDATE = 5,
CMD_DELETE = 6,
CMD_QUERY = 7,
CMD_GET_TYPE = 8,
CMD_BATCH_INSERT = 9,
CMD_REGISTER_OBSERVER = 10,
CMD_UNREGISTER_OBSERVER = 11,
CMD_NOTIFY_CHANGE = 12,
CMD_NORMALIZE_URI = 13,
CMD_DENORMALIZE_URI = 14,
CMD_EXECUTE_BATCH = 15,
};
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
virtual std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0;
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
virtual int OpenFile(const Uri &uri, const std::string &mode) = 0;
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
virtual int OpenRawFile(const Uri &uri, const std::string &mode) = 0;
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) = 0;
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param value Indicates the data to update. This parameter can be null.
*
* @return Returns the number of data records updated.
*/
virtual int Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value) = 0;
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) = 0;
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
*
* @return Returns the query result.
*/
virtual std::shared_ptr<DataShareResultSet> Query(
const Uri &uri, const DataSharePredicates &predicates, std::vector<std::string> &columns) = 0;
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
virtual std::string GetType(const Uri &uri) = 0;
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
virtual int BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values) = 0;
/**
* @brief Registers an observer to DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
virtual bool RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) = 0;
/**
* @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
virtual bool UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) = 0;
/**
* @brief Notifies the registered observers of a change to the data resource specified by Uri.
*
* @param uri, Indicates the path of the data to operate.
*
* @return Return true if success. otherwise return false.
*/
virtual bool NotifyChange(const Uri &uri) = 0;
/**
* @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
* across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if
* the context has changed. If you implement URI normalization for a Data ability, you must also implement
* denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
* any method that is called on the Data ability must require normalization verification and denormalization. The
* default implementation of this method returns null, indicating that this Data ability does not support URI
* normalization.
*
* @param uri Indicates the Uri object to normalize.
*
* @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
*/
virtual Uri NormalizeUri(const Uri &uri) = 0;
/**
* @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
* The default implementation of this method returns the original URI passed to it.
*
* @param uri uri Indicates the Uri object to denormalize.
*
* @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri
* passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot
* be found in the current environment.
*/
virtual Uri DenormalizeUri(const Uri &uri) = 0;
/**
* @brief Performs batch operations on the database.
*
* @param operations Indicates a list of database operations on the database.
* @return Returns the result of each operation, in array.
*/
virtual std::vector<std::shared_ptr<DataShareResult>> ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations) = 0;
};
} // namespace DataShare
} // namespace OHOS
#endif // I_DATASHARE_H

View File

@ -1,67 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_I_SHARED_RESULT_SET_H
#define DATASHARE_I_SHARED_RESULT_SET_H
#include <memory>
#include "iremote_broker.h"
#include "datashare_result_set.h"
namespace OHOS::DataShare {
class ISharedResultSet : public DataShareResultSet, public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DataShare.ISharedResultSet")
static std::shared_ptr<DataShareResultSet> ReadFromParcel(MessageParcel &parcel);
static sptr<ISharedResultSet> WriteToParcel(std::shared_ptr<DataShareResultSet> 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<std::shared_ptr<DataShareResultSet>(MessageParcel &parcel)> consumerCreator_;
static std::function<sptr<ISharedResultSet>(std::shared_ptr<DataShareResultSet>,
MessageParcel &)> providerCreator_;
};
} // namespace OHOS::DataShare
#endif // DATASHARE_I_SHARED_RESULT_SET_H

View File

@ -1,38 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_I_SHARED_RESULT_SET_PROXY_H
#define DATASHARE_I_SHARED_RESULT_SET_PROXY_H
#include "ishared_result_set.h"
#include "iremote_proxy.h"
#include "datashare_errno.h"
namespace OHOS::DataShare {
class ISharedResultSetProxy : public IRemoteProxy<ISharedResultSet> {
public:
static std::shared_ptr<DataShareResultSet> CreateProxy(MessageParcel &parcel);
explicit ISharedResultSetProxy(const sptr<IRemoteObject> &impl);
virtual ~ISharedResultSetProxy() = default;
int GetAllColumnNames(std::vector<std::string> &columnNames) override;
int GetRowCount(int &count) override;
bool OnGo(int oldRowIndex, int newRowIndex) override;
int Close() override;
private:
static BrokerDelegator<ISharedResultSetProxy> delegator_;
std::vector<std::string> columnNames_;
int32_t rowCount_ = -1;
};
} // namespace OHOS::DataShare
#endif // DATASHARE_I_SHARED_RESULT_SET_PROXY_H

View File

@ -1,68 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_I_SHARED_RESULT_SET_STUB_H
#define DATASHARE_I_SHARED_RESULT_SET_STUB_H
#include <functional>
#include <future>
#include "safe_block_queue.h"
#include "ishared_result_set.h"
#include "iremote_stub.h"
namespace OHOS::DataShare {
class ISharedResultSetStub : public IRemoteStub<ISharedResultSet> {
public:
explicit ISharedResultSetStub(std::shared_ptr<DataShareResultSet> resultSet);
~ISharedResultSetStub();
static sptr<ISharedResultSet> CreateStub(std::shared_ptr<DataShareResultSet> resultSet,
MessageParcel &parcel);
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
protected:
int HandleGetRowCountRequest(MessageParcel &data, MessageParcel &reply);
int HandleGetAllColumnNamesRequest(MessageParcel &data, MessageParcel &reply);
int HandleOnGoRequest(MessageParcel &data, MessageParcel &reply);
int HandleCloseRequest(MessageParcel &data, MessageParcel &reply);
template<typename F, typename... Args>
auto Submit(F&& func, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>
{
auto exec = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
auto task = std::make_shared<std::packaged_task<typename std::result_of<F(Args...)>::type()>>(std::move(exec));
auto future = task->get_future();
runnables_.Push([task, this] {
bool isRunning = isRunning_;
(*task)();
return isRunning;
});
return future;
}
private:
void Run();
using Handler = int(ISharedResultSetStub::*)(MessageParcel &request, MessageParcel &reply);
static constexpr int MAX_RUNNABLE = 1024;
std::shared_ptr<DataShareResultSet> resultSet_;
SafeBlockQueue<std::function<bool()>> runnables_;
bool isRunning_ = true;
std::thread thread_;
static constexpr Handler handlers[FUNC_BUTT] {
&ISharedResultSetStub::HandleGetRowCountRequest,
&ISharedResultSetStub::HandleGetAllColumnNamesRequest,
&ISharedResultSetStub::HandleOnGoRequest,
&ISharedResultSetStub::HandleCloseRequest,
};
};
} // namespace OHOS::DataShare
#endif // DATASHARE_I_SHARED_RESULT_SET_STUB_H

View File

@ -1,229 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVE_DATASHARE_COMMON_INCLUDE_RESULT_SET_H
#define NATIVE_DATASHARE_COMMON_INCLUDE_RESULT_SET_H
#include <string>
namespace OHOS {
namespace DataShare {
/* Value returned by getDataType(int) */
enum class DataType {
TYPE_NULL = 0,
TYPE_INTEGER,
TYPE_FLOAT,
TYPE_STRING,
TYPE_BLOB,
};
class ResultSet {
public:
virtual ~ResultSet() {}
/**
* Returns a string array holding the names of all of the columns in the
* result set.
*
* return the names of the columns contains in this query result.
*/
virtual int GetAllColumnNames(std::vector<std::string> &columnNames) = 0;
/**
* Return the total number of columns
*
* return the number of columns
*/
virtual int GetColumnCount(int &count) = 0;
/**
* Returns data type of the given column's value.
*
* param columnIndex the zero-based index of the target column.
* return column value type.
*/
virtual int GetDataType(int columnIndex, DataType &dataType) = 0;
/**
* Returns the zero-based index for the given column name.
*
* param columnName the name of the column.
* return the column index for the given column, or -1 if
* the column does not exist.
*/
virtual int GetColumnIndex(const std::string &columnName, int &columnIndex) = 0;
/**
* Returns the column name at the given column index.
*
* param columnIndex the zero-based index.
* return the column name for the given index.
*/
virtual int GetColumnName(int columnIndex, std::string &columnName) = 0;
/**
* return the numbers of rows in the result set.
*/
virtual int GetRowCount(int &count) = 0;
/**
* Returns the current position of the cursor in the result set.
* The value is zero-based. When the result set is first returned the cursor
* will be at position -1, which is before the first row.
* After the last row is returned another call to next() will leave the cursor past
* the last entry, at a position of count().
*
* return the current cursor position.
*/
virtual int GetRowIndex(int &position) const = 0;
/**
* Move the cursor a relative amount from current position. Positive offset move forward,
* negative offset move backward.
*
* param offset the offset to be applied from the current position.
* return whether the requested move succeeded.
*/
virtual int GoTo(int offset) = 0;
/**
* Move the cursor to an absolute position.
*
* param position the zero-based position to move to.
* return whether the requested move succeeded.
*/
virtual int GoToRow(int position) = 0;
/**
* Move the cursor to the first row.
*
* return whether the requested move succeeded.
*/
virtual int GoToFirstRow() = 0;
/**
* Move the cursor to the last row.
*
* return whether the requested move succeeded.
*/
virtual int GoToLastRow() = 0;
/**
* Move the cursor to the next row.
*
* return whether the requested move succeeded.
*/
virtual int GoToNextRow() = 0;
/**
* Move the cursor to the previous row.
*
* return whether the requested move succeeded.
*/
virtual int GoToPreviousRow() = 0;
/**
* Returns whether the cursor is pointing to the position after the last
* row.
*
* return whether the cursor is before the first row.
*/
virtual int IsEnded(bool &result) = 0;
/**
* Returns whether the cursor is pointing to the position before the first
* row.
*
* return whether the cursor is before the first row.
*/
virtual int IsStarted(bool &result) const = 0;
/**
* Returns whether the cursor is pointing to the first row.
*
* return whether the cursor is pointing at the first entry.
*/
virtual int IsAtFirstRow(bool &result) const = 0;
/**
* Returns whether the cursor is pointing to the last row.
*
* return whether the cursor is pointing at the last entry.
*/
virtual int IsAtLastRow(bool &result) = 0;
/**
* Returns the value of the requested column as a byte array.
*
* param columnIndex the zero-based index of the target column.
* return the value of the requested column as a byte array.
*/
virtual int GetBlob(int columnIndex, std::vector<uint8_t> &blob) = 0;
/**
* Returns the value of the requested column as a String.
*
* param columnIndex the zero-based index of the target column.
* return the value of the requested column as a String.
*/
virtual int GetString(int columnIndex, std::string &value) = 0;
/**
* Returns the value of the requested column as a int.
*
* param columnIndex the zero-based index of the target column.
* return the value of the requested column as a int.
*/
virtual int GetInt(int columnIndex, int &value) = 0;
/**
* Returns the value of the requested column as a long.
*
* param columnIndex the zero-based index of the target column.
* return the value of the requested column as a long.
*/
virtual int GetLong(int columnIndex, int64_t &value) = 0;
/**
* Returns the value of the requested column as a double.
*
* param columnIndex the zero-based index of the target column.
* return the value of the requested column as a double.
*/
virtual int GetDouble(int columnIndex, double &value) = 0;
/**
* Whether the value of the requested column is null.
*
* param columnIndex the zero-based index of the target column.
* return whether the column value is null.
*/
virtual int IsColumnNull(int columnIndex, bool &isNull) = 0;
/**
* Return true if the result set is closed.
*
* return true if the result set is closed.
*/
virtual bool IsClosed() const = 0;
/**
* Closes the result set, releasing all of its resources and making it
* completely invalid.
*/
virtual int Close() = 0;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,240 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_abs_result_set.h"
#include <vector>
#include "datashare_log.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DataShare {
DataShareAbsResultSet::DataShareAbsResultSet() : rowPos_(INIT_POS), isClosed_(false)
{}
DataShareAbsResultSet::~DataShareAbsResultSet() {}
int DataShareAbsResultSet::GetRowCount(int &count)
{
return E_OK;
}
int DataShareAbsResultSet::GetAllColumnNames(std::vector<std::string> &columnNames)
{
return E_OK;
}
int DataShareAbsResultSet::GetBlob(int columnIndex, std::vector<uint8_t> &blob)
{
return E_OK;
}
int DataShareAbsResultSet::GetString(int columnIndex, std::string &value)
{
return E_OK;
}
int DataShareAbsResultSet::GetInt(int columnIndex, int &value)
{
return E_OK;
}
int DataShareAbsResultSet::GetLong(int columnIndex, int64_t &value)
{
return E_OK;
}
int DataShareAbsResultSet::GetDouble(int columnIndex, double &value)
{
return E_OK;
}
int DataShareAbsResultSet::IsColumnNull(int columnIndex, bool &isNull)
{
return E_OK;
}
int DataShareAbsResultSet::GoToRow(int position)
{
return E_OK;
}
int DataShareAbsResultSet::GetDataType(int columnIndex, DataType &dataType)
{
return E_OK;
}
int DataShareAbsResultSet::GetRowIndex(int &position) const
{
position = rowPos_;
return E_OK;
}
int DataShareAbsResultSet::GoTo(int offset)
{
int ret = GoToRow(rowPos_ + offset);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GoTo return ret is wrong!");
}
return ret;
}
int DataShareAbsResultSet::GoToFirstRow()
{
int ret = GoToRow(0);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GoToFirstRow return ret is wrong!");
}
return ret;
}
int DataShareAbsResultSet::GoToLastRow()
{
int rowCnt = 0;
int ret = GetRowCount(rowCnt);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GoToLastRow return GetRowCount::ret is wrong!");
return ret;
}
ret = GoToRow(rowCnt - 1);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GoToLastRow return GoToRow::ret is wrong!");
}
return ret;
}
int DataShareAbsResultSet::GoToNextRow()
{
int ret = GoToRow(rowPos_ + 1);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GoToNextRow return GoToRow::ret is wrong!");
}
return ret;
}
int DataShareAbsResultSet::GoToPreviousRow()
{
int ret = GoToRow(rowPos_ - 1);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GoToPreviousRow return GoToRow::ret is wrong!");
}
return ret;
}
int DataShareAbsResultSet::IsAtFirstRow(bool &result) const
{
result = (rowPos_ == 0);
return E_OK;
}
int DataShareAbsResultSet::IsAtLastRow(bool &result)
{
int rowCnt = 0;
int ret = GetRowCount(rowCnt);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::IsAtLastRow return GetRowCount::ret is wrong!");
return ret;
}
result = (rowPos_ == (rowCnt - 1));
return E_OK;
}
int DataShareAbsResultSet::IsStarted(bool &result) const
{
result = (rowPos_ != INIT_POS);
return E_OK;
}
int DataShareAbsResultSet::IsEnded(bool &result)
{
int rowCnt = 0;
int ret = GetRowCount(rowCnt);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::IsEnded return GetRowCount::ret is wrong!");
return ret;
}
result = (rowCnt == 0) ? true : (rowPos_ == rowCnt);
return E_OK;
}
int DataShareAbsResultSet::GetColumnCount(int &count)
{
std::vector<std::string> columnNames;
int ret = GetAllColumnNames(columnNames);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GetColumnCount return GetAllColumnNames::ret is wrong!");
return ret;
}
count = static_cast<int>(columnNames.size());
return E_OK;
}
int DataShareAbsResultSet::GetColumnIndex(const std::string &columnName, int &columnIndex)
{
auto periodIndex = columnName.rfind('.');
std::string columnNameLower = columnName;
if (periodIndex != std::string::npos) {
columnNameLower = columnNameLower.substr(periodIndex + 1);
}
transform(columnNameLower.begin(), columnNameLower.end(), columnNameLower.begin(), ::tolower);
std::vector<std::string> columnNames;
int ret = GetAllColumnNames(columnNames);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GetColumnIndex return GetAllColumnNames::ret is wrong!");
return ret;
}
columnIndex = 0;
for (const auto& name : columnNames) {
std::string lowerName = name;
transform(name.begin(), name.end(), lowerName.begin(), ::tolower);
if (lowerName == columnNameLower) {
return E_OK;
}
columnIndex++;
}
columnIndex = -1;
return E_ERROR;
}
int DataShareAbsResultSet::GetColumnName(int columnIndex, std::string &columnName)
{
int rowCnt = 0;
int ret = GetColumnCount(rowCnt);
if (ret != E_OK) {
LOG_ERROR("DataShareAbsResultSet::GetColumnName return GetColumnCount::ret is wrong!");
return ret;
}
if (columnIndex >= rowCnt || columnIndex < 0) {
return E_INVALID_COLUMN_INDEX;
}
std::vector<std::string> columnNames;
GetAllColumnNames(columnNames);
columnName = columnNames[columnIndex];
return E_OK;
}
bool DataShareAbsResultSet::IsClosed() const
{
return isClosed_;
}
int DataShareAbsResultSet::Close()
{
isClosed_ = true;
return E_OK;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,211 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_block_writer_impl.h"
#include "datashare_log.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DataShare {
DataShareBlockWriterImpl::DataShareBlockWriterImpl() : shareBlock_(nullptr)
{
}
DataShareBlockWriterImpl::DataShareBlockWriterImpl(const std::string &name, size_t size)
: shareBlock_(nullptr)
{
AppDataFwk::SharedBlock::Create(name, size, shareBlock_);
}
DataShareBlockWriterImpl::~DataShareBlockWriterImpl()
{
}
int DataShareBlockWriterImpl::Clear()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::Clear shareBlock_ is nullptr");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->Clear());
}
int DataShareBlockWriterImpl::SetColumnNum(uint32_t numColumns)
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::SetColumnNum shareBlock_ is nullptr");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->SetColumnNum(numColumns));
}
int DataShareBlockWriterImpl::AllocRow()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::AllocRow shareBlock_ is nullptr");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->AllocRow());
}
int DataShareBlockWriterImpl::FreeLastRow()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::FreeLastRow shareBlock_ is nullptr");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->FreeLastRow());
}
int DataShareBlockWriterImpl::Write(uint32_t column)
{
uint32_t currentRowIndex = 0;
if (!GetCurrentRowIndex(currentRowIndex)) {
LOG_INFO("Write null fail");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->PutNull(currentRowIndex, column));
}
int DataShareBlockWriterImpl::Write(uint32_t column, int64_t value)
{
uint32_t currentRowIndex = 0;
if (!GetCurrentRowIndex(currentRowIndex)) {
LOG_INFO("Write long fail");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->PutLong(currentRowIndex, column, value));
}
int DataShareBlockWriterImpl::Write(uint32_t column, double value)
{
uint32_t currentRowIndex = 0;
if (!GetCurrentRowIndex(currentRowIndex)) {
LOG_INFO("Write double fail");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->PutDouble(currentRowIndex, column, value));
}
int DataShareBlockWriterImpl::Write(uint32_t column, const uint8_t *value, size_t size)
{
uint32_t currentRowIndex = 0;
if (!GetCurrentRowIndex(currentRowIndex)) {
LOG_INFO("Write blob fail");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->PutBlob(currentRowIndex, column, value, size));
}
int DataShareBlockWriterImpl::Write(uint32_t column, const char *value, size_t sizeIncludingNull)
{
uint32_t currentRowIndex = 0;
if (!GetCurrentRowIndex(currentRowIndex)) {
LOG_INFO("Write string fail");
return E_ERROR;
}
return ConvertErrorCode(shareBlock_->PutString(currentRowIndex, column, value, sizeIncludingNull));
}
const void *DataShareBlockWriterImpl::GetHeader()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::GetHeader shareBlock_ is nullptr");
return nullptr;
}
return shareBlock_->GetHeader();
}
size_t DataShareBlockWriterImpl::GetUsedBytes()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::GetUsedBytes shareBlock_ is nullptr");
return E_ERROR;
}
return shareBlock_->GetUsedBytes();
}
std::string DataShareBlockWriterImpl::Name()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::Name shareBlock_ is nullptr");
}
return shareBlock_->Name();
}
size_t DataShareBlockWriterImpl::Size()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::Size shareBlock_ is nullptr");
return E_ERROR;
}
return shareBlock_->Size();
}
uint32_t DataShareBlockWriterImpl::GetRowNum()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::GetRowNum shareBlock_ is nullptr");
return E_ERROR;
}
return shareBlock_->GetRowNum();
}
uint32_t DataShareBlockWriterImpl::GetColumnNum()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::GetColumnNum shareBlock_ is nullptr");
return E_ERROR;
}
return shareBlock_->GetColumnNum();
}
size_t DataShareBlockWriterImpl::SetRawData(const void *rawData, size_t size)
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::SetRawData shareBlock_ is nullptr");
return E_ERROR;
}
return shareBlock_->SetRawData(rawData, size);
}
int DataShareBlockWriterImpl::GetFd()
{
if (shareBlock_ == nullptr) {
LOG_INFO("DataShareBlockWriterImpl::GetFd shareBlock_ is nullptr");
return E_ERROR;
}
return shareBlock_->GetFd();
}
AppDataFwk::SharedBlock *DataShareBlockWriterImpl::GetBlock() const
{
return shareBlock_;
}
bool DataShareBlockWriterImpl::GetCurrentRowIndex(uint32_t &rowIndex)
{
if (shareBlock_ == nullptr) {
LOG_INFO("shareBlock_ is nullptr");
return false;
}
uint32_t rowNum = shareBlock_->GetRowNum();
if (rowNum > 0) {
rowIndex = rowNum - 1;
return true;
}
return false;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,482 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_operation.h"
#include "datashare_log.h"
namespace OHOS {
namespace DataShare {
DataShareOperation::DataShareOperation(
const std::shared_ptr<DataShareOperation> &dataShareOperation, const std::shared_ptr<Uri> &withUri)
{
uri_ = withUri;
if (dataShareOperation != nullptr) {
type_ = dataShareOperation->type_;
valuesBucket_ = dataShareOperation->valuesBucket_;
expectedCount_ = dataShareOperation->expectedCount_;
dataSharePredicates_ = dataShareOperation->dataSharePredicates_;
valuesBucketReferences_ = dataShareOperation->valuesBucketReferences_;
dataSharePredicatesBackReferences_ = dataShareOperation->dataSharePredicatesBackReferences_;
interrupted_ = dataShareOperation->interrupted_;
} else {
type_ = 0;
expectedCount_ = 0;
valuesBucket_ = std::make_shared<DataShareValuesBucket>();
dataSharePredicates_ = std::make_shared<DataSharePredicates>();
valuesBucketReferences_ = std::make_shared<DataShareValuesBucket>();
dataSharePredicatesBackReferences_.clear();
interrupted_ = false;
}
}
DataShareOperation::DataShareOperation(Parcel &in)
{
ReadFromParcel(in);
}
DataShareOperation::DataShareOperation(const std::shared_ptr<DataShareOperationBuilder> &builder)
{
if (builder != nullptr) {
type_ = builder->type_;
uri_ = builder->uri_;
valuesBucket_ = builder->valuesBucket_;
expectedCount_ = builder->expectedCount_;
dataSharePredicates_ = builder->dataSharePredicates_;
valuesBucketReferences_ = builder->valuesBucketReferences_;
dataSharePredicatesBackReferences_ = builder->dataSharePredicatesBackReferences_;
interrupted_ = builder->interrupted_;
}
}
DataShareOperation::DataShareOperation()
{
type_ = 0;
uri_ = nullptr;
expectedCount_ = 0;
valuesBucket_ = std::make_shared<DataShareValuesBucket>();
dataSharePredicates_ = std::make_shared<DataSharePredicates>();
valuesBucketReferences_ = std::make_shared<DataShareValuesBucket>();
dataSharePredicatesBackReferences_.clear();
interrupted_ = false;
}
DataShareOperation::~DataShareOperation()
{
dataSharePredicatesBackReferences_.clear();
}
bool DataShareOperation::operator==(const DataShareOperation &other) const
{
if (type_ != other.type_) {
return false;
}
if ((uri_ != nullptr) && (other.uri_ != nullptr) && (uri_->ToString() != other.uri_->ToString())) {
return false;
}
if (expectedCount_ != other.expectedCount_) {
return false;
}
if (valuesBucket_ != other.valuesBucket_) {
return false;
}
if (dataSharePredicates_ != other.dataSharePredicates_) {
return false;
}
if (valuesBucketReferences_ != other.valuesBucketReferences_) {
return false;
}
size_t backReferencesCount = dataSharePredicatesBackReferences_.size();
size_t otherBackReferencesCount = other.dataSharePredicatesBackReferences_.size();
if (backReferencesCount != otherBackReferencesCount) {
return false;
}
std::map<int, int>::const_iterator it = dataSharePredicatesBackReferences_.begin();
while (it != dataSharePredicatesBackReferences_.end()) {
std::map<int, int>::const_iterator otherIt = other.dataSharePredicatesBackReferences_.find(it->first);
if (otherIt != other.dataSharePredicatesBackReferences_.end()) {
if (otherIt->second != it->second) {
return false;
}
} else {
return false;
}
++it;
}
if (interrupted_ != other.interrupted_) {
return false;
}
return true;
}
DataShareOperation &DataShareOperation::operator=(const DataShareOperation &other)
{
if (this != &other) {
type_ = other.type_;
uri_ = other.uri_;
expectedCount_ = other.expectedCount_;
valuesBucket_ = other.valuesBucket_;
dataSharePredicates_ = other.dataSharePredicates_;
valuesBucketReferences_ = other.valuesBucketReferences_;
dataSharePredicatesBackReferences_ = other.dataSharePredicatesBackReferences_;
interrupted_ = other.interrupted_;
}
return *this;
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperation::NewInsertBuilder(const std::shared_ptr<Uri> &uri)
{
LOG_DEBUG("DataShareOperation::NewInsertBuilder start");
if (uri == nullptr) {
LOG_ERROR("DataShareOperation::NewInsertBuilder uri is nullptr");
return nullptr;
}
std::shared_ptr<DataShareOperationBuilder> builder =
std::make_shared<DataShareOperationBuilder>(TYPE_INSERT, uri);
LOG_DEBUG("DataShareOperation::NewInsertBuilder end");
return builder;
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperation::NewUpdateBuilder(const std::shared_ptr<Uri> &uri)
{
LOG_DEBUG("DataShareOperation::NewUpdateBuilder start");
if (uri == nullptr) {
LOG_ERROR("DataShareOperation::NewUpdateBuilder uri is nullptr");
return nullptr;
}
std::shared_ptr<DataShareOperationBuilder> builder =
std::make_shared<DataShareOperationBuilder>(TYPE_UPDATE, uri);
LOG_DEBUG("DataShareOperation::NewUpdateBuilder end");
return builder;
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperation::NewDeleteBuilder(const std::shared_ptr<Uri> &uri)
{
LOG_DEBUG("DataShareOperation::NewDeleteBuilder start");
if (uri == nullptr) {
LOG_ERROR("DataShareOperation::NewDeleteBuilder uri is nullptr");
return nullptr;
}
std::shared_ptr<DataShareOperationBuilder> builder =
std::make_shared<DataShareOperationBuilder>(TYPE_DELETE, uri);
LOG_DEBUG("DataShareOperation::NewDeleteBuilder end");
return builder;
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperation::NewAssertBuilder(const std::shared_ptr<Uri> &uri)
{
LOG_DEBUG("DataShareOperation::NewAssertBuilder start");
if (uri == nullptr) {
LOG_ERROR("DataShareOperation::NewAssertBuilder uri is nullptr");
return nullptr;
}
std::shared_ptr<DataShareOperationBuilder> builder =
std::make_shared<DataShareOperationBuilder>(TYPE_ASSERT, uri);
LOG_DEBUG("DataShareOperation::NewAssertBuilder end");
return builder;
}
int DataShareOperation::GetType() const
{
LOG_DEBUG("DataShareOperation::GetType");
return type_;
}
std::shared_ptr<Uri> DataShareOperation::GetUri() const
{
LOG_DEBUG("DataShareOperation::GetUri");
return uri_;
}
std::shared_ptr<DataShareValuesBucket> DataShareOperation::GetValuesBucket() const
{
LOG_DEBUG("DataShareOperation::GetValuesBucket");
return valuesBucket_;
}
int DataShareOperation::GetExpectedCount() const
{
LOG_DEBUG("DataShareOperation::GetExpectedCount");
return expectedCount_;
}
std::shared_ptr<DataSharePredicates> DataShareOperation::GetDataSharePredicates() const
{
LOG_DEBUG("DataShareOperation::GetDataSharePredicates");
return dataSharePredicates_;
}
std::shared_ptr<DataShareValuesBucket> DataShareOperation::GetValuesBucketReferences() const
{
LOG_DEBUG("DataShareOperation::GetValuesBucketReferences");
return valuesBucketReferences_;
}
std::map<int, int> DataShareOperation::GetDataSharePredicatesBackReferences() const
{
LOG_DEBUG("DataShareOperation::GetDataSharePredicatesBackReferences");
return dataSharePredicatesBackReferences_;
}
bool DataShareOperation::IsInsertOperation() const
{
LOG_DEBUG("DataShareOperation::IsInsertOperation%d", type_ == TYPE_INSERT);
return type_ == TYPE_INSERT;
}
bool DataShareOperation::IsUpdateOperation() const
{
LOG_DEBUG("DataShareOperation::IsUpdateOperation%d", type_ == TYPE_UPDATE);
return type_ == TYPE_UPDATE;
}
bool DataShareOperation::IsDeleteOperation() const
{
LOG_DEBUG("DataShareOperation::IsDeleteOperation%d", type_ == TYPE_DELETE);
return type_ == TYPE_DELETE;
}
bool DataShareOperation::IsAssertOperation() const
{
LOG_DEBUG("DataShareOperation::IsAssertOperation%d", type_ == TYPE_ASSERT);
return type_ == TYPE_ASSERT;
}
bool DataShareOperation::IsInterruptionAllowed() const
{
LOG_DEBUG("DataShareOperation::IsInterruptionAllowed%d", interrupted_);
return interrupted_;
}
bool DataShareOperation::Marshalling(Parcel &out) const
{
LOG_DEBUG("DataShareOperation::Marshalling start");
if (!out.WriteInt32(type_)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(type_) error");
return false;
}
if (!out.WriteInt32(expectedCount_)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (!out.WriteBool(interrupted_)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (uri_ != nullptr) {
if (!out.WriteInt32(VALUE_OBJECT)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (!out.WriteParcelable(uri_.get())) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
} else {
if (!out.WriteInt32(VALUE_NULL)) {
return false;
}
}
if (valuesBucket_ != nullptr) {
if (!out.WriteInt32(VALUE_OBJECT)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (!DataShareValuesBucket::Marshalling(*valuesBucket_, out)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
} else {
if (!out.WriteInt32(VALUE_NULL)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
}
if (dataSharePredicates_ != nullptr) {
if (!out.WriteInt32(VALUE_OBJECT)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (!out.WriteParcelable(dataSharePredicates_.get())) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
} else {
if (!out.WriteInt32(VALUE_NULL)) {
return false;
}
}
if (valuesBucketReferences_ != nullptr) {
if (!out.WriteInt32(VALUE_OBJECT)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (!DataShareValuesBucket::Marshalling(*valuesBucketReferences_, out)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
} else {
if (!out.WriteInt32(VALUE_NULL)) {
return false;
}
}
int referenceSize = 0;
if (!dataSharePredicatesBackReferences_.empty()) {
referenceSize = (int)dataSharePredicatesBackReferences_.size();
if (!out.WriteInt32(referenceSize)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (referenceSize >= REFERENCE_THRESHOLD) {
LOG_INFO("DataShareOperation::Marshalling referenceSize >= REFERENCE_THRESHOLD");
return true;
}
for (auto &it : dataSharePredicatesBackReferences_) {
if (!out.WriteInt32(it.first)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
if (!out.WriteInt32(it.second)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
}
} else {
LOG_DEBUG("DataShareOperation::Marshalling dataSharePredicatesBackReferences_ is empty");
if (!out.WriteInt32(referenceSize)) {
LOG_ERROR("DataShareOperation::Marshalling WriteInt32(VALUE_OBJECT) error");
return false;
}
}
LOG_DEBUG("DataShareOperation::Marshalling end");
return true;
}
DataShareOperation *DataShareOperation::Unmarshalling(Parcel &in)
{
LOG_DEBUG("DataShareOperation::Unmarshalling start");
DataShareOperation *dataShareOperation = new (std::nothrow) DataShareOperation();
if (dataShareOperation != nullptr && !dataShareOperation->ReadFromParcel(in)) {
LOG_ERROR("DataShareOperation::Unmarshalling dataShareOperation error");
delete dataShareOperation;
dataShareOperation = nullptr;
}
LOG_DEBUG("DataShareOperation::Unmarshalling end");
return dataShareOperation;
}
bool DataShareOperation::ReadFromParcel(Parcel &in)
{
LOG_DEBUG("DataShareOperation::ReadFromParcel start");
if (!in.ReadInt32(type_)) {
LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(type_) error");
return false;
}
if (!in.ReadInt32(expectedCount_)) {
LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error");
return false;
}
interrupted_ = in.ReadBool();
int empty = VALUE_NULL;
if (!in.ReadInt32(empty)) {
LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error");
return false;
}
if (empty == VALUE_OBJECT) {
uri_.reset(in.ReadParcelable<Uri>());
} else {
uri_.reset();
}
empty = VALUE_NULL;
if (!in.ReadInt32(empty)) {
LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error");
return false;
}
LOG_DEBUG("DataShareOperation::ReadFromParcel empty is %{public}s",
empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL");
if (empty == VALUE_OBJECT) {
valuesBucket_.reset(DataShareValuesBucket::Unmarshalling(in));
} else {
valuesBucket_.reset();
}
empty = VALUE_NULL;
if (!in.ReadInt32(empty)) {
LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error");
return false;
}
LOG_DEBUG("DataShareOperation::ReadFromParcel empty is %{public}s",
empty == VALUE_OBJECT ? "VALUE_OBJECT" : "VALUE_NULL");
if (empty == VALUE_OBJECT) {
dataSharePredicates_.reset(in.ReadParcelable<DataSharePredicates>());
} else {
dataSharePredicates_.reset();
}
empty = VALUE_NULL;
if (!in.ReadInt32(empty)) {
LOG_ERROR("DataShareOperation::ReadFromParcel ReadInt32(empty) error");
return false;
}
LOG_DEBUG("DataShareOperation::ReadFromParcel empty is %{public}s",
(empty == VALUE_OBJECT) ? "VALUE_OBJECT" : "VALUE_NULL");
if (empty == VALUE_OBJECT) {
valuesBucketReferences_.reset(DataShareValuesBucket::Unmarshalling(in));
} else {
valuesBucketReferences_.reset();
}
int referenceSize = 0;
if (!in.ReadInt32(referenceSize)) {
LOG_ERROR("DataShareOperation::ReadFromParcel end");
return false;
}
if (referenceSize >= REFERENCE_THRESHOLD) {
LOG_INFO("DataShareOperation::ReadFromParcel referenceSize:%{public}d >= REFERENCE_THRESHOLD:%{public}d",
referenceSize, REFERENCE_THRESHOLD);
return true;
}
for (int i = 0; i < REFERENCE_THRESHOLD && i < referenceSize; ++i) {
int first = 0;
int second = 0;
if (!in.ReadInt32(first)) {
LOG_ERROR("DataShareOperation::ReadFromParcel end");
return false;
}
if (!in.ReadInt32(second)) {
LOG_ERROR("DataShareOperation::ReadFromParcel end");
return false;
}
dataSharePredicatesBackReferences_.insert(std::make_pair(first, second));
}
LOG_DEBUG("DataShareOperation::ReadFromParcel end");
return true;
}
std::shared_ptr<DataShareOperation> DataShareOperation::CreateFromParcel(Parcel &in)
{
LOG_DEBUG("DataShareOperation::CreateFromParcel start");
std::shared_ptr<DataShareOperation> operation = std::make_shared<DataShareOperation>(in);
LOG_DEBUG("DataShareOperation::CreateFromParcel end");
return operation;
}
void DataShareOperation::PutMap(Parcel &in)
{
LOG_DEBUG("DataShareOperation::PutMap start");
int count = in.ReadInt32();
if (count > 0 && count < REFERENCE_THRESHOLD) {
for (int i = 0; i < count; ++i) {
dataSharePredicatesBackReferences_.insert(std::make_pair(in.ReadInt32(), in.ReadInt32()));
}
}
LOG_DEBUG("DataShareOperation::PutMap end");
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,154 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_operation_builder.h"
#include "datashare_log.h"
#include "datashare_operation.h"
#include "datashare_value_object.h"
#include "datashare_values_bucket.h"
namespace OHOS::DataShare { class DataSharePredicates; }
namespace OHOS {
namespace DataShare {
DataShareOperationBuilder::DataShareOperationBuilder(const int type, const std::shared_ptr<Uri> &uri)
{
type_ = type;
uri_ = uri;
expectedCount_ = 0;
interrupted_ = false;
valuesBucket_ = nullptr;
dataSharePredicates_ = nullptr;
valuesBucketReferences_ = nullptr;
dataSharePredicatesBackReferences_.clear();
}
DataShareOperationBuilder::~DataShareOperationBuilder()
{
dataSharePredicatesBackReferences_.clear();
}
std::shared_ptr<DataShareOperation> DataShareOperationBuilder::Build()
{
LOG_DEBUG("DataShareOperationBuilder::Build start");
if (type_ != DataShareOperation::TYPE_UPDATE || (valuesBucket_ != nullptr && !valuesBucket_->IsEmpty())) {
std::shared_ptr<DataShareOperation> operation = std::make_shared<DataShareOperation>(shared_from_this());
LOG_DEBUG("DataShareOperationBuilder::Build end");
return operation;
}
LOG_ERROR("DataShareOperationBuilder::Build return nullptr");
return nullptr;
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperationBuilder::WithValuesBucket(
std::shared_ptr<DataShareValuesBucket> &values)
{
LOG_DEBUG("DataShareOperationBuilder::WithValuesBucket start");
if (type_ != DataShareOperation::TYPE_INSERT && type_ != DataShareOperation::TYPE_UPDATE &&
type_ != DataShareOperation::TYPE_ASSERT) {
LOG_ERROR(
"DataShareOperationBuilder::WithValuesBucket only inserts, updates can have values, type=%{public}d",
type_);
return nullptr;
}
std::map<std::string, DataShareValueObject> valuesMap;
values->GetAll(valuesMap);
valuesBucket_.reset(new (std::nothrow) DataShareValuesBucket(valuesMap));
LOG_DEBUG("DataShareOperationBuilder::WithValuesBucket end");
return shared_from_this();
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperationBuilder::WithPredicates(
std::shared_ptr<DataSharePredicates> &predicates)
{
LOG_DEBUG("DataShareOperationBuilder::WithPredicates start");
if (type_ != DataShareOperation::TYPE_DELETE && type_ != DataShareOperation::TYPE_UPDATE &&
type_ != DataShareOperation::TYPE_ASSERT) {
LOG_ERROR(
"DataShareOperationBuilder::withPredicates only deletes and updates can have selections, type=%{public}d",
type_);
return nullptr;
}
dataSharePredicates_ = predicates;
LOG_DEBUG("DataShareOperationBuilder::WithPredicates end");
return shared_from_this();
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperationBuilder::WithExpectedCount(int count)
{
LOG_DEBUG("DataShareOperationBuilder::WithExpectedCount start");
LOG_INFO("DataShareOperationBuilder::WithExpectedCount expectedCount:%{public}d", count);
if (type_ != DataShareOperation::TYPE_UPDATE && type_ != DataShareOperation::TYPE_DELETE &&
type_ != DataShareOperation::TYPE_ASSERT) {
LOG_ERROR("DataShareOperationBuilder::withExpectedCount only updates, deletes can have expected counts, "
"type=%{public}d",
type_);
return nullptr;
}
expectedCount_ = count;
LOG_DEBUG("DataShareOperationBuilder::WithExpectedCount end");
return shared_from_this();
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperationBuilder::WithPredicatesBackReference(
int requestArgIndex, int previousResult)
{
LOG_DEBUG("DataShareOperationBuilder::WithPredicatesBackReference start");
LOG_INFO("DataShareOperationBuilder::WithPredicatesBackReference requestArgIndex:%{public}d, "
"previousResult:%{public}d",
requestArgIndex,
previousResult);
if (type_ != DataShareOperation::TYPE_UPDATE && type_ != DataShareOperation::TYPE_DELETE &&
type_ != DataShareOperation::TYPE_ASSERT) {
LOG_ERROR(
"DataShareOperationBuilder::withPredicatesBackReference only updates, deletes, and asserts can have "
"select back-references, type=%{public}d",
type_);
return nullptr;
}
dataSharePredicatesBackReferences_.insert(std::make_pair(requestArgIndex, previousResult));
LOG_DEBUG("DataShareOperationBuilder::WithPredicatesBackReference end");
return shared_from_this();
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperationBuilder::WithValueBackReferences(
std::shared_ptr<DataShareValuesBucket> &backReferences)
{
LOG_DEBUG("DataShareOperationBuilder::WithValueBackReferences start");
if (type_ != DataShareOperation::TYPE_INSERT && type_ != DataShareOperation::TYPE_UPDATE &&
type_ != DataShareOperation::TYPE_ASSERT) {
LOG_ERROR("DataShareOperationBuilder::withValueBackReferences only inserts, updates, and asserts can have "
"value back-references, type=%{public}d",
type_);
return nullptr;
}
valuesBucketReferences_ = backReferences;
LOG_DEBUG("DataShareOperationBuilder::WithValueBackReferences end");
return shared_from_this();
}
std::shared_ptr<DataShareOperationBuilder> DataShareOperationBuilder::WithInterruptionAllowed(bool interrupted)
{
LOG_DEBUG("DataShareOperationBuilder::WithInterruptionAllowed start");
LOG_INFO("DataShareOperationBuilder::WithInterruptionAllowed interrupted=%{public}d", interrupted);
if (type_ != DataShareOperation::TYPE_INSERT && type_ != DataShareOperation::TYPE_UPDATE &&
type_ != DataShareOperation::TYPE_ASSERT && type_ != DataShareOperation::TYPE_DELETE) {
LOG_ERROR(
"DataShareOperationBuilder::withInterruptionAllowed only inserts, updates, delete, and asserts can "
"have value back-references, type=%{public}d",
type_);
return nullptr;
}
interrupted_ = interrupted;
LOG_DEBUG("DataShareOperationBuilder::WithInterruptionAllowed end");
return shared_from_this();
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,559 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_predicates.h"
#include "datashare_log.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DataShare {
DataSharePredicates::DataSharePredicates()
{
}
DataSharePredicates::DataSharePredicates(Predicates &predicates)
: predicates_(predicates)
{
}
DataSharePredicates::~DataSharePredicates()
{
}
/**
* EqualTo
*/
DataSharePredicates *DataSharePredicates::EqualTo(const std::string &field, const DataSharePredicatesObject &value)
{
LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str());
SetOperationList(EQUAL_TO, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::EqualTo End");
return this;
}
/**
* NotEqualTo
*/
DataSharePredicates *DataSharePredicates::NotEqualTo(const std::string &field, const DataSharePredicatesObject &value)
{
LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str());
SetOperationList(NOT_EQUAL_TO, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::NotEqualTo End");
return this;
}
/**
* GreaterThan
*/
DataSharePredicates *DataSharePredicates::GreaterThan(const std::string &field, const DataSharePredicatesObject &value)
{
LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str());
SetOperationList(GREATER_THAN, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::GreaterThan End");
return this;
}
/**
* LessThan
*/
DataSharePredicates *DataSharePredicates::LessThan(const std::string &field, const DataSharePredicatesObject &value)
{
LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str());
SetOperationList(LESS_THAN, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::LessThan End");
return this;
}
/**
* GreaterThanOrEqualTo
*/
DataSharePredicates *DataSharePredicates::GreaterThanOrEqualTo(const std::string &field,
const DataSharePredicatesObject &value)
{
LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str());
SetOperationList(GREATER_THAN_OR_EQUAL_TO, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::GreaterThanOrEqualTo End");
return this;
}
/**
* LessThanOrEqualTo
*/
DataSharePredicates *DataSharePredicates::LessThanOrEqualTo(const std::string &field,
const DataSharePredicatesObject &value)
{
LOG_DEBUG("%{public}s call field%{public}s", __func__, field.c_str());
SetOperationList(LESS_THAN_OR_EQUAL_TO, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::LessThanOrEqualTo End");
return this;
}
/**
* In
*/
DataSharePredicates *DataSharePredicates::In(const std::string &field, const DataSharePredicatesObject &value)
{
LOG_DEBUG("DataSharePredicates::In Start field%{public}s", field.c_str());
SetOperationList(IN, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::In End");
return this;
}
/**
* NotIn
*/
DataSharePredicates *DataSharePredicates::NotIn(const std::string &field, const DataSharePredicatesObject &value)
{
LOG_DEBUG("DataSharePredicates::NotIn Start field%{public}s", field.c_str());
SetOperationList(NOT_IN, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::NotIn End");
return this;
}
/**
* BeginWrap
*/
DataSharePredicates *DataSharePredicates::BeginWrap()
{
LOG_DEBUG("DataSharePredicates::BeginWrap Start");
SetOperationList(BEGIN_WARP, {}, {}, {}, ZERO_COUNT);
LOG_DEBUG("DataSharePredicates::BeginWrap End");
return this;
}
/**
* EndWrap
*/
DataSharePredicates *DataSharePredicates::EndWrap()
{
LOG_DEBUG("DataSharePredicates::EndWrap Start");
SetOperationList(END_WARP, {}, {}, {}, ZERO_COUNT);
LOG_DEBUG("DataSharePredicates::EndWrap End");
return this;
}
/**
* Or
*/
DataSharePredicates *DataSharePredicates::Or()
{
LOG_DEBUG("DataSharePredicates::Or Start");
SetOperationList(OR, {}, {}, {}, ZERO_COUNT);
LOG_DEBUG("DataSharePredicates::Or End");
return this;
}
/**
* And
*/
DataSharePredicates *DataSharePredicates::And()
{
LOG_DEBUG("DataSharePredicates::And Start");
SetOperationList(AND, {}, {}, {}, ZERO_COUNT);
LOG_DEBUG("DataSharePredicates::And End");
return this;
}
/**
* Contains
*/
DataSharePredicates *DataSharePredicates::Contains(const std::string &field, const std::string &value)
{
LOG_DEBUG("DataSharePredicates::Contains Start field%{public}s,value%{public}s", field.c_str(), value.c_str());
SetOperationList(CONTAINS, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::Contains End");
return this;
}
/**
* BeginsWith
*/
DataSharePredicates *DataSharePredicates::BeginsWith(const std::string &field, const std::string &value)
{
LOG_DEBUG("DataSharePredicates::BeginsWith Start field%{public}s,value%{public}s", field.c_str(), value.c_str());
SetOperationList(BEGIN_WITH, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::BeginsWith End");
return this;
}
/**
* EndsWith
*/
DataSharePredicates *DataSharePredicates::EndsWith(const std::string &field, const std::string &value)
{
LOG_DEBUG("DataSharePredicates::EndsWith Start field%{public}s,value%{public}s", field.c_str(), value.c_str());
SetOperationList(END_WITH, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::EndsWith End");
return this;
}
/**
* IsNull
*/
DataSharePredicates *DataSharePredicates::IsNull(const std::string &field)
{
LOG_DEBUG("DataSharePredicates::IsNull Start field%{public}s", field.c_str());
SetOperationList(IS_NULL, field, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::IsNull End");
return this;
}
/**
* IsNotNull
*/
DataSharePredicates *DataSharePredicates::IsNotNull(const std::string &field)
{
LOG_DEBUG("DataSharePredicates::IsNotNull Start field%{public}s", field.c_str());
SetOperationList(IS_NOT_NULL, field, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::IsNotNull End");
return this;
}
/**
* Like
*/
DataSharePredicates *DataSharePredicates::Like(const std::string &field, const std::string &value)
{
LOG_DEBUG("DataSharePredicates::Like Start field%{public}s value%{public}s", field.c_str(), value.c_str());
SetOperationList(LIKE, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::Like End");
return this;
}
/**
* UnLike
*/
DataSharePredicates *DataSharePredicates::Unlike(const std::string &field, const std::string &value)
{
LOG_DEBUG("DataSharePredicates::Unlike Start field%{public}s value%{public}s", field.c_str(), value.c_str());
SetOperationList(UNLIKE, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::Unlike End");
return this;
}
/**
* Glob
*/
DataSharePredicates *DataSharePredicates::Glob(const std::string &field, const std::string &value)
{
LOG_DEBUG("DataSharePredicates::Glob Start field%{public}s value%{public}s", field.c_str(), value.c_str());
SetOperationList(GLOB, field, value, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::Glob End");
return this;
}
/**
* Between
*/
DataSharePredicates *DataSharePredicates::Between(const std::string &field,
const std::string &low, const std::string &high)
{
LOG_DEBUG("DataSharePredicates::Between Start field%{public}s low%{public}s high%{public}s",
field.c_str(), low.c_str(), high.c_str());
SetOperationList(BETWEEN, field, low, high, THREE_COUNT);
LOG_DEBUG("DataSharePredicates::Between End");
return this;
}
/**
* NotBetween
*/
DataSharePredicates *DataSharePredicates::NotBetween(const std::string &field,
const std::string &low, const std::string &high)
{
LOG_DEBUG("DataSharePredicates::NotBetween Start field%{public}s low%{public}s high%{public}s",
field.c_str(), low.c_str(), high.c_str());
SetOperationList(NOTBETWEEN, field, low, high, THREE_COUNT);
LOG_DEBUG("DataSharePredicates::NotBetween End");
return this;
}
/**
* OrderByAsc
*/
DataSharePredicates *DataSharePredicates::OrderByAsc(const std::string &field)
{
LOG_DEBUG("DataSharePredicates::OrderByAsc Start field%{public}s", field.c_str());
SetOperationList(ORDER_BY_ASC, field, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::OrderByAsc End");
return this;
}
/**
* OrderByDesc
*/
DataSharePredicates *DataSharePredicates::OrderByDesc(const std::string &field)
{
LOG_DEBUG("DataSharePredicates::OrderByDesc Start field%{public}s", field.c_str());
SetOperationList(ORDER_BY_DESC, field, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::OrderByDesc End");
return this;
}
/**
* Distinct
*/
DataSharePredicates *DataSharePredicates::Distinct()
{
LOG_DEBUG("DataSharePredicates::Distinct Start");
SetOperationList(DISTINCT, {}, {}, {}, ZERO_COUNT);
LOG_DEBUG("DataSharePredicates::Distinct End");
return this;
}
/**
* Limit
*/
DataSharePredicates *DataSharePredicates::Limit(const int number, const int offset)
{
LOG_DEBUG("DataSharePredicates::Limit Start number : %{public}d, offset : %{public}d", number, offset);
SetOperationList(LIMIT, number, offset, {}, TWO_COUNT);
LOG_DEBUG("DataSharePredicates::Limit End");
return this;
}
/**
* GroupBy
*/
DataSharePredicates *DataSharePredicates::GroupBy(const std::vector<std::string> &fields)
{
LOG_DEBUG("DataSharePredicates::GroupBy Start fields%{public}s", fields.at(0).c_str());
SetOperationList(GROUP_BY, fields, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::GroupBy End");
return this;
}
/**
* IndexedBy
*/
DataSharePredicates *DataSharePredicates::IndexedBy(const std::string &indexName)
{
LOG_DEBUG("DataSharePredicates::IndexedBy Start indexName%{public}s", indexName.c_str());
SetOperationList(INDEXED_BY, indexName, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::IndexedBy End");
return this;
}
/**
* KeyPrefix
*/
DataSharePredicates *DataSharePredicates::KeyPrefix(const std::string &prefix)
{
LOG_DEBUG("DataSharePredicates::KeyPrefix Start prefix%{public}s", prefix.c_str());
SetOperationList(KEY_PREFIX, prefix, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::KeyPrefix End");
return this;
}
/**
* InKeys
*/
DataSharePredicates *DataSharePredicates::InKeys(const std::vector<std::string> &keys)
{
LOG_DEBUG("DataSharePredicates::InKeys Start keys%{public}s", keys.at(0).c_str());
SetOperationList(IN_KEY, keys, {}, {}, ONE_COUNT);
LOG_DEBUG("DataSharePredicates::InKeys End");
return this;
}
/**
* Obtains the table name.
*/
std::string DataSharePredicates::GetTableName() const
{
return predicates_.tableName;
}
/**
* GetOperationList
*/
const std::list<OperationItem>& DataSharePredicates::GetOperationList() const
{
return predicates_.operationList;
}
/**
* Get WhereClause
*/
std::string DataSharePredicates::GetWhereClause() const
{
return whereClause_;
}
/**
* Set WhereClause
*/
int DataSharePredicates::SetWhereClause(const std::string &whereClause)
{
if ((settingMode_ != PREDICATES_METHOD) && (!whereClause.empty())) {
this->whereClause_ = whereClause;
settingMode_ = QUERY_LANGUAGE;
return E_OK;
}
return E_ERROR;
}
/**
* Get WhereArgs
*/
std::vector<std::string> DataSharePredicates::GetWhereArgs() const
{
return whereArgs_;
}
/**
* Get WhereArgs
*/
int DataSharePredicates::SetWhereArgs(const std::vector<std::string> &whereArgs)
{
if ((settingMode_ != PREDICATES_METHOD) && (!whereArgs.empty())) {
if (!whereArgs.empty()) {
this->whereArgs_ = whereArgs;
settingMode_ = QUERY_LANGUAGE;
return E_OK;
}
}
return E_ERROR;
}
/**
* Get Order
*/
std::string DataSharePredicates::GetOrder() const
{
return order_;
}
/**
* Set Order
*/
int DataSharePredicates::SetOrder(const std::string &order)
{
LOG_DEBUG("DataSharePredicates::SetOrder Start order%{public}s", order.c_str());
if ((settingMode_ != PREDICATES_METHOD) && (!order.empty())) {
this->order_ = order;
settingMode_ = QUERY_LANGUAGE;
return E_OK;
}
return E_ERROR;
}
/**
* Clear Query Language
*/
void DataSharePredicates::ClearQueryLanguage()
{
whereClause_ = "";
whereArgs_ = {};
order_ = "";
}
/**
* Set Setting Mode
*/
void DataSharePredicates::SetSettingMode(const SettingMode &settingMode)
{
settingMode_ = settingMode;
}
/**
* Get Setting Mode
*/
SettingMode DataSharePredicates::GetSettingMode() const
{
return settingMode_;
}
/**
* SetOperationList
*/
void DataSharePredicates::SetOperationList(OperationType operationType, const DataSharePredicatesObject &para1,
const DataSharePredicatesObject &para2, const DataSharePredicatesObject &para3, ParameterCount parameterCount)
{
LOG_DEBUG("DataSharePredicates::SetOperationList Start");
OperationItem operationItem {};
operationItem.operation = operationType;
operationItem.para1 = para1;
operationItem.para2 = para2;
operationItem.para3 = para3;
operationItem.parameterCount = parameterCount;
predicates_.operationList.push_back(operationItem);
if (settingMode_ != PREDICATES_METHOD) {
ClearQueryLanguage();
settingMode_ = PREDICATES_METHOD;
}
LOG_DEBUG("DataSharePredicates::SetOperationList END settingMode_%{public}d", settingMode_);
}
/**
* Write DataSharePredicates object to Parcel.
*/
bool DataSharePredicates::Marshalling(OHOS::Parcel &parcel) const
{
LOG_DEBUG("DataSharePredicates::Marshalling Start");
parcel.WriteInt32(predicates_.operationList.size());
for (auto &it : predicates_.operationList) {
parcel.WriteInt64(static_cast<int64_t>(it.operation));
parcel.WriteParcelable(&it.para1);
parcel.WriteParcelable(&it.para2);
parcel.WriteParcelable(&it.para3);
parcel.WriteInt64(static_cast<int64_t>(it.parameterCount));
}
parcel.WriteString(whereClause_);
parcel.WriteStringVector(whereArgs_);
parcel.WriteString(order_);
parcel.WriteInt64(static_cast<int64_t>(settingMode_));
LOG_DEBUG("DataSharePredicates::Marshalling End");
return true;
}
/**
* Read from Parcel object.
*/
DataSharePredicates* DataSharePredicates::Unmarshalling(OHOS::Parcel &parcel)
{
LOG_DEBUG("DataSharePredicates::Unmarshalling Start");
Predicates predicates {};
OperationItem listitem {};
std::string whereClause = "";
std::vector<std::string> whereArgs;
std::string order = "";
int64_t settingMode = INVALID_MODE;
int listSize = parcel.ReadInt32();
for (int i = 0; i < listSize; i++) {
listitem.operation = static_cast<OperationType>(parcel.ReadInt64());
DataSharePredicatesObject *parameter1 = parcel.ReadParcelable<DataSharePredicatesObject>();
listitem.para1 = *parameter1;
DataSharePredicatesObject *parameter2 = parcel.ReadParcelable<DataSharePredicatesObject>();
listitem.para2 = *parameter2;
DataSharePredicatesObject *parameter3 = parcel.ReadParcelable<DataSharePredicatesObject>();
listitem.para3 = *parameter3;
listitem.parameterCount = static_cast<ParameterCount>(parcel.ReadInt64());
predicates.operationList.push_back(listitem);
}
parcel.ReadString(whereClause);
parcel.ReadStringVector(&whereArgs);
parcel.ReadString(order);
parcel.ReadInt64(settingMode);
SettingMode settingmode = static_cast<SettingMode>(settingMode);
auto predicatesObject = new DataSharePredicates(predicates);
predicatesObject->SetWhereClause(whereClause);
predicatesObject->SetWhereArgs(whereArgs);
predicatesObject->SetOrder(order);
predicatesObject->SetSettingMode(settingmode);
LOG_DEBUG("DataSharePredicates::Unmarshalling End");
return predicatesObject;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,358 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_predicates_object.h"
#include "datashare_log.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DataShare {
DataSharePredicatesObject::DataSharePredicatesObject() : type(DataSharePredicatesObjectType::TYPE_NULL)
{
}
DataSharePredicatesObject::DataSharePredicatesObject(DataSharePredicatesObject &&DataSharePredicatesObject) noexcept
{
if (this == &DataSharePredicatesObject) {
return;
}
type = DataSharePredicatesObject.type;
value = std::move(DataSharePredicatesObject.value);
DataSharePredicatesObject.type = DataSharePredicatesObjectType::TYPE_NULL;
}
DataSharePredicatesObject::DataSharePredicatesObject(const DataSharePredicatesObject &DataSharePredicatesObject)
{
if (this == &DataSharePredicatesObject) {
return;
}
type = DataSharePredicatesObject.type;
value = DataSharePredicatesObject.value;
}
DataSharePredicatesObject::~DataSharePredicatesObject()
{
}
DataSharePredicatesObject::DataSharePredicatesObject(int val) : type(DataSharePredicatesObjectType::TYPE_INT)
{
value = val;
}
DataSharePredicatesObject::DataSharePredicatesObject(int64_t val) : type(DataSharePredicatesObjectType::TYPE_LONG)
{
value = val;
}
DataSharePredicatesObject::DataSharePredicatesObject(double val) : type(DataSharePredicatesObjectType::TYPE_DOUBLE)
{
value = val;
}
DataSharePredicatesObject::DataSharePredicatesObject(bool val) : type(DataSharePredicatesObjectType::TYPE_BOOL)
{
value = val;
}
DataSharePredicatesObject::DataSharePredicatesObject(const std::string &val)
: type(DataSharePredicatesObjectType::TYPE_STRING)
{
value = val;
}
DataSharePredicatesObject::DataSharePredicatesObject(const std::vector<int> &val)
: type(DataSharePredicatesObjectType::TYPE_INT_VECTOR)
{
std::vector<int64_t> int64val {};
if (!val.empty()) {
for (const auto &it : val) {
int64val.push_back(static_cast<int64_t>(it));
}
value = int64val;
}
}
DataSharePredicatesObject::DataSharePredicatesObject(const std::vector<int64_t> &val)
: type(DataSharePredicatesObjectType::TYPE_LONG_VECTOR)
{
std::vector<int64_t> parameter = val;
value = parameter;
}
DataSharePredicatesObject::DataSharePredicatesObject(const std::vector<std::string> &val)
: type(DataSharePredicatesObjectType::TYPE_STRING_VECTOR)
{
std::vector<std::string> parameter = val;
value = parameter;
}
DataSharePredicatesObject::DataSharePredicatesObject(const std::vector<double> &val)
: type(DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR)
{
std::vector<double> parameter = val;
value = parameter;
}
DataSharePredicatesObject &DataSharePredicatesObject::operator=(
DataSharePredicatesObject &&DataSharePredicatesObject) noexcept
{
if (this == &DataSharePredicatesObject) {
return *this;
}
type = DataSharePredicatesObject.type;
value = std::move(DataSharePredicatesObject.value);
DataSharePredicatesObject.type = DataSharePredicatesObjectType::TYPE_NULL;
return *this;
}
DataSharePredicatesObject &DataSharePredicatesObject::operator=(
const DataSharePredicatesObject &DataSharePredicatesObject)
{
if (this == &DataSharePredicatesObject) {
return *this;
}
type = DataSharePredicatesObject.type;
value = DataSharePredicatesObject.value;
return *this;
}
DataSharePredicatesObjectType DataSharePredicatesObject::GetType() const
{
return type;
}
int DataSharePredicatesObject::GetInt(int &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_INT) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<int>(value);
return E_OK;
}
int DataSharePredicatesObject::GetLong(int64_t &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_INT) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<int64_t>(value);
return E_OK;
}
int DataSharePredicatesObject::GetDouble(double &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_DOUBLE) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<double>(value);
return E_OK;
}
int DataSharePredicatesObject::GetBool(bool &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_BOOL) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<bool>(value);
return E_OK;
}
int DataSharePredicatesObject::GetString(std::string &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_STRING) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<std::string>(value);
return E_OK;
}
int DataSharePredicatesObject::GetIntVector(std::vector<int> &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_INT_VECTOR) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<std::vector<int>>(value);
return E_OK;
}
int DataSharePredicatesObject::GetLongVector(std::vector<int64_t> &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_LONG_VECTOR) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<std::vector<int64_t>>(value);
return E_OK;
}
int DataSharePredicatesObject::GetDoubleVector(std::vector<double> &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<std::vector<double>>(value);
return E_OK;
}
int DataSharePredicatesObject::GetStringVector(std::vector<std::string> &val) const
{
if (type != DataSharePredicatesObjectType::TYPE_STRING_VECTOR) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<std::vector<std::string>>(value);
return E_OK;
}
bool DataSharePredicatesObject::Marshalling(Parcel &parcel) const
{
LOG_DEBUG("DataSharePredicatesObject::Marshalling Start");
parcel.WriteInt16((int16_t)this->type);
switch (this->type) {
case DataSharePredicatesObjectType::TYPE_NULL: {
break;
}
case DataSharePredicatesObjectType::TYPE_INT: {
parcel.WriteInt32(std::get<int>(value));
break;
}
case DataSharePredicatesObjectType::TYPE_LONG: {
parcel.WriteInt64(std::get<int64_t>(value));
break;
}
case DataSharePredicatesObjectType::TYPE_DOUBLE: {
parcel.WriteDouble(std::get<double>(value));
break;
}
case DataSharePredicatesObjectType::TYPE_STRING: {
parcel.WriteString(std::get<std::string>(value));
break;
}
case DataSharePredicatesObjectType::TYPE_BOOL: {
parcel.WriteBool(std::get<bool>(value));
break;
}
default:
break;
}
MarshallingVector(parcel);
LOG_DEBUG("DataSharePredicatesObject::Marshalling End");
return true;
}
DataSharePredicatesObject *DataSharePredicatesObject::Unmarshalling(Parcel &parcel)
{
LOG_DEBUG("DataSharePredicatesObject::Unmarshalling Start");
auto *pValueObject = new DataSharePredicatesObject();
if (pValueObject != nullptr) {
pValueObject->type = (DataSharePredicatesObjectType)parcel.ReadInt16();
switch (pValueObject->type) {
case DataSharePredicatesObjectType::TYPE_NULL: {
break;
}
case DataSharePredicatesObjectType::TYPE_INT: {
pValueObject->value = parcel.ReadInt32();
break;
}
case DataSharePredicatesObjectType::TYPE_LONG: {
pValueObject->value = parcel.ReadInt64();
break;
}
case DataSharePredicatesObjectType::TYPE_DOUBLE: {
pValueObject->value = parcel.ReadDouble();
break;
}
case DataSharePredicatesObjectType::TYPE_STRING: {
pValueObject->value = parcel.ReadString();
break;
}
case DataSharePredicatesObjectType::TYPE_BOOL: {
pValueObject->value = parcel.ReadBool();
break;
}
default:
break;
}
UnmarshallingVector(pValueObject->type, pValueObject, parcel);
}
LOG_DEBUG("DataSharePredicatesObject::Unmarshalling End");
return pValueObject;
}
void DataSharePredicatesObject::UnmarshallingVector(DataSharePredicatesObjectType type,
DataSharePredicatesObject *pValueObject, Parcel &parcel)
{
switch (type) {
case DataSharePredicatesObjectType::TYPE_INT_VECTOR: {
std::vector<int> intval {};
parcel.ReadInt32Vector(&intval);
pValueObject->value = intval;
break;
}
case DataSharePredicatesObjectType::TYPE_LONG_VECTOR: {
std::vector<int64_t> int64val {};
parcel.ReadInt64Vector(&int64val);
pValueObject->value = int64val;
break;
}
case DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR: {
std::vector<double> doubleval {};
parcel.ReadDoubleVector(&doubleval);
pValueObject->value = doubleval;
break;
}
case DataSharePredicatesObjectType::TYPE_STRING_VECTOR: {
std::vector<std::string> stringval {};
parcel.ReadStringVector(&stringval);
pValueObject->value = stringval;
break;
}
default:
break;
}
}
void DataSharePredicatesObject::MarshallingVector(Parcel &parcel) const
{
switch (this->type) {
case DataSharePredicatesObjectType::TYPE_INT_VECTOR: {
parcel.WriteInt32Vector(std::get<std::vector<int>>(value));
break;
}
case DataSharePredicatesObjectType::TYPE_LONG_VECTOR: {
parcel.WriteInt64Vector(std::get<std::vector<int64_t>>(value));
break;
}
case DataSharePredicatesObjectType::TYPE_DOUBLE_VECTOR: {
parcel.WriteDoubleVector(std::get<std::vector<double>>(value));
break;
}
case DataSharePredicatesObjectType::TYPE_STRING_VECTOR: {
parcel.WriteStringVector(std::get<std::vector<std::string>>(value));
break;
}
default:
break;
}
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,180 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_result.h"
#include "datashare_log.h"
#include "parcel_macro.h"
namespace OHOS {
namespace DataShare {
using namespace AppExecFwk;
/**
* @brief A constructor used to create a DataShareResult instance
* with the input parameter count specified.
*/
DataShareResult::DataShareResult(int count) : uri_("")
{
count_ = count;
}
/**
* @brief A constructor used to create a DataShareResult instance
* with a Parcel object specified.
*/
DataShareResult::DataShareResult(Parcel &parcel) : uri_(""), count_(0)
{
ReadFromParcel(parcel);
}
/**
* @brief A constructor used to create a DataShareResult instance
* with the input parameter uri specified
*/
DataShareResult::DataShareResult(const Uri &uri) : uri_(uri.ToString()), count_(0)
{}
/**
* @brief A constructor used to create a DataShareResult instance
* with input parameters uri, count, and failure specified.
*/
DataShareResult::DataShareResult(const Uri &uri, int count) : uri_(uri.ToString())
{
count_ = count;
}
DataShareResult::~DataShareResult()
{}
/**
* @brief Obtains the Uri object corresponding to the operation.
* @return Obtains the Uri object corresponding to the operation.
*/
Uri DataShareResult::GetUri()
{
return uri_;
}
/**
* @brief Obtains the number of rows affected by the operation.
* @return Returns the number of rows affected by the operation.
*/
int DataShareResult::GetCount()
{
return count_;
}
/**
* @brief Creates a DataShareResult instance based on the given Parcel object.
* Used to transfer DataShareResult object using Parcel.
* @param parcel Indicates the Parcel object.
* @return Returns the DataShareResult object.
*/
DataShareResult *DataShareResult::CreateFromParcel(Parcel &parcel)
{
DataShareResult *dataShareResult = new (std::nothrow) DataShareResult(parcel);
if (dataShareResult == nullptr) {
LOG_ERROR("DataShareResult::CreateFromParcel dataShareResult is nullptr");
}
return dataShareResult;
}
/**
* @brief Prints out a string containing the class object information.
* @return Returns object information.
*/
std::string DataShareResult::ToString()
{
std::string stringBuilder = "DataShareResult(";
stringBuilder.append("uri=").append(uri_.ToString()).append(" ");
stringBuilder.append("count=").append(std::to_string(count_)).append(" ");
stringBuilder.erase(stringBuilder.length() - 1, 1);
stringBuilder.append(")");
return stringBuilder;
}
/**
* @brief Marshals a DataShareResult object into a Parcel.
* @param parcel Indicates the Parcel object for marshalling.
* @return Returns true if the marshalling is successful; returns false otherwise.
*/
bool DataShareResult::Marshalling(Parcel &parcel) const
{
// uri_
if (uri_.ToString().empty()) {
WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, VALUE_NULL);
} else {
if (!parcel.WriteInt32(VALUE_OBJECT)) {
return false;
}
if (!parcel.WriteParcelable(&uri_)) {
return false;
}
}
// count_
if (!parcel.WriteInt32(count_)) {
return false;
}
return true;
}
/**
* @brief Unmarshals a DataShareResult object from a Parcel.
* @param parcel Indicates the Parcel object for unmarshalling.
* @return Returns true if the unmarshalling is successful; returns false otherwise.
*/
DataShareResult *DataShareResult::Unmarshalling(Parcel &parcel)
{
DataShareResult *dataShareResult = new (std::nothrow) DataShareResult(0);
if (dataShareResult != nullptr) {
if (!dataShareResult->ReadFromParcel(parcel)) {
delete dataShareResult;
dataShareResult = nullptr;
}
}
return dataShareResult;
}
bool DataShareResult::ReadFromParcel(Parcel &parcel)
{
// uri_
int32_t empty = VALUE_NULL;
if (!parcel.ReadInt32(empty)) {
return false;
}
if (empty == VALUE_OBJECT) {
auto uri = parcel.ReadParcelable<Uri>();
if (uri != nullptr) {
uri_ = *uri;
delete uri;
uri = nullptr;
} else {
return false;
}
}
// count_
if (!parcel.ReadInt32(count_)) {
return false;
}
return true;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,426 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_result_set.h"
#include <securec.h>
#include <sstream>
#include "datashare_log.h"
#include "parcel.h"
#include "datashare_errno.h"
#include "shared_block.h"
#include "string_ex.h"
namespace OHOS {
namespace DataShare {
namespace {
// The default position of the cursor
static const int INITIAL_POS = -1;
static const size_t DEFAULT_SHARE_BLOCK_SIZE = 2 * 1024 * 1024;
// Equivalent to filling in setp + 1 rows each time
static const int STEP_LEN = 2;
} // namespace
int DataShareResultSet::blockId_ = 0;
DataShareResultSet::DataShareResultSet()
{
}
DataShareResultSet::DataShareResultSet(std::shared_ptr<ResultSetBridge> &bridge)
: bridge_(bridge)
{
std::string name = "DataShare" + std::to_string(blockId_++);
blockWriter_ = std::make_shared<DataShareBlockWriterImpl>(name, DEFAULT_SHARE_BLOCK_SIZE);
sharedBlock_ = blockWriter_->GetBlock();
}
DataShareResultSet::~DataShareResultSet()
{
ClosedBlock();
}
int DataShareResultSet::GetAllColumnNames(std::vector<std::string> &columnNames)
{
if (bridge_ == nullptr) {
LOG_ERROR("bridge_ is null!");
return E_ERROR;
}
return bridge_->GetAllColumnNames(columnNames);
}
int DataShareResultSet::GetRowCount(int &count)
{
if (bridge_ == nullptr) {
LOG_ERROR("bridge_ is null!");
return E_ERROR;
}
return bridge_->GetRowCount(count);
}
bool DataShareResultSet::OnGo(int startRowIndex, int targetRowIndex)
{
if (bridge_ == nullptr || blockWriter_ == nullptr) {
LOG_ERROR("bridge_ or blockWriter_ is null!");
return E_ERROR;
}
return bridge_->OnGo(startRowIndex, targetRowIndex, *blockWriter_);
}
void DataShareResultSet::FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block)
{
return;
}
/**
* Get current shared block
*/
AppDataFwk::SharedBlock *DataShareResultSet::GetBlock() const
{
return sharedBlock_;
}
int DataShareResultSet::GetDataType(int columnIndex, DataType &dataType)
{
AppDataFwk::SharedBlock::CellUnit *cellUnit =
sharedBlock_->GetCellUnit((uint32_t)rowPos_ - startRowPos_, (uint32_t)columnIndex);
if (!cellUnit) {
LOG_ERROR("DataShareResultSet::GetDataType cellUnit is null!");
return E_ERROR;
}
dataType = (DataType)cellUnit->type;
return E_OK;
}
int DataShareResultSet::GoToRow(int position)
{
if (sharedBlock_ == nullptr) {
LOG_ERROR("sharedBlock_ is null!");
return E_ERROR;
}
int rowCnt = 0;
GetRowCount(rowCnt);
if (position >= rowCnt) {
rowPos_ = rowCnt;
return E_ERROR;
}
if (position < 0) {
rowPos_ = INITIAL_POS;
return E_ERROR;
}
if (position == rowPos_) {
return E_OK;
}
bool result = true;
if (position > endRowPos_ || position < startRowPos_) {
result = OnGo(position, std::min(position + STEP_LEN, rowCnt - 1));
if (result) {
startRowPos_ = position;
endRowPos_ = position + static_cast<int>(sharedBlock_->GetRowNum()) -1;
}
}
if (!result) {
rowPos_ = INITIAL_POS;
startRowPos_ = INITIAL_POS;
endRowPos_ = INITIAL_POS;
return E_ERROR;
} else {
rowPos_ = position;
return E_OK;
}
}
int DataShareResultSet::GetBlob(int columnIndex, std::vector<uint8_t> &value)
{
int errorCode = CheckState(columnIndex);
if (errorCode != E_OK) {
return errorCode;
}
AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex);
if (!cellUnit) {
LOG_ERROR("DataShareResultSet::GetBlob cellUnit is null!");
return E_ERROR;
}
value.resize(0);
int type = cellUnit->type;
if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB
|| type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) {
size_t size;
const auto *blob = static_cast<const uint8_t *>(sharedBlock_->GetCellUnitValueBlob(cellUnit, &size));
if (size == 0 || blob == nullptr) {
LOG_WARN("blob data is empty!");
} else {
value.resize(size);
value.assign(blob, blob + size);
}
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) {
LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER!");
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) {
LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!");
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) {
LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT!");
return E_OK;
} else {
LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::nothing !");
return E_INVALID_OBJECT_TYPE;
}
}
int DataShareResultSet::GetString(int columnIndex, std::string &value)
{
int errorCode = CheckState(columnIndex);
if (errorCode != E_OK) {
return errorCode;
}
AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex);
if (!cellUnit) {
LOG_ERROR("DataShareResultSet::GetString cellUnit is null!");
return E_ERROR;
}
int type = cellUnit->type;
if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) {
size_t sizeIncludingNull;
const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull);
if ((sizeIncludingNull <= 1) || (tempValue == nullptr)) {
value = "";
return E_ERROR;
}
value = tempValue;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) {
int64_t tempValue = cellUnit->cell.longValue;
value = std::to_string(tempValue);
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) {
double tempValue = cellUnit->cell.doubleValue;
std::ostringstream os;
if (os << tempValue)
value = os.str();
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) {
LOG_ERROR("DataShareResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!");
return E_ERROR;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) {
LOG_ERROR("DataShareResultSet::AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!");
return E_ERROR;
} else {
LOG_ERROR("DataShareResultSet::GetString is failed!");
return E_ERROR;
}
}
int DataShareResultSet::GetInt(int columnIndex, int &value)
{
AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex);
if (!cellUnit) {
LOG_ERROR("DataShareResultSet::GetInt cellUnit is null!");
return E_ERROR;
}
value = (int)cellUnit->cell.longValue;
return E_OK;
}
int DataShareResultSet::GetLong(int columnIndex, int64_t &value)
{
int errorCode = CheckState(columnIndex);
if (errorCode != E_OK) {
return errorCode;
}
AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex);
if (!cellUnit) {
LOG_ERROR("DataShareResultSet::GetLong cellUnit is null!");
return E_ERROR;
}
int type = cellUnit->type;
if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) {
value = cellUnit->cell.longValue;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) {
size_t sizeIncludingNull;
const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull);
value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? long(strtoll(tempValue, nullptr, 0)) : 0L;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) {
value = (int64_t)cellUnit->cell.doubleValue;
LOG_ERROR("DataShareResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT !");
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) {
LOG_ERROR("DataShareResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL !");
value = 0L;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) {
LOG_ERROR("DataShareResultSet::GetLong AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB !");
value = 0L;
return E_OK;
} else {
LOG_ERROR("DataShareResultSet::GetLong Nothing !");
return E_INVALID_OBJECT_TYPE;
}
}
int DataShareResultSet::GetDouble(int columnIndex, double &value)
{
int errorCode = CheckState(columnIndex);
if (errorCode != E_OK) {
return errorCode;
}
AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex);
if (!cellUnit) {
LOG_ERROR("DataShareResultSet::GetDouble cellUnit is null!");
return E_ERROR;
}
int type = cellUnit->type;
if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) {
value = cellUnit->cell.doubleValue;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) {
size_t sizeIncludingNull;
const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull);
value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? strtod(tempValue, nullptr) : 0.0;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) {
value = cellUnit->cell.longValue;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) {
LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL!");
value = 0.0;
return E_OK;
} else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) {
LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB!");
value = 0.0;
return E_OK;
} else {
LOG_ERROR("DataShareResultSet::GetDouble AppDataFwk::SharedBlock::nothing !");
value = 0.0;
return E_INVALID_OBJECT_TYPE;
}
}
int DataShareResultSet::IsColumnNull(int columnIndex, bool &isNull)
{
int errorCode = CheckState(columnIndex);
if (errorCode != E_OK) {
return errorCode;
}
AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex);
if (!cellUnit) {
LOG_ERROR("DataShareResultSet::IsColumnNull cellUnit is null!");
return E_ERROR;
}
if (cellUnit->type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) {
isNull = true;
return E_OK;
}
isNull = false;
return E_OK;
}
int DataShareResultSet::Close()
{
DataShareAbsResultSet::Close();
ClosedBlock();
return E_OK;
}
/**
* Allocates a new shared block to an {@link DataShareResultSet}
*/
void DataShareResultSet::SetBlock(AppDataFwk::SharedBlock *block)
{
if (sharedBlock_ != block) {
ClosedBlock();
sharedBlock_ = block;
}
}
/**
* Checks whether an {@code DataShareResultSet} object contains shared blocks
*/
bool DataShareResultSet::HasBlock() const
{
return sharedBlock_ != nullptr;
}
/**
* Closes a shared block that is not empty in this {@code DataShareResultSet} object
*/
void DataShareResultSet::ClosedBlock()
{
delete sharedBlock_;
sharedBlock_ = nullptr;
}
void DataShareResultSet::ClearBlock()
{
if (sharedBlock_ != nullptr) {
sharedBlock_->Clear();
}
}
void DataShareResultSet::Finalize()
{
Close();
}
/**
* Check current status
*/
int DataShareResultSet::CheckState(int columnIndex)
{
if (sharedBlock_ == nullptr) {
LOG_ERROR("DataShareResultSet::CheckState sharedBlock is null!");
return E_ERROR;
}
int cnt = 0;
GetColumnCount(cnt);
if (columnIndex >= cnt || columnIndex < 0) {
return E_INVALID_COLUMN_INDEX;
}
int rowCnt = 0;
GetRowCount(rowCnt);
if (rowPos_ < 0 || rowPos_ >= rowCnt) {
return E_INVALID_STATEMENT;
}
return E_OK;
}
bool DataShareResultSet::Marshalling(MessageParcel &parcel)
{
if (sharedBlock_ == nullptr) {
LOG_ERROR("DataShareResultSet::Marshalling sharedBlock is null.");
return false;
}
LOG_DEBUG("DataShareResultSet::Marshalling sharedBlock.");
return sharedBlock_->WriteMessageParcel(parcel);
}
bool DataShareResultSet::Unmarshalling(MessageParcel &parcel)
{
if (sharedBlock_ != nullptr) {
return false;
}
int result = AppDataFwk::SharedBlock::ReadMessageParcel(parcel, sharedBlock_);
if (result < 0) {
LOG_ERROR("DataShareResultSet: create from parcel error is %{public}d.", result);
}
return true;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,51 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_string_utils.h"
namespace OHOS {
namespace DataShare {
std::string DataShareStringUtils::SurroundWithQuote(std::string value, std::string quote)
{
if (value.empty()) {
return value;
}
std::string str = quote + value + quote;
return str;
}
// Join array members as parameters of a function call.
std::string DataShareStringUtils::SurroundWithFunction(std::string function, std::string separator,
std::vector<std::string> array)
{
std::string builder(function);
builder += "(";
bool isFirst = true;
for (auto text : array) {
if (!isFirst) {
builder = builder + " " + separator + " ";
} else {
isFirst = false;
}
builder += text;
}
builder += ")";
return builder;
}
DataShareStringUtils::DataShareStringUtils() {}
DataShareStringUtils::~DataShareStringUtils() {}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,167 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_value_object.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DataShare {
DataShareValueObjectType DataShareValueObject::GetType() const
{
return type;
}
int DataShareValueObject::GetInt(int &val) const
{
if (type != DataShareValueObjectType::TYPE_INT) {
return E_INVALID_OBJECT_TYPE;
}
int64_t v = std::get<int64_t>(value);
val = static_cast<int>(v);
return E_OK;
}
int DataShareValueObject::GetLong(int64_t &val) const
{
if (type != DataShareValueObjectType::TYPE_INT) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<int64_t>(value);
return E_OK;
}
int DataShareValueObject::GetDouble(double &val) const
{
if (type != DataShareValueObjectType::TYPE_DOUBLE) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<double>(value);
return E_OK;
}
int DataShareValueObject::GetBool(bool &val) const
{
if (type != DataShareValueObjectType::TYPE_BOOL) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<bool>(value);
return E_OK;
}
int DataShareValueObject::GetString(std::string &val) const
{
if (type != DataShareValueObjectType::TYPE_STRING) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<std::string>(value);
return E_OK;
}
int DataShareValueObject::GetBlob(std::vector<uint8_t> &val) const
{
if (type != DataShareValueObjectType::TYPE_BLOB) {
return E_INVALID_OBJECT_TYPE;
}
val = std::get<std::vector<uint8_t>>(value);
return E_OK;
}
bool DataShareValueObject::Marshalling(const DataShareValueObject &valueObject, Parcel &parcel)
{
switch (valueObject.type) {
case DataShareValueObjectType::TYPE_NULL: {
parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_NULL);
break;
}
case DataShareValueObjectType::TYPE_INT: {
parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_INT);
parcel.WriteInt64(std::get<int64_t>(valueObject.value));
break;
}
case DataShareValueObjectType::TYPE_DOUBLE: {
parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_DOUBLE);
parcel.WriteDouble(std::get<double>(valueObject.value));
break;
}
case DataShareValueObjectType::TYPE_STRING: {
parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_STRING);
parcel.WriteString(std::get<std::string>(valueObject.value));
break;
}
case DataShareValueObjectType::TYPE_BLOB: {
parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_BLOB);
parcel.WriteUInt8Vector(std::get<std::vector<uint8_t>>(valueObject.value));
break;
}
case DataShareValueObjectType::TYPE_BOOL: {
parcel.WriteInt16((int16_t) DataShareValueObjectType::TYPE_BOOL);
parcel.WriteBool(std::get<bool>(valueObject.value));
break;
}
default:
break;
}
return true;
}
DataShareValueObject *DataShareValueObject::Unmarshalling(Parcel &parcel)
{
auto *pValueObject = new DataShareValueObject();
switch (parcel.ReadInt16()) {
case (int16_t)DataShareValueObjectType::TYPE_NULL: {
pValueObject->type = DataShareValueObjectType::TYPE_NULL;
break;
}
case (int16_t)DataShareValueObjectType::TYPE_INT: {
pValueObject->type = DataShareValueObjectType::TYPE_INT;
pValueObject->value = parcel.ReadInt64();
break;
}
case (int16_t)DataShareValueObjectType::TYPE_DOUBLE: {
pValueObject->type = DataShareValueObjectType::TYPE_DOUBLE;
pValueObject->value = parcel.ReadDouble();
break;
}
case (int16_t)DataShareValueObjectType::TYPE_STRING: {
pValueObject->type = DataShareValueObjectType::TYPE_STRING;
pValueObject->value = parcel.ReadString();
break;
}
case (int16_t)DataShareValueObjectType::TYPE_BLOB: {
pValueObject->type = DataShareValueObjectType::TYPE_BLOB;
std::vector<uint8_t> val;
parcel.ReadUInt8Vector(&val);
pValueObject->value = val;
break;
}
case (int16_t)DataShareValueObjectType::TYPE_BOOL: {
pValueObject->type = DataShareValueObjectType::TYPE_BOOL;
pValueObject->value = parcel.ReadBool();
break;
}
default:
break;
}
return pValueObject;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,123 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_values_bucket.h"
#include "datashare_value_object.h"
namespace OHOS {
namespace DataShare {
void DataShareValuesBucket::PutString(const std::string &columnName, const std::string &value)
{
valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value)));
}
void DataShareValuesBucket::PutInt(const std::string &columnName, int value)
{
valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value)));
}
void DataShareValuesBucket::PutLong(const std::string &columnName, int64_t value)
{
valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value)));
}
void DataShareValuesBucket::PutDouble(const std::string &columnName, double value)
{
valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value)));
}
void DataShareValuesBucket::PutBool(const std::string &columnName, bool value)
{
valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value)));
}
void DataShareValuesBucket::PutBlob(const std::string &columnName, const std::vector<uint8_t> &value)
{
valuesMap.insert(std::make_pair(columnName, DataShareValueObject(value)));
}
void DataShareValuesBucket::PutNull(const std::string &columnName)
{
valuesMap.insert(std::make_pair(columnName, DataShareValueObject()));
}
void DataShareValuesBucket::Delete(const std::string &columnName)
{
valuesMap.erase(columnName);
}
void DataShareValuesBucket::Clear()
{
valuesMap.clear();
}
int DataShareValuesBucket::Size() const
{
return valuesMap.size();
}
bool DataShareValuesBucket::IsEmpty() const
{
return valuesMap.empty();
}
bool DataShareValuesBucket::HasColumn(const std::string &columnName) const
{
auto iter = valuesMap.find(columnName);
if (iter == valuesMap.end()) {
return false;
}
return true;
}
bool DataShareValuesBucket::GetObject(const std::string &columnName, DataShareValueObject &value) const
{
auto iter = valuesMap.find(columnName);
if (iter == valuesMap.end()) {
return false;
}
value = iter->second;
return true;
}
void DataShareValuesBucket::GetAll(std::map<std::string, DataShareValueObject> &outValuesMap) const
{
outValuesMap = valuesMap;
}
bool DataShareValuesBucket::Marshalling(const DataShareValuesBucket &valuesBucket, Parcel &parcel)
{
parcel.WriteInt32(valuesBucket.valuesMap.size());
for (auto &it : valuesBucket.valuesMap) {
parcel.WriteString(it.first);
DataShareValueObject::Marshalling(it.second, parcel);
}
return true;
}
DataShareValuesBucket *DataShareValuesBucket::Unmarshalling(Parcel &parcel)
{
int mapSize = parcel.ReadInt32();
std::map<std::string, DataShareValueObject> valuesMap;
for (int i = 0; i < mapSize; i++) {
std::string key = parcel.ReadString();
DataShareValueObject *value = DataShareValueObject::Unmarshalling(parcel);
valuesMap.insert(std::make_pair(key, *value));
delete value;
}
return new DataShareValuesBucket(valuesMap);
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,29 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ishared_result_set.h"
namespace OHOS::DataShare {
std::shared_ptr<DataShareResultSet> ISharedResultSet::ReadFromParcel(MessageParcel &parcel)
{
return consumerCreator_(parcel);
}
sptr<ISharedResultSet> ISharedResultSet::WriteToParcel(std::shared_ptr<DataShareResultSet> resultSet,
MessageParcel &parcel)
{
return providerCreator_(std::move(resultSet), parcel);
}
} // namespace OHOS::DataShare

View File

@ -1,128 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ishared_result_set_proxy.h"
#include "datashare_errno.h"
#include "iremote_proxy.h"
#include "datashare_log.h"
namespace OHOS::DataShare {
std::function<std::shared_ptr<DataShareResultSet>(
MessageParcel &parcel)> ISharedResultSet::consumerCreator_ = ISharedResultSetProxy::CreateProxy;
BrokerDelegator<ISharedResultSetProxy> ISharedResultSetProxy::delegator_;
ISharedResultSetProxy::ISharedResultSetProxy(const sptr<OHOS::IRemoteObject> &impl)
: IRemoteProxy<ISharedResultSet>(impl)
{
}
std::shared_ptr<DataShareResultSet> ISharedResultSetProxy::CreateProxy(MessageParcel &parcel)
{
sptr<IRemoteObject> remoter = parcel.ReadRemoteObject();
if (remoter == nullptr) {
return nullptr;
}
sptr<ISharedResultSet> result = iface_cast<ISharedResultSet>(remoter);
result->Unmarshalling(parcel);
return std::shared_ptr<DataShareResultSet>(result.GetRefPtr(),
[keep = result] (DataShareResultSet *) {});
}
int ISharedResultSetProxy::GetAllColumnNames(std::vector<std::string> &columnNames)
{
LOG_DEBUG("GetAllColumnNames Begin");
if (!columnNames_.empty()) {
columnNames = columnNames_;
return E_OK;
}
MessageParcel request;
request.WriteInterfaceToken(GetDescriptor());
MessageParcel reply;
MessageOption msgOption;
int errCode = Remote()->SendRequest(FUNC_GET_ALL_COLUMN_NAMES, request, reply, msgOption);
if (errCode != 0) {
LOG_ERROR("GetAllColumnNames IPC Error %{public}x", errCode);
return -errCode;
}
errCode = reply.ReadInt32();
if (errCode != E_OK) {
LOG_ERROR("GetAllColumnNames Reply Error %{public}d", errCode);
return errCode;
}
if (!reply.ReadStringVector(&columnNames)) {
return E_INVALID_PARCEL;
}
columnNames_ = columnNames;
return E_OK;
}
int ISharedResultSetProxy::GetRowCount(int &count)
{
LOG_DEBUG("GetRowCount Begin");
if (rowCount_ >= 0) {
count = rowCount_;
return E_OK;
}
MessageParcel request;
request.WriteInterfaceToken(GetDescriptor());
MessageParcel reply;
MessageOption msgOption;
int errCode = Remote()->SendRequest(FUNC_GET_ROW_COUNT, request, reply, msgOption);
if (errCode != 0) {
LOG_ERROR("GetRowCount IPC Error %{public}x", errCode);
return -errCode;
}
errCode = reply.ReadInt32();
if (errCode != E_OK) {
LOG_ERROR("GetRowCount Reply Error %{public}d", errCode);
return errCode;
}
count = reply.ReadInt32();
LOG_DEBUG("GetRowCount count %{public}d", count);
rowCount_ = count;
return E_OK;
}
bool ISharedResultSetProxy::OnGo(int oldRowIndex, int newRowIndex)
{
LOG_DEBUG("OnGo Begin");
MessageParcel request;
request.WriteInterfaceToken(GetDescriptor());
request.WriteInt32(oldRowIndex);
request.WriteInt32(newRowIndex);
MessageParcel reply;
MessageOption msgOption;
int errCode = Remote()->SendRequest(FUNC_ON_GO, request, reply, msgOption);
if (errCode != 0) {
LOG_ERROR("OnGo IPC Error %{public}x", errCode);
return -errCode;
}
return reply.ReadBool();
}
int ISharedResultSetProxy::Close()
{
LOG_DEBUG("Close Begin");
DataShareResultSet::Close();
MessageParcel request;
request.WriteInterfaceToken(GetDescriptor());
MessageParcel reply;
MessageOption msgOption;
int errCode = Remote()->SendRequest(FUNC_CLOSE, request, reply, msgOption);
if (errCode != 0) {
LOG_ERROR("Close IPC Error %{public}x", errCode);
return -errCode;
}
return reply.ReadInt32();
}
} // namespace OHOS::DataShare

View File

@ -1,142 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ishared_result_set_stub.h"
#include <future>
#include "datashare_log.h"
#include "datashare_errno.h"
namespace OHOS::DataShare {
std::function<sptr<ISharedResultSet>(std::shared_ptr<DataShareResultSet>,
MessageParcel &)> ISharedResultSet::providerCreator_ = ISharedResultSetStub::CreateStub;
constexpr ISharedResultSetStub::Handler ISharedResultSetStub::handlers[ISharedResultSet::FUNC_BUTT];
sptr<ISharedResultSet> ISharedResultSetStub::CreateStub(std::shared_ptr<DataShareResultSet> result,
OHOS::MessageParcel &parcel)
{
sptr<ISharedResultSet> stub = new ISharedResultSetStub(result);
parcel.WriteRemoteObject(stub->AsObject().GetRefPtr());
result->Marshalling(parcel);
return stub;
}
ISharedResultSetStub::ISharedResultSetStub(std::shared_ptr<DataShareResultSet> resultSet)
: resultSet_(std::move(resultSet)),
runnables_(MAX_RUNNABLE),
thread_(&ISharedResultSetStub::Run, this)
{
thread_.detach();
LOG_ERROR("ISharedResultSetStub start thread(%{public}" PRIx64 ")", uint64_t(thread_.native_handle()));
}
ISharedResultSetStub::~ISharedResultSetStub()
{
auto handle = thread_.native_handle();
isRunning_ = false;
// do not delete this code, this code is waiting the thread exit.
isRunning_ = Submit([this]() -> bool { return isRunning_;}).get();
LOG_ERROR("~ISharedResultSetStub thread(%{public}" PRIx64 ")", uint64_t(handle));
}
int ISharedResultSetStub::OnRemoteRequest(uint32_t code, OHOS::MessageParcel &data,
OHOS::MessageParcel &reply, OHOS::MessageOption &option)
{
if (GetDescriptor() != data.ReadInterfaceToken()) {
LOG_ERROR("IPC descriptor is not equal");
return INVALID_FD;
}
if (code >= FUNC_BUTT) {
LOG_ERROR("OnRemoteRequest method code(%{public}d) out of range", code);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
Handler handler = handlers[code];
if (handler == nullptr) {
LOG_ERROR("OnRemoteRequest method code(%{public}d) is not support", code);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
auto future = Submit([this, &data, &reply, handler]() -> int {
return (this->*handler)(data, reply);
});
return future.get();
}
int ISharedResultSetStub::HandleGetRowCountRequest(MessageParcel &data, MessageParcel &reply)
{
int count = -1;
int errCode = resultSet_->GetRowCount(count);
reply.WriteInt32(errCode);
if (errCode == E_OK) {
reply.WriteInt32(count);
}
LOG_DEBUG("HandleGetRowCountRequest call %{public}d", errCode);
return NO_ERROR;
}
int ISharedResultSetStub::HandleGetAllColumnNamesRequest(MessageParcel &data, MessageParcel &reply)
{
std::vector<std::string> names;
int errCode = resultSet_->GetAllColumnNames(names);
reply.WriteInt32(errCode);
if (errCode == E_OK) {
reply.WriteStringVector(names);
}
LOG_DEBUG("HandleGetAllColumnNamesRequest call %{public}d", errCode);
return NO_ERROR;
}
int ISharedResultSetStub::HandleOnGoRequest(MessageParcel &data, MessageParcel &reply)
{
int oldRow = data.ReadInt32();
int newRow = data.ReadInt32();
std::vector<std::string> columnNames;
resultSet_->GetAllColumnNames(columnNames);
auto block = resultSet_->GetBlock();
int errCode = block->Clear();
if (errCode != E_OK) {
reply.WriteInt32(errCode);
return NO_ERROR;
}
errCode = block->SetColumnNum(columnNames.size());
if (errCode == E_OK) {
errCode = resultSet_->OnGo(oldRow, newRow);
}
reply.WriteInt32(errCode);
LOG_DEBUG("HandleOnGoRequest call %{public}d", errCode);
return NO_ERROR;
}
int ISharedResultSetStub::HandleCloseRequest(MessageParcel &data, MessageParcel &reply)
{
int errCode = resultSet_->Close();
reply.WriteInt32(errCode);
LOG_DEBUG("HandleCloseRequest call %{public}d", errCode);
return NO_ERROR;
}
void ISharedResultSetStub::Run()
{
auto handle = thread_.native_handle();
bool isRunning = true;
while (isRunning) {
auto runnable = runnables_.Pop();
if (runnable == nullptr) {
continue;
}
isRunning = runnable();
}
LOG_ERROR("ISharedResultSetStub thread(%{public}" PRIx64 ") is exited", uint64_t(handle));
}
} // namespace OHOS::DataShare

View File

@ -1,95 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_CONNECTION_H
#define DATASHARE_CONNECTION_H
#include <memory>
#include "ability_connect_callback_stub.h"
#include "event_handler.h"
#include "idatashare.h"
#include "want.h"
namespace OHOS {
namespace DataShare {
using namespace AppExecFwk;
class DataShareConnection : public AAFwk::AbilityConnectionStub {
public:
DataShareConnection(const Uri &uri) : uri_(uri) {}
virtual ~DataShareConnection() = default;
/**
* @brief This method is called back to receive the connection result after an ability calls the
* ConnectAbility method to connect it to an extension ability.
*
* @param element: Indicates information about the connected extension ability.
* @param remote: Indicates the remote proxy object of the extension ability.
* @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any
* other value indicates a connection failure.
*/
void OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode) override;
/**
* @brief This method is called back to receive the disconnection result after the connected extension ability
* crashes or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and
* each ability previously connected to it will call onAbilityDisconnectDone.
*
* @param element: Indicates information about the disconnected extension ability.
* @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection,
* and any other value indicates a disconnection failure.
*/
void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override;
/**
* @brief connect remote ability of DataShareExtAbility.
*/
void ConnectDataShareExtAbility(const Uri &uri, const sptr<IRemoteObject> &token);
/**
* @brief disconnect remote ability of DataShareExtAbility.
*/
void DisconnectDataShareExtAbility();
/**
* @brief check whether connected to remote extension ability.
*
* @return bool true if connected, otherwise false.
*/
bool IsExtAbilityConnected();
/**
* @brief get the proxy of datashare extension ability.
*
* @return the proxy of datashare extension ability.
*/
sptr<IDataShare> GetDataShareProxy();
struct ConnectCondition {
std::condition_variable condition;
std::mutex mutex;
};
private:
static sptr<DataShareConnection> instance_;
static std::mutex mutex_;
std::atomic<bool> isConnected_ = {false};
sptr<IDataShare> dataShareProxy_;
ConnectCondition condition_;
Uri uri_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_CONNECTION_H

View File

@ -1,69 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_PROXY_H
#define DATASHARE_PROXY_H
#include <iremote_proxy.h>
#include "idatashare.h"
namespace OHOS {
namespace DataShare {
class DataShareProxy : public IRemoteProxy<IDataShare> {
public:
explicit DataShareProxy(const sptr<IRemoteObject>& remote) : IRemoteProxy<IDataShare>(remote) {}
virtual ~DataShareProxy() {}
virtual std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override;
virtual int OpenFile(const Uri &uri, const std::string &mode) override;
virtual int OpenRawFile(const Uri &uri, const std::string &mode) override;
virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) override;
virtual int Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value) override;
virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) override;
virtual std::shared_ptr<DataShareResultSet> Query(const Uri &uri,
const DataSharePredicates &predicates, std::vector<std::string> &columns) override;
virtual std::string GetType(const Uri &uri) override;
virtual int BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values) override;
virtual bool RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
virtual bool UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
virtual bool NotifyChange(const Uri &uri) override;
virtual Uri NormalizeUri(const Uri &uri) override;
virtual Uri DenormalizeUri(const Uri &uri) override;
virtual std::vector<std::shared_ptr<DataShareResult>> ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations) override;
private:
static inline BrokerDelegator<DataShareProxy> delegator_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_PROXY_H

View File

@ -1,118 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_connection.h"
#include "ability_manager_client.h"
#include "datashare_proxy.h"
#include "datashare_log.h"
namespace OHOS {
namespace DataShare {
using namespace AppExecFwk;
constexpr int WAIT_TIME = 1;
sptr<DataShareConnection> DataShareConnection::instance_ = nullptr;
std::mutex DataShareConnection::mutex_;
/**
* @brief This method is called back to receive the connection result after an ability calls the
* ConnectAbility method to connect it to an extension ability.
*
* @param element: Indicates information about the connected extension ability.
* @param remote: Indicates the remote proxy object of the extension ability.
* @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any
* other value indicates a connection failure.
*/
void DataShareConnection::OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode)
{
LOG_INFO("called begin");
if (remoteObject == nullptr) {
LOG_ERROR("DataShareConnection::OnAbilityConnectDone failed, remote is nullptr");
return;
}
dataShareProxy_ = iface_cast<DataShareProxy>(remoteObject);
std::unique_lock<std::mutex> lock(condition_.mutex);
condition_.condition.notify_all();
if (dataShareProxy_ == nullptr) {
LOG_ERROR("DataShareConnection::OnAbilityConnectDone failed, dataShareProxy_ is nullptr");
return;
}
isConnected_.store(true);
LOG_INFO("called end");
}
/**
* @brief This method is called back to receive the disconnection result after the connected extension ability crashes
* or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and each ability
* previously connected to it will call onAbilityDisconnectDone.
*
* @param element: Indicates information about the disconnected extension ability.
* @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, and
* any other value indicates a disconnection failure.
*/
void DataShareConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode)
{
LOG_INFO("called begin");
dataShareProxy_ = nullptr;
isConnected_.store(false);
LOG_INFO("called end");
}
/**
* @brief connect remote ability of DataShareExtAbility.
*/
void DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr<IRemoteObject> &token)
{
LOG_INFO("called begin");
std::unique_lock<std::mutex> lock(condition_.mutex);
AAFwk::Want want;
want.SetUri(uri);
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, this, token);
if (condition_.condition.wait_for(lock, std::chrono::seconds(WAIT_TIME),
[this] { return dataShareProxy_ != nullptr; })) {
LOG_INFO("Wait connect timeout.");
}
LOG_INFO("called end, ret=%{public}d", ret);
}
/**
* @brief disconnect remote ability of DataShareExtAbility.
*/
void DataShareConnection::DisconnectDataShareExtAbility()
{
LOG_INFO("called begin");
dataShareProxy_ = nullptr;
isConnected_.store(false);
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(this);
LOG_INFO("called end, ret=%{public}d", ret);
}
/**
* @brief check whether connected to remote extension ability.
*
* @return bool true if connected, otherwise false.
*/
bool DataShareConnection::IsExtAbilityConnected()
{
return isConnected_.load();
}
sptr<IDataShare> DataShareConnection::GetDataShareProxy()
{
return dataShareProxy_;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,826 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_helper.h"
#include "datashare_result_set.h"
#include "data_ability_observer_interface.h"
#include "datashare_log.h"
#include "idatashare.h"
namespace OHOS {
namespace DataShare {
using namespace AppExecFwk;
namespace {
const std::string SCHEME_DATASHARE = "datashare";
constexpr int INVALID_VALUE = -1;
} // namespace
std::mutex DataShareHelper::oplock_;
DataShareHelper::DataShareHelper(const sptr<IRemoteObject> &token,
const Uri &uri, const sptr<IDataShare> &dataShareProxy, sptr<DataShareConnection> dataShareConnection)
{
LOG_INFO("DataShareHelper::DataShareHelper start");
token_ = token;
uri_ = uri;
dataShareProxy_ = dataShareProxy;
dataShareConnection_ = dataShareConnection;
LOG_INFO("DataShareHelper::DataShareHelper end");
}
DataShareHelper::~DataShareHelper()
{
if (callerDeathRecipient_ != nullptr) {
dataShareProxy_->AsObject()->RemoveDeathRecipient(callerDeathRecipient_);
callerDeathRecipient_ = nullptr;
}
}
void DataShareHelper::AddDataShareDeathRecipient(const sptr<IRemoteObject> &token)
{
LOG_INFO("DataShareHelper::AddDataShareDeathRecipient start.");
if (token == nullptr) {
LOG_INFO("token is nullptr");
return;
}
if (callerDeathRecipient_ != nullptr) {
LOG_INFO("exist callerDeathRecipient_.");
return;
}
LOG_INFO("token AddDeathRecipient.");
callerDeathRecipient_ =
new DataShareDeathRecipient(std::bind(&DataShareHelper::OnSchedulerDied, this, std::placeholders::_1));
token->AddDeathRecipient(callerDeathRecipient_);
LOG_INFO("DataShareHelper::AddDataShareDeathRecipient end.");
}
void DataShareHelper::OnSchedulerDied(const wptr<IRemoteObject> &remote)
{
LOG_INFO("start.");
if (callerDeathRecipient_ != nullptr) {
dataShareProxy_->AsObject()->RemoveDeathRecipient(callerDeathRecipient_);
callerDeathRecipient_ = nullptr;
}
dataShareProxy_ = nullptr;
dataShareConnection_->ConnectDataShareExtAbility(uri_, token_);
LOG_INFO("DataShareHelper::OnSchedulerDied end.");
}
/**
* @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
* between the ability using the Data template (data share for short) and the associated client process in
* a DataShareHelper instance.
*
* @param context Indicates the Context object on OHOS.
* @param strUri Indicates the database table or disk file to operate.
*
* @return Returns the created DataShareHelper instance.
*/
std::shared_ptr<DataShareHelper> DataShareHelper::Creator(
const std::shared_ptr<Context> &context, const std::string &strUri)
{
LOG_INFO("DataShareHelper::Creator with context and uri called start.");
if (context == nullptr) {
LOG_ERROR("DataShareHelper::Creator failed, context == nullptr");
return nullptr;
}
sptr<IRemoteObject> token = context->GetToken();
return Creator(token, strUri);
}
/**
* @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
* between the ability using the Data template (data share for short) and the associated client process in
* a DataShareHelper instance.
*
* @param context Indicates the Context object on OHOS.
* @param strUri Indicates the database table or disk file to operate.
*
* @return Returns the created DataShareHelper instance.
*/
std::shared_ptr<DataShareHelper> DataShareHelper::Creator(
const std::shared_ptr<OHOS::AbilityRuntime::Context> &context, const std::string &strUri)
{
LOG_INFO("DataShareHelper::Creator with runtime context and uri called start.");
if (context == nullptr) {
LOG_ERROR("DataShareHelper::Creator failed, context == nullptr");
return nullptr;
}
sptr<IRemoteObject> token = context->GetToken();
return Creator(token, strUri);
}
/**
* @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
* between the ability using the Data template (data share for short) and the associated client process in
* a DataShareHelper instance.
*
* @param token Indicates the System token.
* @param strUri Indicates the database table or disk file to operate.
*
* @return Returns the created DataShareHelper instance.
*/
std::shared_ptr<DataShareHelper> DataShareHelper::Creator(const sptr<IRemoteObject> &token, const std::string &strUri)
{
LOG_INFO("DataShareHelper::Creator with runtime token and uri called start.");
if (token == nullptr) {
LOG_ERROR("DataShareHelper::Creator failed, token == nullptr");
return nullptr;
}
Uri uri(strUri);
if (uri.GetScheme() != SCHEME_DATASHARE) {
LOG_ERROR("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s",
uri.GetScheme().c_str());
return nullptr;
}
LOG_INFO("DataShareHelper::Creator before ConnectDataShareExtAbility.");
sptr<DataShareConnection> dataShareConnection = new (std::nothrow) DataShareConnection(uri);
if (!dataShareConnection->IsExtAbilityConnected()) {
dataShareConnection->ConnectDataShareExtAbility(uri, token);
}
sptr<IDataShare> dataShareProxy = dataShareConnection->GetDataShareProxy();
if (dataShareProxy == nullptr) {
LOG_ERROR("DataShareHelper::Creator get invalid dataShareProxy");
if (dataShareConnection->IsExtAbilityConnected()) {
dataShareConnection->DisconnectDataShareExtAbility();
}
return nullptr;
}
LOG_INFO("DataShareHelper::Creator after ConnectDataShareExtAbility.");
DataShareHelper *ptrDataShareHelper =
new (std::nothrow) DataShareHelper(token, uri, dataShareProxy, dataShareConnection);
if (ptrDataShareHelper == nullptr) {
LOG_ERROR("DataShareHelper::Creator failed, create DataShareHelper failed");
if (dataShareConnection->IsExtAbilityConnected()) {
dataShareConnection->DisconnectDataShareExtAbility();
}
return nullptr;
}
LOG_INFO("DataShareHelper::Creator out.");
return std::shared_ptr<DataShareHelper>(ptrDataShareHelper);
}
/**
* @brief Releases the client resource of the data share.
* You should call this method to releases client resource after the data operations are complete.
*
* @return Returns true if the resource is successfully released; returns false otherwise.
*/
bool DataShareHelper::Release()
{
LOG_INFO("DataShareHelper::Release start.");
LOG_INFO("DataShareHelper::Release before DisconnectDataShareExtAbility.");
if (dataShareConnection_->IsExtAbilityConnected()) {
dataShareConnection_->DisconnectDataShareExtAbility();
}
LOG_INFO("DataShareHelper::Release after DisconnectDataShareExtAbility.");
dataShareProxy_ = nullptr;
dataShareConnection_ = nullptr;
uri_ = Uri("");
LOG_INFO("DataShareHelper::Release end.");
return true;
}
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> DataShareHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter)
{
LOG_INFO("DataShareHelper::GetFileTypes start.");
std::vector<std::string> matchedMIMEs;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return matchedMIMEs;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return matchedMIMEs;
}
LOG_INFO("DataShareHelper::GetFileTypes before dataShareProxy_->GetFileTypes.");
matchedMIMEs = dataShareProxy_->GetFileTypes(uri, mimeTypeFilter);
LOG_INFO("DataShareHelper::GetFileTypes after dataShareProxy_->GetFileTypes.");
LOG_INFO("DataShareHelper::GetFileTypes end.");
return matchedMIMEs;
}
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int DataShareHelper::OpenFile(Uri &uri, const std::string &mode)
{
LOG_INFO("DataShareHelper::OpenFile start.");
int fd = INVALID_VALUE;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return fd;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return fd;
}
LOG_INFO("DataShareHelper::OpenFile before dataShareProxy_->OpenFile.");
fd = dataShareProxy_->OpenFile(uri, mode);
LOG_INFO("DataShareHelper::OpenFile after dataShareProxy_->OpenFile.");
LOG_INFO("DataShareHelper::OpenFile end.");
return fd;
}
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode)
{
LOG_INFO("DataShareHelper::OpenRawFile start.");
int fd = INVALID_VALUE;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return fd;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return fd;
}
LOG_INFO("DataShareHelper::OpenRawFile before dataShareProxy_->OpenRawFile.");
fd = dataShareProxy_->OpenRawFile(uri, mode);
LOG_INFO("DataShareHelper::OpenRawFile after dataShareProxy_->OpenRawFile.");
LOG_INFO("DataShareHelper::OpenRawFile end.");
return fd;
}
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int DataShareHelper::Insert(Uri &uri, const DataShareValuesBucket &value)
{
LOG_INFO("DataShareHelper::Insert start.");
int index = INVALID_VALUE;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return index;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return index;
}
LOG_INFO("DataShareHelper::Insert before dataShareProxy_->Insert.");
index = dataShareProxy_->Insert(uri, value);
LOG_INFO("DataShareHelper::Insert after dataShareProxy_->Insert.");
LOG_INFO("DataShareHelper::Insert end.");
return index;
}
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param value Indicates the data to update. This parameter can be null.
*
* @return Returns the number of data records updated.
*/
int DataShareHelper::Update(
Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value)
{
LOG_INFO("DataShareHelper::Update start.");
int index = INVALID_VALUE;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return index;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return index;
}
LOG_INFO("DataShareHelper::Update before dataShareProxy_->Update.");
index = dataShareProxy_->Update(uri, predicates, value);
LOG_INFO("DataShareHelper::Update after dataShareProxy_->Update.");
LOG_INFO("DataShareHelper::Update end.");
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int DataShareHelper::Delete(Uri &uri, const DataSharePredicates &predicates)
{
LOG_INFO("DataShareHelper::Delete start.");
int index = INVALID_VALUE;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return index;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return index;
}
LOG_INFO("DataShareHelper::Delete before dataShareProxy_->Delete.");
index = dataShareProxy_->Delete(uri, predicates);
LOG_INFO("DataShareHelper::Delete after dataShareProxy_->Delete.");
LOG_INFO("DataShareHelper::Delete end.");
return index;
}
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
*
* @return Returns the query result.
*/
std::shared_ptr<DataShareResultSet> DataShareHelper::Query(
Uri &uri, const DataSharePredicates &predicates, std::vector<std::string> &columns)
{
LOG_INFO("DataShareHelper::Query start.");
std::shared_ptr<DataShareResultSet> resultset = nullptr;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return resultset;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return resultset;
}
LOG_INFO("DataShareHelper::Query before dataShareProxy_->Query.");
resultset = dataShareProxy_->Query(uri, predicates, columns);
LOG_INFO("DataShareHelper::Query after dataShareProxy_->Query.");
LOG_INFO("DataShareHelper::Query end.");
return resultset;
}
/**
* @brief Obtains the MIME type matching the data specified by the URI of the data share. This method should be
* implemented by a data share. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string DataShareHelper::GetType(Uri &uri)
{
LOG_INFO("DataShareHelper::GetType start.");
std::string type;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return type;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return type;
}
LOG_INFO("DataShareHelper::GetType before dataShareProxy_->GetType.");
type = dataShareProxy_->GetType(uri);
LOG_INFO("DataShareHelper::GetType after dataShareProxy_->GetType.");
LOG_INFO("DataShareHelper::GetType end.");
return type;
}
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int DataShareHelper::BatchInsert(Uri &uri, const std::vector<DataShareValuesBucket> &values)
{
LOG_INFO("DataShareHelper::BatchInsert start.");
int ret = INVALID_VALUE;
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return ret;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return ret;
}
LOG_INFO("DataShareHelper::BatchInsert before dataShareProxy_->BatchInsert.");
ret = dataShareProxy_->BatchInsert(uri, values);
LOG_INFO("DataShareHelper::BatchInsert after dataShareProxy_->BatchInsert.");
LOG_INFO("DataShareHelper::BatchInsert end.");
return ret;
}
bool DataShareHelper::CheckUriParam(const Uri &uri)
{
LOG_INFO("DataShareHelper::CheckUriParam start.");
Uri checkUri(uri.ToString());
if (!CheckOhosUri(checkUri)) {
LOG_ERROR("DataShareHelper::CheckUriParam failed. CheckOhosUri uri failed");
return false;
}
if (uri_.ToString().empty()) {
if (!CheckOhosUri(uri_)) {
LOG_ERROR("DataShareHelper::CheckUriParam failed. CheckOhosUri uri_ failed");
return false;
}
std::vector<std::string> checkSegments;
checkUri.GetPathSegments(checkSegments);
std::vector<std::string> segments;
uri_.GetPathSegments(segments);
if (checkSegments[0] != segments[0]) {
LOG_ERROR("DataShareHelper::CheckUriParam failed. the datashare in uri doesn't equal the one in uri_.");
return false;
}
}
LOG_INFO("DataShareHelper::CheckUriParam end.");
return true;
}
bool DataShareHelper::CheckOhosUri(const Uri &uri)
{
LOG_INFO("DataShareHelper::CheckOhosUri start.");
Uri checkUri(uri.ToString());
if (checkUri.GetScheme() != SCHEME_DATASHARE) {
LOG_ERROR("DataShareHelper::CheckOhosUri failed. uri is not a datashare one.");
return false;
}
std::vector<std::string> segments;
checkUri.GetPathSegments(segments);
if (segments.empty()) {
LOG_ERROR("DataShareHelper::CheckOhosUri failed. There is no segments in the uri.");
return false;
}
if (checkUri.GetPath() == "") {
LOG_ERROR("DataShareHelper::CheckOhosUri failed. The path in the uri is empty.");
return false;
}
LOG_INFO("DataShareHelper::CheckOhosUri end.");
return true;
}
/**
* @brief Registers an observer to DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
void DataShareHelper::RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("DataShareHelper::RegisterObserver start.");
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return;
}
if (dataObserver == nullptr) {
LOG_ERROR("%{public}s called. dataObserver is nullptr", __func__);
return;
}
Uri tmpUri(uri.ToString());
std::lock_guard<std::mutex> lock_l(oplock_);
if (uri_.ToString().empty()) {
auto datashare = registerMap_.find(dataObserver);
if (datashare == registerMap_.end()) {
if (!dataShareConnection_->IsExtAbilityConnected()) {
dataShareConnection_->ConnectDataShareExtAbility(uri, token_);
}
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
registerMap_.emplace(dataObserver, dataShareProxy_);
uriMap_.emplace(dataObserver, tmpUri.GetPath());
} else {
auto path = uriMap_.find(dataObserver);
if (path->second != tmpUri.GetPath()) {
LOG_ERROR("DataShareHelper::RegisterObserver failed input uri's path is not equal the one the "
"observer used");
return;
}
dataShareProxy_ = datashare->second;
}
} else {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_ == nullptr) {
LOG_ERROR("DataShareHelper::RegisterObserver failed dataShareProxy_ == nullptr");
registerMap_.erase(dataObserver);
uriMap_.erase(dataObserver);
return;
}
dataShareProxy_->RegisterObserver(uri, dataObserver);
LOG_INFO("DataShareHelper::RegisterObserver end.");
}
/**
* @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
void DataShareHelper::UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("DataShareHelper::UnregisterObserver start.");
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return;
}
if (dataObserver == nullptr) {
LOG_ERROR("%{public}s called. dataObserver is nullptr", __func__);
return;
}
Uri tmpUri(uri.ToString());
std::lock_guard<std::mutex> lock_l(oplock_);
if (uri_.ToString().empty()) {
auto datashare = registerMap_.find(dataObserver);
if (datashare == registerMap_.end()) {
return;
}
auto path = uriMap_.find(dataObserver);
if (path->second != tmpUri.GetPath()) {
LOG_ERROR("DataShareHelper::UnregisterObserver failed input uri's path is not equal the one the "
"observer used");
return;
}
dataShareProxy_ = datashare->second;
} else {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_ == nullptr) {
LOG_ERROR("DataShareHelper::UnregisterObserver failed dataShareProxy_ == nullptr");
return;
}
dataShareProxy_->UnregisterObserver(uri, dataObserver);
if (uri_.ToString().empty()) {
LOG_INFO("DataShareHelper::UnregisterObserver before DisconnectDataShareExtAbility.");
if (dataShareConnection_->IsExtAbilityConnected()) {
dataShareConnection_->DisconnectDataShareExtAbility();
}
LOG_INFO("DataShareHelper::UnregisterObserver after DisconnectDataShareExtAbility.");
dataShareProxy_ = nullptr;
}
registerMap_.erase(dataObserver);
uriMap_.erase(dataObserver);
LOG_INFO("DataShareHelper::UnregisterObserver end.");
}
/**
* @brief Notifies the registered observers of a change to the data resource specified by Uri.
*
* @param uri, Indicates the path of the data to operate.
*/
void DataShareHelper::NotifyChange(const Uri &uri)
{
LOG_INFO("DataShareHelper::NotifyChange start.");
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return;
}
LOG_INFO("DataShareHelper::NotifyChange before dataShareProxy_->NotifyChange.");
dataShareProxy_->NotifyChange(uri);
LOG_INFO("DataShareHelper::NotifyChange after dataShareProxy_->NotifyChange.");
LOG_INFO("DataShareHelper::NotifyChange end.");
}
/**
* @brief Converts the given uri that refer to the data share into a normalized URI. A normalized URI can be used
* across devices, persisted, backed up, and restored. It can refer to the same item in the data share even if the
* context has changed. If you implement URI normalization for a data share, you must also implement
* denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any
* method that is called on the data share must require normalization verification and denormalization. The default
* implementation of this method returns null, indicating that this data share does not support URI normalization.
*
* @param uri Indicates the Uri object to normalize.
*
* @return Returns the normalized Uri object if the data share supports URI normalization; returns null otherwise.
*/
Uri DataShareHelper::NormalizeUri(Uri &uri)
{
LOG_INFO("DataShareHelper::NormalizeUri start.");
Uri urivalue("");
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return urivalue;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return urivalue;
}
LOG_INFO("DataShareHelper::NormalizeUri before dataShareProxy_->NormalizeUri.");
urivalue = dataShareProxy_->NormalizeUri(uri);
LOG_INFO("DataShareHelper::NormalizeUri after dataShareProxy_->NormalizeUri.");
LOG_INFO("DataShareHelper::NormalizeUri end.");
return urivalue;
}
/**
* @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
* The default implementation of this method returns the original URI passed to it.
*
* @param uri uri Indicates the Uri object to denormalize.
*
* @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to
* this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in
* the current environment.
*/
Uri DataShareHelper::DenormalizeUri(Uri &uri)
{
LOG_INFO("DataShareHelper::DenormalizeUri start.");
Uri urivalue("");
if (!CheckUriParam(uri)) {
LOG_ERROR("%{public}s called. CheckUriParam uri failed", __func__);
return urivalue;
}
if (dataShareProxy_ == nullptr) {
dataShareProxy_ = dataShareConnection_->GetDataShareProxy();
}
if (dataShareProxy_) {
AddDataShareDeathRecipient(dataShareProxy_->AsObject());
} else {
LOG_ERROR("%{public}s failed with invalid dataShareProxy_", __func__);
return urivalue;
}
LOG_INFO("DataShareHelper::DenormalizeUri before dataShareProxy_->DenormalizeUri.");
urivalue = dataShareProxy_->DenormalizeUri(uri);
LOG_INFO("DataShareHelper::DenormalizeUri after dataShareProxy_->DenormalizeUri.");
LOG_INFO("DataShareHelper::DenormalizeUri end.");
return urivalue;
}
void DataShareDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
LOG_INFO("recv DataShareDeathRecipient death notice");
if (handler_) {
handler_(remote);
}
LOG_INFO("DataShareHelper::OnRemoteDied end.");
}
DataShareDeathRecipient::DataShareDeathRecipient(RemoteDiedHandler handler) : handler_(handler)
{}
DataShareDeathRecipient::~DataShareDeathRecipient()
{}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,580 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_proxy.h"
#include <string_ex.h>
#include "datashare_result_set.h"
#include "data_ability_observer_interface.h"
#include "datashare_operation.h"
#include "datashare_log.h"
#include "ipc_types.h"
#include "ishared_result_set.h"
#include "pac_map.h"
namespace OHOS {
namespace DataShare {
std::vector<std::string> DataShareProxy::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
LOG_INFO("begin.");
std::vector<std::string> types;
MessageParcel data;
MessageParcel reply;
MessageOption option;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return types;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return types;
}
if (!data.WriteString(mimeTypeFilter)) {
LOG_ERROR("fail to WriteString mimeTypeFilter");
return types;
}
int32_t err = Remote()->SendRequest(CMD_GET_FILE_TYPES, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err);
}
if (!reply.ReadStringVector(&types)) {
LOG_ERROR("fail to ReadStringVector types");
}
LOG_INFO("end successfully.");
return types;
}
int DataShareProxy::OpenFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
int fd = -1;
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return fd;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return fd;
}
if (!data.WriteString(mode)) {
LOG_ERROR("fail to WriteString mode");
return fd;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_OPEN_FILE, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("OpenFile fail to SendRequest. err: %d", err);
return fd;
}
fd = reply.ReadFileDescriptor();
if (fd == -1) {
LOG_ERROR("fail to ReadFileDescriptor fd");
return fd;
}
LOG_INFO("end successfully.");
return fd;
}
int DataShareProxy::OpenRawFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
int fd = -1;
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return fd;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return fd;
}
if (!data.WriteString(mode)) {
LOG_ERROR("fail to WriteString mode");
return fd;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_OPEN_RAW_FILE, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("OpenRawFile fail to SendRequest. err: %d", err);
return fd;
}
if (!reply.ReadInt32(fd)) {
LOG_ERROR("fail to ReadInt32 fd");
return fd;
}
LOG_INFO("end successfully.");
return fd;
}
int DataShareProxy::Insert(const Uri &uri, const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
int index = -1;
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return index;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return index;
}
if (!DataShareValuesBucket::Marshalling(value, data)) {
LOG_ERROR("fail to WriteParcelable value");
return index;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_INSERT, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("Insert fail to SendRequest. err: %d", err);
return index;
}
if (!reply.ReadInt32(index)) {
LOG_ERROR("fail to ReadInt32 index");
return index;
}
LOG_INFO("end successfully.");
return index;
}
int DataShareProxy::Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
int index = -1;
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return index;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return index;
}
if (!data.WriteParcelable(&predicates)) {
LOG_ERROR("fail to WriteParcelable predicates");
return index;
}
if (!DataShareValuesBucket::Marshalling(value, data)) {
LOG_ERROR("fail to WriteParcelable value");
return index;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_UPDATE, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("Update fail to SendRequest. err: %d", err);
return index;
}
if (!reply.ReadInt32(index)) {
LOG_ERROR("fail to ReadInt32 index");
return index;
}
LOG_INFO("end successfully.");
return index;
}
int DataShareProxy::Delete(const Uri &uri, const DataSharePredicates &predicates)
{
LOG_INFO("begin.");
int index = -1;
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return index;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return index;
}
if (!data.WriteParcelable(&predicates)) {
LOG_ERROR("fail to WriteParcelable predicates");
return index;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_DELETE, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("Delete fail to SendRequest. err: %d", err);
return index;
}
if (!reply.ReadInt32(index)) {
LOG_ERROR("fail to ReadInt32 index");
return index;
}
LOG_INFO("end successfully.");
return index;
}
std::shared_ptr<DataShareResultSet> DataShareProxy::Query(const Uri &uri,
const DataSharePredicates &predicates, std::vector<std::string> &columns)
{
LOG_INFO("begin.");
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return nullptr;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return nullptr;
}
if (!data.WriteParcelable(&predicates)) {
LOG_ERROR("fail to WriteParcelable predicates");
return nullptr;
}
if (!data.WriteStringVector(columns)) {
LOG_ERROR("fail to WriteStringVector columns");
return nullptr;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_QUERY, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("Query fail to SendRequest. err: %d", err);
return nullptr;
}
LOG_INFO("end successfully.");
return ISharedResultSet::ReadFromParcel(reply);
}
std::string DataShareProxy::GetType(const Uri &uri)
{
LOG_INFO("begin.");
std::string type;
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return type;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return type;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_GET_TYPE, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err);
return type;
}
type = reply.ReadString();
if (type.empty()) {
LOG_ERROR("fail to ReadString type");
return type;
}
LOG_INFO("end successfully.");
return type;
}
int DataShareProxy::BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values)
{
LOG_INFO("begin.");
int ret = -1;
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return ret;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return ret;
}
int count = (int)values.size();
if (!data.WriteInt32(count)) {
LOG_ERROR("fail to WriteInt32 ret");
return ret;
}
for (int i = 0; i < count; i++) {
if (!DataShareValuesBucket::Marshalling(values[i], data)) {
LOG_ERROR("fail to WriteParcelable ret, index = %{public}d", i);
return ret;
}
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_BATCH_INSERT, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("GetFileTypes fail to SendRequest. err: %d", err);
return ret;
}
if (!reply.ReadInt32(ret)) {
LOG_ERROR("fail to ReadInt32 index");
return ret;
}
LOG_INFO("end successfully.");
return ret;
}
bool DataShareProxy::RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return false;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__);
return false;
}
if (!data.WriteRemoteObject(dataObserver->AsObject())) {
LOG_ERROR("%{public}s failed to WriteParcelable dataObserver ", __func__);
return false;
}
MessageParcel reply;
MessageOption option;
int32_t result = Remote()->SendRequest(CMD_REGISTER_OBSERVER, data, reply, option);
if (result == ERR_NONE) {
LOG_INFO("SendRequest ok, retval is %{public}d", reply.ReadInt32());
} else {
LOG_ERROR("SendRequest error, result=%{public}d", result);
return false;
}
LOG_INFO("end.");
return true;
}
bool DataShareProxy::UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return false;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__);
return false;
}
if (!data.WriteRemoteObject(dataObserver->AsObject())) {
LOG_ERROR("%{public}s failed to WriteParcelable dataObserver ", __func__);
return false;
}
MessageParcel reply;
MessageOption option;
int32_t result = Remote()->SendRequest(CMD_UNREGISTER_OBSERVER, data, reply, option);
if (result == ERR_NONE) {
LOG_INFO("SendRequest ok, retval is %{public}d", reply.ReadInt32());
} else {
LOG_ERROR("SendRequest error, result=%{public}d", result);
return false;
}
LOG_INFO("end successfully.");
return true;
}
bool DataShareProxy::NotifyChange(const Uri &uri)
{
LOG_INFO("begin.");
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return false;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("%{public}s failed to WriteParcelable uri ", __func__);
return false;
}
MessageParcel reply;
MessageOption option;
int32_t result = Remote()->SendRequest(CMD_NOTIFY_CHANGE, data, reply, option);
if (result == ERR_NONE) {
LOG_INFO("SendRequest ok, retval is %{public}d", reply.ReadInt32());
} else {
LOG_ERROR("SendRequest error, result=%{public}d", result);
return false;
}
LOG_INFO("end successfully.");
return true;
}
Uri DataShareProxy::NormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
Uri urivalue("");
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return urivalue;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return urivalue;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_NORMALIZE_URI, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("NormalizeUri fail to SendRequest. err: %d", err);
return urivalue;
}
std::unique_ptr<Uri> info(reply.ReadParcelable<Uri>());
if (!info) {
LOG_ERROR("ReadParcelable value is nullptr.");
return urivalue;
}
LOG_INFO("end successfully.");
return *info;
}
Uri DataShareProxy::DenormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
Uri urivalue("");
MessageParcel data;
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return urivalue;
}
if (!data.WriteParcelable(&uri)) {
LOG_ERROR("fail to WriteParcelable uri");
return urivalue;
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_DENORMALIZE_URI, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("DenormalizeUri fail to SendRequest. err: %d", err);
return urivalue;
}
std::unique_ptr<Uri> info(reply.ReadParcelable<Uri>());
if (!info) {
LOG_ERROR("ReadParcelable value is nullptr.");
return urivalue;
}
LOG_INFO("end successfully.");
return *info;
}
std::vector<std::shared_ptr<DataShareResult>> DataShareProxy::ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations)
{
LOG_INFO("begin.");
MessageParcel data;
std::vector<std::shared_ptr<DataShareResult>> results;
results.clear();
if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) {
LOG_ERROR("%{public}s WriteInterfaceToken failed", __func__);
return results;
}
int count = (int)operations.size();
if (!data.WriteInt32(count)) {
LOG_ERROR("fail to WriteInt32 ret");
return results;
}
for (int i = 0; i < count; i++) {
if (!data.WriteParcelable(operations[i].get())) {
LOG_ERROR("fail to WriteParcelable ret, index = %{public}d", i);
return results;
}
}
MessageParcel reply;
MessageOption option;
int32_t err = Remote()->SendRequest(CMD_EXECUTE_BATCH, data, reply, option);
if (err != NO_ERROR) {
LOG_ERROR("fail to SendRequest. err: %{public}d", err);
return results;
}
int total = 0;
if (!reply.ReadInt32(total)) {
LOG_ERROR("fail to ReadInt32 count %{public}d", total);
return results;
}
for (int i = 0; i < total; i++) {
DataShareResult *result = reply.ReadParcelable<DataShareResult>();
if (result == nullptr) {
LOG_ERROR("result is nullptr, index = %{public}d", i);
return results;
}
std::shared_ptr<DataShareResult> dataShareResult(result);
results.push_back(dataShareResult);
}
LOG_INFO("end successfully.");
return results;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,240 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_EXT_ABILITY_H
#define DATASHARE_EXT_ABILITY_H
#include "extension_base.h"
#include "datashare_values_bucket.h"
#include "datashare_result.h"
#include "datashare_predicates.h"
#include "datashare_result_set.h"
#include "datashare_operation.h"
namespace OHOS {
namespace AAFwk {
class IDataAbilityObserver;
}
namespace AbilityRuntime {
class Runtime;
}
namespace DataShare {
using namespace AbilityRuntime;
class DataShareExtAbilityContext;
class DataShareExtAbility;
using CreatorFunc = std::function<DataShareExtAbility* (const std::unique_ptr<Runtime>& runtime)>;
/**
* @brief Basic datashare extension ability components.
*/
class DataShareExtAbility : public ExtensionBase<DataShareExtAbilityContext> {
public:
DataShareExtAbility() = default;
virtual ~DataShareExtAbility() = default;
/**
* @brief Init the extension.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
*/
virtual void Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application,
std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token) override;
/**
* @brief Create Extension.
*
* @param runtime The runtime.
* @return The DataShareExtAbility instance.
*/
static DataShareExtAbility* Create(const std::unique_ptr<Runtime>& runtime);
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
virtual std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter);
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
virtual int OpenFile(const Uri &uri, const std::string &mode);
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
virtual int OpenRawFile(const Uri &uri, const std::string &mode);
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
virtual int Insert(const Uri &uri, const DataShareValuesBucket &value);
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param value Indicates the data to update. This parameter can be null.
*
* @return Returns the number of data records updated.
*/
virtual int Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
virtual int Delete(const Uri &uri, const DataSharePredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
*
* @return Returns the query result.
*/
virtual std::shared_ptr<DataShareResultSet> Query(
const Uri &uri, const DataSharePredicates &predicates, std::vector<std::string> &columns);
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
virtual std::string GetType(const Uri &uri);
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
virtual int BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values);
/**
* @brief Registers an observer to DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
virtual bool RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver);
/**
* @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
virtual bool UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver);
/**
* @brief Notifies the registered observers of a change to the data resource specified by Uri.
*
* @param uri, Indicates the path of the data to operate.
*
* @return Return true if success. otherwise return false.
*/
virtual bool NotifyChange(const Uri &uri);
/**
* @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
* across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if
* the context has changed. If you implement URI normalization for a Data ability, you must also implement
* denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
* any method that is called on the Data ability must require normalization verification and denormalization. The
* default implementation of this method returns null, indicating that this Data ability does not support URI
* normalization.
*
* @param uri Indicates the Uri object to normalize.
*
* @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
*/
virtual Uri NormalizeUri(const Uri &uri);
/**
* @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
* The default implementation of this method returns the original URI passed to it.
*
* @param uri uri Indicates the Uri object to denormalize.
*
* @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri
* passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot
* be found in the current environment.
*/
virtual Uri DenormalizeUri(const Uri &uri);
/**
* @brief Performs batch operations on the database.
*
* @param operations Indicates a list of database operations on the database.
* @return Returns the result of each operation, in array.
*/
virtual std::vector<std::shared_ptr<DataShareResult>> ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations);
/**
* @brief Set a creator function.
*
* @param creator The function for create a datashare extension ability.
*/
static void SetCreator(const CreatorFunc& creator);
private:
static CreatorFunc creator_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_EXT_ABILITY_H

View File

@ -1,44 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_EXT_ABILITY_CONTEXT_H
#define DATASHARE_EXT_ABILITY_CONTEXT_H
#include "extension_context.h"
namespace OHOS {
namespace DataShare {
using namespace AbilityRuntime;
/**
* @brief context supply for datashare
*
*/
class DataShareExtAbilityContext : public ExtensionContext {
public:
DataShareExtAbilityContext();
virtual ~DataShareExtAbilityContext() = default;
using SelfType = DataShareExtAbilityContext;
static const size_t CONTEXT_TYPE_ID;
protected:
bool IsContext(size_t contextTypeId) override
{
return contextTypeId == CONTEXT_TYPE_ID || ExtensionContext::IsContext(contextTypeId);
}
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_EXT_ABILITY_CONTEXT_H

View File

@ -1,37 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_EXT_ABILITY_MODULE_LOADER_H
#define DATASHARE_EXT_ABILITY_MODULE_LOADER_H
#include "extension_module_loader.h"
namespace OHOS::DataShare {
using namespace AbilityRuntime;
class DataShareExtAbilityModuleLoader : public ExtensionModuleLoader,
public Singleton<DataShareExtAbilityModuleLoader> {
DECLARE_SINGLETON(DataShareExtAbilityModuleLoader);
public:
/**
* @brief Create Extension.
*
* @param runtime The runtime.
* @return The Extension instance.
*/
virtual Extension *Create(const std::unique_ptr<Runtime>& runtime) const override;
};
} // namespace OHOS::DataShare
#endif // DATASHARE_EXT_ABILITY_MODULE_LOADER_H

View File

@ -1,54 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_STUB_H
#define DATASHARE_STUB_H
#include <iremote_stub.h>
#include <map>
#include "idatashare.h"
namespace OHOS {
namespace DataShare {
class DataShareStub : public IRemoteStub<IDataShare> {
public:
DataShareStub();
~DataShareStub();
int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override;
private:
ErrCode CmdGetFileTypes(MessageParcel &data, MessageParcel &reply);
ErrCode CmdOpenFile(MessageParcel &data, MessageParcel &reply);
ErrCode CmdOpenRawFile(MessageParcel &data, MessageParcel &reply);
ErrCode CmdInsert(MessageParcel &data, MessageParcel &reply);
ErrCode CmdUpdate(MessageParcel &data, MessageParcel &reply);
ErrCode CmdDelete(MessageParcel &data, MessageParcel &reply);
ErrCode CmdQuery(MessageParcel &data, MessageParcel &reply);
ErrCode CmdGetType(MessageParcel &data, MessageParcel &reply);
ErrCode CmdBatchInsert(MessageParcel &data, MessageParcel &reply);
ErrCode CmdRegisterObserver(MessageParcel &data, MessageParcel &reply);
ErrCode CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply);
ErrCode CmdNotifyChange(MessageParcel &data, MessageParcel &reply);
ErrCode CmdNormalizeUri(MessageParcel &data, MessageParcel &reply);
ErrCode CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply);
ErrCode CmdExecuteBatch(MessageParcel &data, MessageParcel &reply);
using RequestFuncType = int (DataShareStub::*)(MessageParcel &data, MessageParcel &reply);
std::map<uint32_t, RequestFuncType> stubFuncMap_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_STUB_H

View File

@ -1,81 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_STUB_IMPL_H
#define DATASHARE_STUB_IMPL_H
#include <memory>
#include "datashare_stub.h"
#include "datashare_uv_queue.h"
#include "js_datashare_ext_ability.h"
#include "native_engine/native_value.h"
namespace OHOS {
namespace DataShare {
using DataShare::JsDataShareExtAbility;
class DataShareStubImpl : public DataShareStub {
public:
explicit DataShareStubImpl(const std::shared_ptr<JsDataShareExtAbility>& extension, napi_env env)
: extension_(extension)
{
uvQueue_ = std::make_shared<DataShare::DataShareUvQueue>(env);
}
virtual ~DataShareStubImpl() {}
std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override;
int OpenFile(const Uri &uri, const std::string &mode) override;
int OpenRawFile(const Uri &uri, const std::string &mode) override;
int Insert(const Uri &uri, const DataShareValuesBucket &value) override;
int Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value) override;
int Delete(const Uri &uri, const DataSharePredicates &predicates) override;
std::shared_ptr<DataShareResultSet> Query(const Uri &uri,
const DataSharePredicates &predicates, std::vector<std::string> &columns) override;
std::string GetType(const Uri &uri) override;
int BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values) override;
bool RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
bool UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
bool NotifyChange(const Uri &uri) override;
Uri NormalizeUri(const Uri &uri) override;
Uri DenormalizeUri(const Uri &uri) override;
std::vector<std::shared_ptr<DataShareResult>> ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations) override;
private:
std::shared_ptr<JsDataShareExtAbility> GetOwner();
private:
std::shared_ptr<JsDataShareExtAbility> extension_;
std::shared_ptr<DataShare::DataShareUvQueue> uvQueue_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_STUB_IMPL_H

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_UV_QUEUE_H
#define DATASHARE_UV_QUEUE_H
#include <functional>
#include "napi/native_api.h"
#include "napi/native_common.h"
#include "napi/native_node_api.h"
#include "uv.h"
namespace OHOS {
namespace DataShare {
class DataShareUvQueue {
using NapiVoidFunc = std::function<void()>;
using NapiBoolFunc = std::function<bool()>;
public:
explicit DataShareUvQueue(napi_env env);
virtual ~DataShareUvQueue() = default;
void SyncCall(NapiVoidFunc func = NapiVoidFunc(), NapiBoolFunc retFunc = NapiBoolFunc());
void CheckFuncAndExec(NapiBoolFunc retFunc);
private:
struct UvEntry {
napi_env env;
NapiVoidFunc func;
bool done;
bool purge;
std::condition_variable condition;
std::mutex mutex;
NapiBoolFunc retFunc;
};
static void Purge(uv_work_t* work);
napi_env env_ = nullptr;
uv_loop_s* loop_ = nullptr;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_UV_QUEUE_H

View File

@ -1,320 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JS_DATASHARE_EXT_ABILITY_H
#define JS_DATASHARE_EXT_ABILITY_H
#include "datashare_result_set.h"
#include "datashare_predicates.h"
#include "datashare_ext_ability.h"
#include "js_runtime.h"
#include "native_engine/native_reference.h"
#include "native_engine/native_value.h"
namespace OHOS {
namespace DataShare {
using namespace AbilityRuntime;
/**
* @brief Basic datashare extension ability components.
*/
class JsDataShareExtAbility : public DataShareExtAbility {
public:
explicit JsDataShareExtAbility(JsRuntime& jsRuntime);
virtual ~JsDataShareExtAbility() override;
/**
* @brief Create JsDataShareExtAbility.
*
* @param runtime The runtime.
* @return The JsDataShareExtAbility instance.
*/
static JsDataShareExtAbility* Create(const std::unique_ptr<Runtime>& runtime);
/**
* @brief Init the extension.
*
* @param record the extension record.
* @param application the application info.
* @param handler the extension handler.
* @param token the remote token.
*/
void Init(const std::shared_ptr<AppExecFwk::AbilityLocalRecord> &record,
const std::shared_ptr<AppExecFwk::OHOSApplication> &application,
std::shared_ptr<AppExecFwk::AbilityHandler> &handler,
const sptr<IRemoteObject> &token) override;
/**
* @brief Called when this datashare extension ability is started. You must override this function if you want to
* perform some initialization operations during extension startup.
*
* This function can be called only once in the entire lifecycle of an extension.
* @param Want Indicates the {@link Want} structure containing startup information about the extension.
*/
void OnStart(const AAFwk::Want &want) override;
/**
* @brief Called when this datashare extension ability is connected for the first time.
*
* You can override this function to implement your own processing logic.
*
* @param want Indicates the {@link Want} structure containing connection information about the datashare
* extension.
* @return Returns a pointer to the <b>sid</b> of the connected datashare extension ability.
*/
sptr<IRemoteObject> OnConnect(const AAFwk::Want &want) override;
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override;
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int OpenFile(const Uri &uri, const std::string &mode) override;
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int OpenRawFile(const Uri &uri, const std::string &mode) override;
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int Insert(const Uri &uri, const DataShareValuesBucket &value) override;
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param value Indicates the data to update. This parameter can be null.
*
* @return Returns the number of data records updated.
*/
int Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value) override;
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int Delete(const Uri &uri, const DataSharePredicates &predicates) override;
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
*
* @return Returns the query result.
*/
std::shared_ptr<DataShareResultSet> Query(const Uri &uri, const DataSharePredicates &predicates,
std::vector<std::string> &columns) override;
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be
* implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string GetType(const Uri &uri) override;
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values) override;
/**
* @brief Registers an observer to DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
bool RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
/**
* @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
bool UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) override;
/**
* @brief Notifies the registered observers of a change to the data resource specified by Uri.
*
* @param uri, Indicates the path of the data to operate.
*
* @return Return true if success. otherwise return false.
*/
bool NotifyChange(const Uri &uri) override;
/**
* @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used
* across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if
* the context has changed. If you implement URI normalization for a Data ability, you must also implement
* denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
* any method that is called on the Data ability must require normalization verification and denormalization. The
* default implementation of this method returns null, indicating that this Data ability does not support URI
* normalization.
*
* @param uri Indicates the Uri object to normalize.
*
* @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise.
*/
Uri NormalizeUri(const Uri &uri) override;
/**
* @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
* The default implementation of this method returns the original URI passed to it.
*
* @param uri uri Indicates the Uri object to denormalize.
*
* @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri
* passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot
* be found in the current environment.
*/
Uri DenormalizeUri(const Uri &uri) override;
/**
* @brief Performs batch operations on the database.
*
* @param operations Indicates a list of database operations on the database.
* @return Returns the result of each operation, in array.
*/
std::vector<std::shared_ptr<DataShareResult>> ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations) override;
bool GetBlockWaiting() const
{
return isBlockWaiting_;
}
void SetBlockWaiting(bool blockWaiting)
{
isBlockWaiting_ = blockWaiting;
}
NativeValue* GetAsyncResult() const
{
return callbackData_;
}
void SetAsyncResult(NativeValue* asyncResult)
{
callbackData_ = asyncResult;
}
void GetResult(int &value)
{
value = callbackResultNumber_;
}
void SetResult(const int value)
{
callbackResultNumber_ = value;
}
void GetResult(std::string &value)
{
value = callbackResultString_;
}
void SetResult(const std::string value)
{
callbackResultString_ = value;
}
void GetResult(std::vector<std::string> &value)
{
value = callbackResultStringArr_;
}
void SetResult(const std::vector<std::string> value)
{
callbackResultStringArr_ = value;
}
void GetResult(std::shared_ptr<DataShareResultSet> &value)
{
value = callbackResultObject_;
}
void SetResult(const std::shared_ptr<DataShareResultSet> value)
{
callbackResultObject_ = value;
}
private:
NativeValue* CallObjectMethod(const char *name, NativeValue * const *argv = nullptr, size_t argc = 0,
bool isAsync = true);
void GetSrcPath(std::string &srcPath);
bool CheckCallingPermission(const std::string &permission);
napi_value MakePredicates(napi_env env, const DataSharePredicates &predicates);
static NativeValue* AsyncCallback(NativeEngine* engine, NativeCallbackInfo* info);
void CheckAndSetAsyncResult(NativeEngine* engine);
JsRuntime& jsRuntime_;
std::unique_ptr<NativeReference> jsObj_;
bool isBlockWaiting_ = false;
NativeValue* callbackData_ = nullptr;
int callbackResultNumber_ = -1;
std::string callbackResultString_ = "";
std::vector<std::string> callbackResultStringArr_ = {};
std::shared_ptr<DataShareResultSet> callbackResultObject_ = nullptr;
};
} // namespace DataShare
} // namespace OHOS
#endif // JS_DATASHARE_EXT_ABILITY_H

View File

@ -1,33 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JS_DATASHARE_EXT_ABILITY_CONTEXT_H
#define JS_DATASHARE_EXT_ABILITY_CONTEXT_H
#include <memory>
#include "ability_connect_callback.h"
#include "datashare_ext_ability_context.h"
#include "native_engine/native_engine.h"
#include "native_engine/native_value.h"
namespace OHOS {
namespace DataShare {
using namespace AbilityRuntime;
NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine,
std::shared_ptr<DataShareExtAbilityContext> context);
} // namespace DataShare
} // namespace OHOS
#endif // JS_DATASHARE_EXT_ABILITY_CONTEXT_H

View File

@ -1,177 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_ext_ability.h"
#include "ability_loader.h"
#include "connection_manager.h"
#include "datashare_log.h"
#include "js_datashare_ext_ability.h"
#include "runtime.h"
#include "datashare_ext_ability_context.h"
namespace OHOS {
namespace DataShare {
using namespace OHOS::AppExecFwk;
CreatorFunc DataShareExtAbility::creator_ = nullptr;
void DataShareExtAbility::SetCreator(const CreatorFunc& creator)
{
creator_ = creator;
}
DataShareExtAbility* DataShareExtAbility::Create(const std::unique_ptr<Runtime>& runtime)
{
if (!runtime) {
return new DataShareExtAbility();
}
if (creator_) {
return creator_(runtime);
}
LOG_INFO("DataShareExtAbility::Create runtime");
switch (runtime->GetLanguage()) {
case Runtime::Language::JS:
return JsDataShareExtAbility::Create(runtime);
default:
return new DataShareExtAbility();
}
}
void DataShareExtAbility::Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application,
std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token)
{
ExtensionBase<DataShareExtAbilityContext>::Init(record, application, handler, token);
LOG_INFO("DataShareExtAbility begin init context");
}
std::vector<std::string> DataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
LOG_INFO("begin.");
std::vector<std::string> ret;
LOG_INFO("end.");
return ret;
}
int DataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return 0;
}
int DataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return 0;
}
int DataShareExtAbility::Insert(const Uri &uri, const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return 0;
}
int DataShareExtAbility::Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return 0;
}
int DataShareExtAbility::Delete(const Uri &uri, const DataSharePredicates &predicates)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return 0;
}
std::shared_ptr<DataShareResultSet> DataShareExtAbility::Query(const Uri &uri,
const DataSharePredicates &predicates, std::vector<std::string> &columns)
{
LOG_INFO("begin.");
std::shared_ptr<DataShareResultSet> ret;
LOG_INFO("end.");
return ret;
}
std::string DataShareExtAbility::GetType(const Uri &uri)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return "";
}
int DataShareExtAbility::BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return 0;
}
bool DataShareExtAbility::RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return true;
}
bool DataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return true;
}
bool DataShareExtAbility::NotifyChange(const Uri &uri)
{
LOG_INFO("begin.");
LOG_INFO("end.");
return true;
}
Uri DataShareExtAbility::NormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
Uri urivalue("");
LOG_INFO("end.");
return urivalue;
}
Uri DataShareExtAbility::DenormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
Uri urivalue("");
LOG_INFO("end.");
return urivalue;
}
std::vector<std::shared_ptr<DataShareResult>> DataShareExtAbility::ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations)
{
LOG_INFO("begin.");
std::vector<std::shared_ptr<DataShareResult>> results;
LOG_INFO("end.");
return results;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,25 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_ext_ability_context.h"
namespace OHOS {
namespace DataShare {
using namespace AbilityRuntime;
const size_t DataShareExtAbilityContext::CONTEXT_TYPE_ID(std::hash<const char*> {} ("DataShareExtAbilityContext"));
DataShareExtAbilityContext::DataShareExtAbilityContext() {}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,38 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_ext_ability_module_loader.h"
#include "datashare_ext_ability.h"
namespace OHOS::DataShare {
using namespace AbilityRuntime;
DataShareExtAbilityModuleLoader::DataShareExtAbilityModuleLoader() = default;
DataShareExtAbilityModuleLoader::~DataShareExtAbilityModuleLoader() = default;
Extension *DataShareExtAbilityModuleLoader::Create(const std::unique_ptr<Runtime>& runtime) const
{
return DataShareExtAbility::Create(runtime);
}
extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule()
{
return &DataShareExtAbilityModuleLoader::GetInstance();
}
extern "C" __attribute__((visibility("default"))) void SetCreator(const CreatorFunc& creator)
{
return DataShareExtAbility::SetCreator(creator);
}
} // namespace OHOS::DataShare

View File

@ -1,418 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_stub.h"
#include "data_ability_observer_interface.h"
#include "data_ability_operation.h"
#include "data_ability_predicates.h"
#include "datashare_log.h"
#include "ipc_types.h"
#include "ishared_result_set.h"
#include "values_bucket.h"
namespace OHOS {
namespace DataShare {
DataShareStub::DataShareStub()
{
stubFuncMap_[CMD_GET_FILE_TYPES] = &DataShareStub::CmdGetFileTypes;
stubFuncMap_[CMD_OPEN_FILE] = &DataShareStub::CmdOpenFile;
stubFuncMap_[CMD_OPEN_RAW_FILE] = &DataShareStub::CmdOpenRawFile;
stubFuncMap_[CMD_INSERT] = &DataShareStub::CmdInsert;
stubFuncMap_[CMD_UPDATE] = &DataShareStub::CmdUpdate;
stubFuncMap_[CMD_DELETE] = &DataShareStub::CmdDelete;
stubFuncMap_[CMD_QUERY] = &DataShareStub::CmdQuery;
stubFuncMap_[CMD_GET_TYPE] = &DataShareStub::CmdGetType;
stubFuncMap_[CMD_BATCH_INSERT] = &DataShareStub::CmdBatchInsert;
stubFuncMap_[CMD_REGISTER_OBSERVER] = &DataShareStub::CmdRegisterObserver;
stubFuncMap_[CMD_UNREGISTER_OBSERVER] = &DataShareStub::CmdUnregisterObserver;
stubFuncMap_[CMD_NOTIFY_CHANGE] = &DataShareStub::CmdNotifyChange;
stubFuncMap_[CMD_NORMALIZE_URI] = &DataShareStub::CmdNormalizeUri;
stubFuncMap_[CMD_DENORMALIZE_URI] = &DataShareStub::CmdDenormalizeUri;
stubFuncMap_[CMD_EXECUTE_BATCH] = &DataShareStub::CmdExecuteBatch;
}
DataShareStub::~DataShareStub()
{
stubFuncMap_.clear();
}
int DataShareStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply,
MessageOption& option)
{
LOG_INFO("Received stub message: %{public}d", code);
std::u16string descriptor = DataShareStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
LOG_INFO("local descriptor is not equal to remote");
return ERR_INVALID_STATE;
}
const auto &itFunc = stubFuncMap_.find(code);
if (itFunc != stubFuncMap_.end()) {
return (this->*(itFunc->second))(data, reply);
}
LOG_INFO("remote request unhandled: %{public}d", code);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
ErrCode DataShareStub::CmdGetFileTypes(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::string mimeTypeFilter = data.ReadString();
if (mimeTypeFilter.empty()) {
LOG_ERROR("DataShareStub mimeTypeFilter is nullptr");
return ERR_INVALID_VALUE;
}
std::vector<std::string> types = GetFileTypes(*uri, mimeTypeFilter);
if (!reply.WriteStringVector(types)) {
LOG_ERROR("fail to WriteStringVector types");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdOpenFile(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::string mode = data.ReadString();
if (mode.empty()) {
LOG_ERROR("DataShareStub mode is nullptr");
return ERR_INVALID_VALUE;
}
int fd = OpenFile(*uri, mode);
if (fd < 0) {
LOG_ERROR("OpenFile fail, fd is %{pubilc}d", fd);
return ERR_INVALID_VALUE;
}
if (!reply.WriteFileDescriptor(fd)) {
LOG_ERROR("fail to WriteFileDescriptor fd");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdOpenRawFile(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::string mode = data.ReadString();
if (mode.empty()) {
LOG_ERROR("DataShareStub mode is nullptr");
return ERR_INVALID_VALUE;
}
int fd = OpenRawFile(*uri, mode);
if (!reply.WriteInt32(fd)) {
LOG_ERROR("fail to WriteInt32 fd");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdInsert(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::shared_ptr<DataShareValuesBucket> value(DataShareValuesBucket::Unmarshalling(data));
if (value == nullptr) {
LOG_ERROR("ReadParcelable value is nullptr");
return ERR_INVALID_VALUE;
}
int index = Insert(*uri, *value);
if (!reply.WriteInt32(index)) {
LOG_ERROR("fail to WriteInt32 index");
return ERR_INVALID_VALUE;
}
LOG_INFO("DataShareStub::CmdInsertInner end");
return NO_ERROR;
}
ErrCode DataShareStub::CmdUpdate(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::shared_ptr<DataSharePredicates> predicates(
data.ReadParcelable<DataSharePredicates>());
if (predicates == nullptr) {
LOG_ERROR("ReadParcelable predicates is nullptr");
return ERR_INVALID_VALUE;
}
std::shared_ptr<DataShareValuesBucket> value(DataShareValuesBucket::Unmarshalling(data));
if (value == nullptr) {
LOG_ERROR("ReadParcelable value is nullptr");
return ERR_INVALID_VALUE;
}
int index = Update(*uri, *predicates, *value);
if (!reply.WriteInt32(index)) {
LOG_ERROR("fail to WriteInt32 index");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdDelete(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::shared_ptr<DataSharePredicates> predicates(
data.ReadParcelable<DataSharePredicates>());
if (predicates == nullptr) {
LOG_ERROR("ReadParcelable predicates is nullptr");
return ERR_INVALID_VALUE;
}
int index = Delete(*uri, *predicates);
if (!reply.WriteInt32(index)) {
LOG_ERROR("fail to WriteInt32 index");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdQuery(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::shared_ptr<DataSharePredicates> predicates(
data.ReadParcelable<DataSharePredicates>());
if (predicates == nullptr) {
LOG_ERROR("ReadParcelable predicates is nullptr");
return ERR_INVALID_VALUE;
}
std::vector<std::string> columns;
if (!data.ReadStringVector(&columns)) {
LOG_ERROR("fail to ReadStringVector columns");
return ERR_INVALID_VALUE;
}
auto resultSet = Query(*uri, *predicates, columns);
if (resultSet == nullptr) {
LOG_ERROR("fail to WriteParcelable resultSet");
return ERR_INVALID_VALUE;
}
auto result = ISharedResultSet::WriteToParcel(std::move(resultSet), reply);
if (result == nullptr) {
LOG_ERROR("!resultSet->Marshalling(reply)");
return ERR_INVALID_VALUE;
}
LOG_INFO("DataShareStub::CmdQueryInner end");
return NO_ERROR;
}
ErrCode DataShareStub::CmdGetType(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
std::string type = GetType(*uri);
if (!reply.WriteString(type)) {
LOG_ERROR("fail to WriteString type");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdBatchInsert(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
int count = 0;
if (!data.ReadInt32(count)) {
LOG_ERROR("fail to ReadInt32 index");
return ERR_INVALID_VALUE;
}
std::vector<DataShareValuesBucket> values;
for (int i = 0; i < count; i++) {
std::unique_ptr<DataShareValuesBucket> value(DataShareValuesBucket::Unmarshalling(data));
if (value == nullptr) {
LOG_ERROR("DataShareStub value is nullptr, index = %{public}d", i);
return ERR_INVALID_VALUE;
}
values.emplace_back(*value);
}
int ret = BatchInsert(*uri, values);
if (!reply.WriteInt32(ret)) {
LOG_ERROR("fail to WriteInt32 ret");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdRegisterObserver(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
auto obServer = iface_cast<AAFwk::IDataAbilityObserver>(data.ReadRemoteObject());
if (obServer == nullptr) {
LOG_ERROR("DataShareStub obServer is nullptr");
return ERR_INVALID_VALUE;
}
bool ret = RegisterObserver(*uri, obServer);
if (!reply.WriteInt32(ret)) {
LOG_ERROR("fail to WriteInt32 ret");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
auto obServer = iface_cast<AAFwk::IDataAbilityObserver>(data.ReadRemoteObject());
if (obServer == nullptr) {
LOG_ERROR("DataShareStub obServer is nullptr");
return ERR_INVALID_VALUE;
}
bool ret = UnregisterObserver(*uri, obServer);
if (!reply.WriteInt32(ret)) {
LOG_ERROR("fail to WriteInt32 ret");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdNotifyChange(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
bool ret = NotifyChange(*uri);
if (!reply.WriteInt32(ret)) {
LOG_ERROR("fail to WriteInt32 ret");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdNormalizeUri(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
Uri ret("");
ret = NormalizeUri(*uri);
if (!reply.WriteParcelable(&ret)) {
LOG_ERROR("fail to WriteParcelable type");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply)
{
std::shared_ptr<Uri> uri(data.ReadParcelable<Uri>());
if (uri == nullptr) {
LOG_ERROR("DataShareStub uri is nullptr");
return ERR_INVALID_VALUE;
}
Uri ret("");
ret = DenormalizeUri(*uri);
if (!reply.WriteParcelable(&ret)) {
LOG_ERROR("fail to WriteParcelable type");
return ERR_INVALID_VALUE;
}
return NO_ERROR;
}
ErrCode DataShareStub::CmdExecuteBatch(MessageParcel &data, MessageParcel &reply)
{
LOG_INFO("DataShareStub::CmdExecuteBatchInner start");
int count = 0;
if (!data.ReadInt32(count)) {
LOG_ERROR("DataShareStub::CmdExecuteBatchInner fail to ReadInt32 count");
return ERR_INVALID_VALUE;
}
LOG_INFO("DataShareStub::CmdExecuteBatchInner count:%{public}d", count);
std::vector<std::shared_ptr<DataShareOperation>> operations;
for (int i = 0; i < count; i++) {
DataShareOperation *operation = data.ReadParcelable<DataShareOperation>();
if (operation == nullptr) {
LOG_ERROR("DataShareStub::CmdExecuteBatchInner operation is nullptr, index = %{public}d", i);
return ERR_INVALID_VALUE;
}
std::shared_ptr<DataShareOperation> dataShareOperation(operation);
operations.push_back(dataShareOperation);
}
std::vector<std::shared_ptr<DataShareResult>> results = ExecuteBatch(operations);
int total = (int)(results.size());
if (!reply.WriteInt32(total)) {
LOG_ERROR("DataShareStub::CmdExecuteBatchInner fail to WriteInt32 ret");
return ERR_INVALID_VALUE;
}
LOG_INFO("DataShareStub::CmdExecuteBatchInner total:%{public}d", total);
for (int i = 0; i < total; i++) {
if (results[i] == nullptr) {
LOG_ERROR("DataShareStub::CmdExecuteBatchInner results[i] is nullptr, index = %{public}d", i);
return ERR_INVALID_VALUE;
}
if (!reply.WriteParcelable(results[i].get())) {
LOG_ERROR(
"DataShareStub::CmdExecuteBatchInner fail to WriteParcelable operation, index = %{public}d", i);
return ERR_INVALID_VALUE;
}
}
LOG_INFO("DataShareStub::CmdExecuteBatchInner end");
return NO_ERROR;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,382 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_stub_impl.h"
#include "datashare_log.h"
namespace OHOS {
namespace DataShare {
constexpr int DEFAULT_NUMBER = -1;
std::shared_ptr<JsDataShareExtAbility> DataShareStubImpl::GetOwner()
{
return extension_;
}
std::vector<std::string> DataShareStubImpl::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
LOG_INFO("begin.");
std::vector<std::string> ret;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->GetFileTypes(uri, mimeTypeFilter);
};
std::function<bool()> getRetFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(ret);
return (ret.size() != 0);
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return ret;
}
int DataShareStubImpl::OpenFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
int ret = -1;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->OpenFile(uri, mode);
};
std::function<bool()> getRetFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(ret);
return (ret != DEFAULT_NUMBER);
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return ret;
}
int DataShareStubImpl::OpenRawFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
int ret = -1;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->OpenRawFile(uri, mode);
};
uvQueue_->SyncCall(syncTaskFunc);
LOG_INFO("end successfully.");
return ret;
}
int DataShareStubImpl::Insert(const Uri &uri, const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
int ret = 0;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->Insert(uri, value);
};
std::function<bool()> getRetFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(ret);
return (ret != DEFAULT_NUMBER);
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return ret;
}
int DataShareStubImpl::Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
int ret = 0;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->Update(uri, predicates, value);
};
std::function<bool()> getRetFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(ret);
return (ret != DEFAULT_NUMBER);
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return ret;
}
int DataShareStubImpl::Delete(const Uri &uri, const DataSharePredicates &predicates)
{
LOG_INFO("begin.");
int ret = 0;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->Delete(uri, predicates);
};
std::function<bool()> getRetFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(ret);
return (ret != DEFAULT_NUMBER);
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return ret;
}
std::shared_ptr<DataShareResultSet> DataShareStubImpl::Query(const Uri &uri,
const DataSharePredicates &predicates, std::vector<std::string> &columns)
{
LOG_INFO("begin.");
std::shared_ptr<DataShareResultSet> resultSet = nullptr;
std::function<void()> syncTaskFunc = [=, &columns, &resultSet, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
resultSet = extension->Query(uri, predicates, columns);
};
std::function<bool()> getRetFunc = [=, &resultSet, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(resultSet);
return (resultSet != nullptr);
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return resultSet;
}
std::string DataShareStubImpl::GetType(const Uri &uri)
{
LOG_INFO("begin.");
std::string ret = "";
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->GetType(uri);
};
std::function<bool()> getRetFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(ret);
return (ret != "");
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return ret;
}
int DataShareStubImpl::BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values)
{
LOG_INFO("begin.");
int ret = 0;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->BatchInsert(uri, values);
};
std::function<bool()> getRetFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
extension->GetResult(ret);
return (ret != DEFAULT_NUMBER);
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return ret;
}
bool DataShareStubImpl::RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
bool ret = false;
std::function<void()> syncTaskFunc = [=, &dataObserver, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->RegisterObserver(uri, dataObserver);
};
uvQueue_->SyncCall(syncTaskFunc);
LOG_INFO("end successfully.");
return ret;
}
bool DataShareStubImpl::UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
bool ret = false;
std::function<void()> syncTaskFunc = [=, &dataObserver, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->UnregisterObserver(uri, dataObserver);
};
uvQueue_->SyncCall(syncTaskFunc);
LOG_INFO("end successfully.");
return ret;
}
bool DataShareStubImpl::NotifyChange(const Uri &uri)
{
LOG_INFO("begin.");
bool ret = false;
std::function<void()> syncTaskFunc = [=, &ret, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
ret = extension->NotifyChange(uri);
};
uvQueue_->SyncCall(syncTaskFunc);
LOG_INFO("end successfully.");
return ret;
}
Uri DataShareStubImpl::NormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
Uri urivalue("");
std::function<void()> syncTaskFunc = [=, &urivalue, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
urivalue = extension->NormalizeUri(uri);
};
std::function<bool()> getRetFunc = [=, &urivalue, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
std::string ret;
extension->GetResult(ret);
Uri tmp(ret);
urivalue = tmp;
return (urivalue.ToString() != "");
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return urivalue;
}
Uri DataShareStubImpl::DenormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
Uri urivalue("");
std::function<void()> syncTaskFunc = [=, &urivalue, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
urivalue = extension->DenormalizeUri(uri);
};
std::function<bool()> getRetFunc = [=, &urivalue, client = sptr<DataShareStubImpl>(this)]() -> bool {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return false;
}
std::string ret;
extension->GetResult(ret);
Uri tmp(ret);
urivalue = tmp;
return (urivalue.ToString() != "");
};
uvQueue_->SyncCall(syncTaskFunc, getRetFunc);
LOG_INFO("end successfully.");
return urivalue;
}
std::vector<std::shared_ptr<DataShareResult>> DataShareStubImpl::ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations)
{
LOG_INFO("begin.");
std::vector<std::shared_ptr<DataShareResult>> results;
std::function<void()> syncTaskFunc = [=, &results, client = sptr<DataShareStubImpl>(this)]() {
auto extension = client->GetOwner();
if (extension == nullptr) {
LOG_ERROR("%{public}s end failed.", __func__);
return;
}
results = extension->ExecuteBatch(operations);
};
uvQueue_->SyncCall(syncTaskFunc);
LOG_INFO("end successfully.");
return results;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,116 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "datashare_uv_queue.h"
#include <thread>
#include "datashare_log.h"
namespace OHOS {
namespace DataShare {
constexpr int WAIT_TIME = 3;
constexpr int SLEEP_TIME = 100;
constexpr int TRY_TIMES = 20;
DataShareUvQueue::DataShareUvQueue(napi_env env)
: env_(env)
{
napi_get_uv_event_loop(env, &loop_);
}
void DataShareUvQueue::SyncCall(NapiVoidFunc func, NapiBoolFunc retFunc)
{
LOG_INFO("begin.");
uv_work_t* work = new (std::nothrow) uv_work_t;
if (work == nullptr) {
return;
}
work->data = new UvEntry {env_, std::move(func), false, false, {}, {}, std::move(retFunc)};
auto status = uv_queue_work(
loop_, work, [](uv_work_t* work) {},
[](uv_work_t* work, int uvstatus) {
if (work == nullptr || work->data == nullptr) {
LOG_ERROR("%{public}s invalid work or work->data.", __func__);
return;
}
auto *entry = static_cast<UvEntry*>(work->data);
std::unique_lock<std::mutex> lock(entry->mutex);
if (entry->func) {
entry->func();
}
entry->done = true;
if (entry->purge) {
DataShareUvQueue::Purge(work);
} else {
entry->condition.notify_all();
}
});
if (status != napi_ok) {
LOG_ERROR("%{public}s queue work failed", __func__);
DataShareUvQueue::Purge(work);
return;
}
bool noNeedPurge = false;
auto *uvEntry = static_cast<UvEntry*>(work->data);
{
std::unique_lock<std::mutex> lock(uvEntry->mutex);
if (uvEntry->condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [uvEntry] { return uvEntry->done; })) {
LOG_INFO("Wait uv_queue_work timeout.");
}
CheckFuncAndExec(uvEntry->retFunc);
if (!uvEntry->done && !uv_cancel((uv_req_t*)&work)) {
LOG_ERROR("%{public}s uv_cancel failed.", __func__);
uvEntry->purge = true;
noNeedPurge = true;
}
}
if (!noNeedPurge) {
DataShareUvQueue::Purge(work);
}
LOG_INFO("end.");
}
void DataShareUvQueue::Purge(uv_work_t* work)
{
LOG_INFO("begin.");
if (work == nullptr || work->data == nullptr) {
LOG_ERROR("%{public}s invalid work or work->data.", __func__);
return;
}
auto *entry = static_cast<UvEntry*>(work->data);
std::unique_lock<std::mutex> lock(entry->mutex);
delete entry;
entry = nullptr;
delete work;
work = nullptr;
LOG_INFO("end.");
}
void DataShareUvQueue::CheckFuncAndExec(NapiBoolFunc retFunc)
{
if (retFunc) {
int tryTimes = TRY_TIMES;
while (retFunc() != true && tryTimes > 0) {
LOG_DEBUG("tryTimes : %{public}d.", tryTimes);
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME));
tryTimes--;
}
}
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,831 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "js_datashare_ext_ability.h"
#include "ability_info.h"
#include "accesstoken_kit.h"
#include "dataobs_mgr_client.h"
#include "datashare_stub_impl.h"
#include "datashare_log.h"
#include "ipc_skeleton.h"
#include "js_datashare_ext_ability_context.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "napi_common_util.h"
#include "napi_common_want.h"
#include "napi_remote_object.h"
#include "napi_datashare_values_bucket.h"
#include "datashare_predicates_proxy.h"
namespace OHOS {
namespace DataShare {
using namespace AbilityRuntime;
namespace {
constexpr size_t ARGC_ONE = 1;
constexpr size_t ARGC_TWO = 2;
constexpr size_t ARGC_THREE = 3;
constexpr int INVALID_VALUE = -1;
const std::string ASYNC_CALLBACK_NAME = "AsyncCallback";
}
bool MakeNapiColumn(napi_env env, napi_value &napiColumns, const std::vector<std::string> &columns);
using namespace OHOS::AppExecFwk;
using OHOS::Security::AccessToken::AccessTokenKit;
using DataObsMgrClient = OHOS::AAFwk::DataObsMgrClient;
JsDataShareExtAbility* JsDataShareExtAbility::Create(const std::unique_ptr<Runtime>& runtime)
{
return new JsDataShareExtAbility(static_cast<JsRuntime&>(*runtime));
}
JsDataShareExtAbility::JsDataShareExtAbility(JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {}
JsDataShareExtAbility::~JsDataShareExtAbility() {}
void JsDataShareExtAbility::Init(const std::shared_ptr<AbilityLocalRecord> &record,
const std::shared_ptr<OHOSApplication> &application, std::shared_ptr<AbilityHandler> &handler,
const sptr<IRemoteObject> &token)
{
DataShareExtAbility::Init(record, application, handler, token);
std::string srcPath = "";
GetSrcPath(srcPath);
if (srcPath.empty()) {
LOG_ERROR("Failed to get srcPath");
return;
}
std::string moduleName(Extension::abilityInfo_->moduleName);
moduleName.append("::").append(abilityInfo_->name);
LOG_INFO("module:%{public}s, srcPath:%{public}s.", moduleName.c_str(), srcPath.c_str());
HandleScope handleScope(jsRuntime_);
auto& engine = jsRuntime_.GetNativeEngine();
jsObj_ = jsRuntime_.LoadModule(moduleName, srcPath);
if (jsObj_ == nullptr) {
LOG_ERROR("Failed to get jsObj_");
return;
}
LOG_INFO("JsDataShareExtAbility::Init ConvertNativeValueTo.");
NativeObject* obj = ConvertNativeValueTo<NativeObject>(jsObj_->Get());
if (obj == nullptr) {
LOG_ERROR("Failed to get JsDataShareExtAbility object");
return;
}
auto context = GetContext();
if (context == nullptr) {
LOG_ERROR("Failed to get context");
return;
}
LOG_INFO("JsDataShareExtAbility::Init CreateJsDataShareExtAbilityContext.");
NativeValue* contextObj = CreateJsDataShareExtAbilityContext(engine, context);
auto contextRef = jsRuntime_.LoadSystemModule("application.DataShareExtensionAbilityContext",
&contextObj, ARGC_ONE);
contextObj = contextRef->Get();
LOG_INFO("JsDataShareExtAbility::Init Bind.");
context->Bind(jsRuntime_, contextRef.release());
LOG_INFO("JsDataShareExtAbility::SetProperty.");
obj->SetProperty("context", contextObj);
auto nativeObj = ConvertNativeValueTo<NativeObject>(contextObj);
if (nativeObj == nullptr) {
LOG_ERROR("Failed to get datashare extension ability native object");
return;
}
LOG_INFO("Set datashare extension ability context pointer is nullptr: %{public}d", context.get() == nullptr);
nativeObj->SetNativePointer(new std::weak_ptr<AbilityRuntime::Context>(context),
[](NativeEngine*, void* data, void*) {
LOG_INFO("Finalizer for weak_ptr datashare extension ability context is called");
delete static_cast<std::weak_ptr<AbilityRuntime::Context>*>(data);
}, nullptr);
LOG_INFO("JsDataShareExtAbility::Init end.");
}
void JsDataShareExtAbility::OnStart(const AAFwk::Want &want)
{
LOG_INFO("begin.");
Extension::OnStart(want);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want);
NativeValue* nativeWant = reinterpret_cast<NativeValue*>(napiWant);
NativeValue* argv[] = {nativeWant};
CallObjectMethod("onCreate", argv, ARGC_ONE);
LOG_INFO("end.");
}
sptr<IRemoteObject> JsDataShareExtAbility::OnConnect(const AAFwk::Want &want)
{
LOG_INFO("begin.");
Extension::OnConnect(want);
sptr<DataShareStubImpl> remoteObject = new (std::nothrow) DataShareStubImpl(
std::static_pointer_cast<JsDataShareExtAbility>(shared_from_this()),
reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine()));
if (remoteObject == nullptr) {
LOG_ERROR("%{public}s No memory allocated for DataShareStubImpl", __func__);
return nullptr;
}
LOG_INFO("end.");
return remoteObject->AsObject();
}
void JsDataShareExtAbility::CheckAndSetAsyncResult(NativeEngine* engine)
{
auto result = GetAsyncResult();
auto type = result->TypeOf();
LOG_DEBUG("type : %{public}d", type);
if (type == NATIVE_NUMBER) {
int32_t value = OHOS::AppExecFwk::UnwrapInt32FromJS(reinterpret_cast<napi_env>(engine),
reinterpret_cast<napi_value>(result));
SetResult(value);
} else if (type == NATIVE_STRING) {
std::string value = OHOS::AppExecFwk::UnwrapStringFromJS(reinterpret_cast<napi_env>(engine),
reinterpret_cast<napi_value>(result));
SetResult(value);
} else if (type == NATIVE_OBJECT) {
ResultSetBridge::Creator *proxy = nullptr;
napi_unwrap(reinterpret_cast<napi_env>(engine), reinterpret_cast<napi_value>(result),
reinterpret_cast<void **>(&proxy));
if (proxy == nullptr) {
LOG_DEBUG("proxy == nullptr. STRARR.");
std::vector<std::string> value;
OHOS::AppExecFwk::UnwrapArrayStringFromJS(reinterpret_cast<napi_env>(engine),
reinterpret_cast<napi_value>(result), value);
SetResult(value);
} else {
std::shared_ptr<ResultSetBridge> value = proxy->Create();
std::shared_ptr<DataShareResultSet> resultSet = std::make_shared<DataShareResultSet>(value);
SetResult(resultSet);
}
} else {
callbackResultNumber_ = -1;
callbackResultString_ = "";
callbackResultStringArr_ = {};
callbackResultObject_ = nullptr;
}
}
NativeValue* JsDataShareExtAbility::AsyncCallback(NativeEngine* engine, NativeCallbackInfo* info)
{
LOG_INFO("engine == nullptr : %{public}d, info == nullptr : %{public}d.", engine == nullptr, info == nullptr);
if (engine == nullptr || info == nullptr) {
LOG_ERROR("%{public}s invalid param.", __func__);
return nullptr;
}
if (info->argc < ARGC_TWO || info->argv[0] == nullptr || info->argv[1] == nullptr) {
LOG_ERROR("%{public}s invalid args.", __func__);
return engine->CreateUndefined();
}
int32_t value = -1;
if ((info->argv[0])->TypeOf() == NATIVE_NUMBER) {
value = OHOS::AppExecFwk::UnwrapInt32FromJS(reinterpret_cast<napi_env>(engine),
reinterpret_cast<napi_value>(info->argv[0]));
LOG_INFO("%{public}s value_number : %{public}d.", __func__, value);
}
if (info->functionInfo == nullptr || info->functionInfo->data == nullptr) {
LOG_ERROR("%{public}s invalid object.", __func__);
return engine->CreateUndefined();
}
JsDataShareExtAbility* instance = static_cast<JsDataShareExtAbility*>(info->functionInfo->data);
if (instance != nullptr) {
instance->SetBlockWaiting(true);
instance->SetAsyncResult(info->argv[1]);
instance->CheckAndSetAsyncResult(engine);
}
LOG_INFO("%{public}s end.", __func__);
return engine->CreateUndefined();
}
NativeValue* JsDataShareExtAbility::CallObjectMethod(const char* name, NativeValue* const* argv, size_t argc,
bool isAsync)
{
LOG_INFO("JsDataShareExtAbility::CallObjectMethod(%{public}s), begin", name);
if (!jsObj_) {
LOG_WARN("Not found DataShareExtAbility.js");
return nullptr;
}
HandleScope handleScope(jsRuntime_);
auto& nativeEngine = jsRuntime_.GetNativeEngine();
NativeValue* value = jsObj_->Get();
NativeObject* obj = ConvertNativeValueTo<NativeObject>(value);
if (obj == nullptr) {
LOG_ERROR("Failed to get DataShareExtAbility object");
return nullptr;
}
NativeValue* method = obj->GetProperty(name);
if (method == nullptr) {
LOG_ERROR("Failed to get '%{public}s' from DataShareExtAbility object", name);
return nullptr;
}
size_t count = argc + 1;
NativeValue **args = new NativeValue *[count];
for (size_t i = 0; i < argc; i++) {
args[i] = argv[i];
}
if (isAsync) {
callbackResultNumber_ = -1;
callbackResultString_ = "";
callbackResultStringArr_ = {};
callbackResultObject_ = nullptr;
args[argc] = nativeEngine.CreateFunction(ASYNC_CALLBACK_NAME.c_str(),
ASYNC_CALLBACK_NAME.length(), JsDataShareExtAbility::AsyncCallback, this);
LOG_INFO("AsyncType::ASYNC_COMMON.");
} else {
args[argc] = nullptr;
}
SetBlockWaiting(false);
LOG_INFO("%{public}s(%{public}s) end", __func__, name);
return handleScope.Escape(nativeEngine.CallFunction(value, method, args, count));
}
void JsDataShareExtAbility::GetSrcPath(std::string &srcPath)
{
if (!Extension::abilityInfo_->isStageBasedModel) {
/* temporary compatibility api8 + config.json */
srcPath.append(Extension::abilityInfo_->package);
srcPath.append("/assets/js/");
if (!Extension::abilityInfo_->srcPath.empty()) {
srcPath.append(Extension::abilityInfo_->srcPath);
}
srcPath.append("/").append(Extension::abilityInfo_->name).append(".abc");
return;
}
if (!Extension::abilityInfo_->srcEntrance.empty()) {
srcPath.append(Extension::abilityInfo_->moduleName + "/");
srcPath.append(Extension::abilityInfo_->srcEntrance);
srcPath.erase(srcPath.rfind('.'));
srcPath.append(".abc");
}
}
std::vector<std::string> JsDataShareExtAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter)
{
LOG_INFO("begin.");
auto ret = DataShareExtAbility::GetFileTypes(uri, mimeTypeFilter);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiMimeTypeFilter = nullptr;
status = napi_create_string_utf8(env, mimeTypeFilter.c_str(), NAPI_AUTO_LENGTH, &napiMimeTypeFilter);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativeMimeTypeFilter = reinterpret_cast<NativeValue*>(napiMimeTypeFilter);
NativeValue* argv[] = {nativeUri, nativeMimeTypeFilter};
NativeValue* nativeResult = CallObjectMethod("getFileTypes", argv, ARGC_TWO);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call getFileTypes with return null.", __func__);
return ret;
}
if (!OHOS::AppExecFwk::UnwrapArrayStringFromJS(env, reinterpret_cast<napi_value>(nativeResult), ret)) {
LOG_ERROR("%{public}s call UnwrapArrayStringFromJS failed", __func__);
return ret;
}
LOG_INFO("end.");
return ret;
}
int JsDataShareExtAbility::OpenFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
auto ret = DataShareExtAbility::OpenFile(uri, mode);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiMode = nullptr;
status = napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativeMode = reinterpret_cast<NativeValue*>(napiMode);
NativeValue* argv[] = {nativeUri, nativeMode};
NativeValue* nativeResult = CallObjectMethod("openFile", argv, ARGC_TWO);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call openFile with return null.", __func__);
return ret;
}
ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast<napi_value>(nativeResult));
LOG_INFO("end.");
return ret;
}
int JsDataShareExtAbility::OpenRawFile(const Uri &uri, const std::string &mode)
{
LOG_INFO("begin.");
auto ret = DataShareExtAbility::OpenRawFile(uri, mode);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiMode = nullptr;
status = napi_create_string_utf8(env, mode.c_str(), NAPI_AUTO_LENGTH, &napiMode);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativeMode = reinterpret_cast<NativeValue*>(napiMode);
NativeValue* argv[] = {nativeUri, nativeMode};
NativeValue* nativeResult = CallObjectMethod("openRawFile", argv, ARGC_TWO, false);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call openRawFile with return null.", __func__);
return ret;
}
ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast<napi_value>(nativeResult));
LOG_INFO("end.");
return ret;
}
int JsDataShareExtAbility::Insert(const Uri &uri, const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
int ret = INVALID_VALUE;
if (!CheckCallingPermission(abilityInfo_->writePermission)) {
LOG_ERROR("%{public}s Check calling permission failed.", __func__);
return ret;
}
ret = DataShareExtAbility::Insert(uri, value);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiValue = DataShareValueBucketNewInstance(env, const_cast<DataShareValuesBucket&>(value));
if (napiValue == nullptr) {
LOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativeValue = reinterpret_cast<NativeValue*>(napiValue);
NativeValue* argv[] = {nativeUri, nativeValue};
NativeValue* nativeResult = CallObjectMethod("insert", argv, ARGC_TWO);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call insert with return null.", __func__);
return ret;
}
ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast<napi_value>(nativeResult));
LOG_INFO("end.");
return ret;
}
int JsDataShareExtAbility::Update(const Uri &uri, const DataSharePredicates &predicates,
const DataShareValuesBucket &value)
{
LOG_INFO("begin.");
int ret = INVALID_VALUE;
if (!CheckCallingPermission(abilityInfo_->writePermission)) {
LOG_ERROR("%{public}s Check calling permission failed.", __func__);
return ret;
}
ret = DataShareExtAbility::Update(uri, predicates, value);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiPredicates = MakePredicates(env, predicates);
if (napiPredicates == nullptr) {
LOG_DEBUG("%{public}s failed to make new instance of dataSharePredicates.", __func__);
return ret;
}
napi_value napiValue = DataShareValueBucketNewInstance(env, const_cast<DataShareValuesBucket&>(value));
if (napiValue == nullptr) {
LOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativePredicates = reinterpret_cast<NativeValue*>(napiPredicates);
NativeValue* nativeValue = reinterpret_cast<NativeValue*>(napiValue);
NativeValue* argv[] = {nativeUri, nativePredicates, nativeValue};
NativeValue* nativeResult = CallObjectMethod("update", argv, ARGC_THREE);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call update with return null.", __func__);
return ret;
}
ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast<napi_value>(nativeResult));
LOG_INFO("end.");
return ret;
}
int JsDataShareExtAbility::Delete(const Uri &uri, const DataSharePredicates &predicates)
{
LOG_INFO("begin.");
int ret = INVALID_VALUE;
if (!CheckCallingPermission(abilityInfo_->writePermission)) {
LOG_ERROR("%{public}s Check calling permission failed.", __func__);
return ret;
}
ret = DataShareExtAbility::Delete(uri, predicates);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiPredicates = MakePredicates(env, predicates);
if (napiPredicates == nullptr) {
LOG_DEBUG("%{public}s failed to make new instance of dataSharePredicates.", __func__);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativePredicates = reinterpret_cast<NativeValue*>(napiPredicates);
NativeValue* argv[] = {nativeUri, nativePredicates};
NativeValue* nativeResult = CallObjectMethod("delete", argv, ARGC_TWO);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call delete with return null.", __func__);
return ret;
}
ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast<napi_value>(nativeResult));
LOG_INFO("end.");
return ret;
}
std::shared_ptr<DataShareResultSet> JsDataShareExtAbility::Query(const Uri &uri,
const DataSharePredicates &predicates, std::vector<std::string> &columns)
{
LOG_INFO("begin.");
std::shared_ptr<DataShareResultSet> ret;
if (!CheckCallingPermission(abilityInfo_->readPermission)) {
LOG_ERROR("%{public}s Check calling permission failed.", __func__);
return ret;
}
ret = DataShareExtAbility::Query(uri, predicates, columns);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiPredicates = MakePredicates(env, predicates);
if (napiPredicates == nullptr) {
LOG_DEBUG("%{public}s failed to make new instance of dataSharePredicates.", __func__);
return ret;
}
napi_value napiColumns = nullptr;
if (!MakeNapiColumn(env, napiColumns, columns)) {
LOG_ERROR("MakeNapiColumn failed");
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativePredicates = reinterpret_cast<NativeValue*>(napiPredicates);
NativeValue* nativeColumns = reinterpret_cast<NativeValue*>(napiColumns);
NativeValue* argv[] = {nativeUri, nativePredicates, nativeColumns};
NativeValue* nativeResult = CallObjectMethod("query", argv, ARGC_THREE);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call query with return null.", __func__);
return ret;
}
ResultSetBridge::Creator *proxy = nullptr;
napi_unwrap(env, reinterpret_cast<napi_value>(nativeResult), reinterpret_cast<void **>(&proxy));
if (proxy == nullptr) {
LOG_ERROR("unwrap ResultSetBridge::Creator proxy is null.");
return nullptr;
}
std::shared_ptr<ResultSetBridge> bridge = proxy->Create();
LOG_INFO("ret == nullptr : %{public}d.", bridge == nullptr);
std::shared_ptr<DataShareResultSet> resultSet = std::make_shared<DataShareResultSet>(bridge);
return resultSet;
}
std::string JsDataShareExtAbility::GetType(const Uri &uri)
{
LOG_INFO("begin.");
auto ret = DataShareExtAbility::GetType(uri);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* argv[] = {nativeUri};
NativeValue* nativeResult = CallObjectMethod("getType", argv, ARGC_ONE);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call getType with return null.", __func__);
return ret;
}
ret = OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast<napi_value>(nativeResult));
LOG_INFO("end.");
return ret;
}
int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector<DataShareValuesBucket> &values)
{
LOG_INFO("begin.");
int ret = INVALID_VALUE;
if (!CheckCallingPermission(abilityInfo_->writePermission)) {
LOG_ERROR("%{public}s Check calling permission failed.", __func__);
return ret;
}
ret = DataShareExtAbility::BatchInsert(uri, values);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
napi_value napiValues = nullptr;
status = napi_create_array(env, &napiValues);
if (status != napi_ok) {
LOG_ERROR("napi_create_array status : %{public}d", status);
return ret;
}
bool isArray = false;
if (napi_is_array(env, napiValues, &isArray) != napi_ok || !isArray) {
LOG_ERROR("JsDataShareExtAbility create array failed");
return ret;
}
int32_t index = 0;
for (const auto &value : values) {
napi_value result = DataShareValueBucketNewInstance(env, const_cast<DataShareValuesBucket&>(value));
if (result == nullptr) {
LOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__);
return ret;
}
napi_set_element(env, napiValues, index++, result);
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* nativeValues = reinterpret_cast<NativeValue*>(napiValues);
NativeValue* argv[] = {nativeUri, nativeValues};
NativeValue* nativeResult = CallObjectMethod("batchInsert", argv, ARGC_TWO);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call batchInsert with return null.", __func__);
return ret;
}
ret = OHOS::AppExecFwk::UnwrapInt32FromJS(env, reinterpret_cast<napi_value>(nativeResult));
LOG_INFO("end.");
return ret;
}
bool JsDataShareExtAbility::RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
DataShareExtAbility::RegisterObserver(uri, dataObserver);
auto obsMgrClient = DataObsMgrClient::GetInstance();
if (obsMgrClient == nullptr) {
LOG_ERROR("%{public}s obsMgrClient is nullptr", __func__);
return false;
}
ErrCode ret = obsMgrClient->RegisterObserver(uri, dataObserver);
if (ret != ERR_OK) {
LOG_ERROR("%{public}s obsMgrClient->RegisterObserver error return %{public}d", __func__, ret);
return false;
}
LOG_INFO("end.");
return true;
}
bool JsDataShareExtAbility::UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver)
{
LOG_INFO("begin.");
DataShareExtAbility::UnregisterObserver(uri, dataObserver);
auto obsMgrClient = DataObsMgrClient::GetInstance();
if (obsMgrClient == nullptr) {
LOG_ERROR("%{public}s obsMgrClient is nullptr", __func__);
return false;
}
ErrCode ret = obsMgrClient->UnregisterObserver(uri, dataObserver);
if (ret != ERR_OK) {
LOG_ERROR("%{public}s obsMgrClient->UnregisterObserver error return %{public}d", __func__, ret);
return false;
}
LOG_INFO("end.");
return true;
}
bool JsDataShareExtAbility::NotifyChange(const Uri &uri)
{
LOG_INFO("begin.");
DataShareExtAbility::NotifyChange(uri);
auto obsMgrClient = DataObsMgrClient::GetInstance();
if (obsMgrClient == nullptr) {
LOG_ERROR("%{public}s obsMgrClient is nullptr", __func__);
return false;
}
ErrCode ret = obsMgrClient->NotifyChange(uri);
if (ret != ERR_OK) {
LOG_ERROR("%{public}s obsMgrClient->NotifyChange error return %{public}d", __func__, ret);
return false;
}
LOG_INFO("end.");
return true;
}
Uri JsDataShareExtAbility::NormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
auto ret = DataShareExtAbility::NormalizeUri(uri);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* argv[] = {nativeUri};
NativeValue* nativeResult = CallObjectMethod("normalizeUri", argv, ARGC_ONE);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call normalizeUri with return null.", __func__);
return ret;
}
ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast<napi_value>(nativeResult)));
LOG_INFO("end.");
return ret;
}
Uri JsDataShareExtAbility::DenormalizeUri(const Uri &uri)
{
LOG_INFO("begin.");
auto ret = DataShareExtAbility::DenormalizeUri(uri);
HandleScope handleScope(jsRuntime_);
napi_env env = reinterpret_cast<napi_env>(&jsRuntime_.GetNativeEngine());
napi_value napiUri = nullptr;
napi_status status = napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri);
if (status != napi_ok) {
LOG_ERROR("napi_create_string_utf8 status : %{public}d", status);
return ret;
}
NativeValue* nativeUri = reinterpret_cast<NativeValue*>(napiUri);
NativeValue* argv[] = {nativeUri};
NativeValue* nativeResult = CallObjectMethod("denormalizeUri", argv, ARGC_ONE);
if (nativeResult == nullptr) {
LOG_ERROR("%{public}s call denormalizeUri with return null.", __func__);
return ret;
}
ret = Uri(OHOS::AppExecFwk::UnwrapStringFromJS(env, reinterpret_cast<napi_value>(nativeResult)));
LOG_INFO("end.");
return ret;
}
std::vector<std::shared_ptr<DataShareResult>> JsDataShareExtAbility::ExecuteBatch(
const std::vector<std::shared_ptr<DataShareOperation>> &operations)
{
LOG_INFO("begin.");
auto ret = DataShareExtAbility::ExecuteBatch(operations);
LOG_INFO("end.");
return ret;
}
bool JsDataShareExtAbility::CheckCallingPermission(const std::string &permission)
{
LOG_INFO("begin, permission:%{public}s", permission.c_str());
if (!permission.empty() && AccessTokenKit::VerifyAccessToken(IPCSkeleton::GetCallingTokenID(), permission)
!= AppExecFwk::Constants::PERMISSION_GRANTED) {
LOG_ERROR("%{public}s permission not granted.", __func__);
return false;
}
LOG_INFO("end.");
return true;
}
napi_value JsDataShareExtAbility::MakePredicates(napi_env env, const DataSharePredicates &predicates)
{
LOG_INFO("begin.");
std::shared_ptr<DataSharePredicates> predicatesPtr = std::make_shared<DataSharePredicates>(predicates);
if (predicatesPtr == nullptr) {
LOG_ERROR("%{public}s No memory allocated for predicates", __func__);
return nullptr;
}
napi_value napiPredicates = GetNapiObject(env, predicatesPtr);
if (napiPredicates == nullptr) {
LOG_ERROR("%{public}s failed to make new instance of DataSharePredicates.", __func__);
}
LOG_INFO("end.");
return napiPredicates;
}
bool MakeNapiColumn(napi_env env, napi_value &napiColumns, const std::vector<std::string> &columns)
{
napi_status status = napi_create_array(env, &napiColumns);
if (status != napi_ok) {
LOG_ERROR("napi_create_array status : %{public}d", status);
return false;
}
bool isArray = false;
if (napi_is_array(env, napiColumns, &isArray) != napi_ok || !isArray) {
LOG_ERROR("JsDataShareExtAbility create array failed");
return false;
}
int32_t index = 0;
for (const auto &column : columns) {
napi_value result = nullptr;
napi_create_string_utf8(env, column.c_str(), column.length(), &result);
napi_set_element(env, napiColumns, index++, result);
}
return true;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,62 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "js_datashare_ext_ability_context.h"
#include <cstdint>
#include "datashare_log.h"
#include "js_extension_context.h"
#include "js_runtime.h"
#include "js_runtime_utils.h"
#include "napi/native_api.h"
#include "napi_common_want.h"
#include "napi_remote_object.h"
#include "napi_common_start_options.h"
#include "start_options.h"
namespace OHOS {
namespace DataShare {
using namespace AbilityRuntime;
namespace {
class JsDataShareExtAbilityContext final {
public:
explicit JsDataShareExtAbilityContext(const std::shared_ptr<DataShareExtAbilityContext>& context)
: context_(context) {}
~JsDataShareExtAbilityContext() = default;
static void Finalizer(NativeEngine* engine, void* data, void* hint)
{
LOG_INFO("JsAbilityContext::Finalizer is called");
std::unique_ptr<JsDataShareExtAbilityContext>(static_cast<JsDataShareExtAbilityContext*>(data));
}
private:
std::weak_ptr<DataShareExtAbilityContext> context_;
};
} // namespace
NativeValue* CreateJsDataShareExtAbilityContext(NativeEngine& engine,
std::shared_ptr<DataShareExtAbilityContext> context)
{
LOG_INFO("CreateJsDataShareExtAbilityContext begin");
NativeValue* objValue = CreateJsExtensionContext(engine, context);
NativeObject* object = ConvertNativeValueTo<NativeObject>(objValue);
std::unique_ptr<JsDataShareExtAbilityContext> jsContext = std::make_unique<JsDataShareExtAbilityContext>(context);
object->SetNativePointer(jsContext.release(), JsDataShareExtAbilityContext::Finalizer, nullptr);
return objValue;
}
} // namespace DataShare
} // namespace OHOS

View File

@ -1,126 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//foundation/distributeddatamgr/data_share/datashare.gni")
import("//foundation/distributeddatamgr/relational_store/relational_store.gni")
config("ability_config") {
visibility = [ ":*" ]
include_dirs = [
"common/include",
"consumer/include",
"provider/include",
"${ability_runtime_services_path}/common/include",
"${datashare_native_consumer_path}/include",
"${datashare_native_provider_path}/include",
"${ability_runtime_napi_path}/inner/napi_common",
"${relational_store_innerapi_path}/rdb/include",
"//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
}
config("ability_public_config") {
visibility = [ ":*" ]
include_dirs = [
"common/include",
"consumer/include",
"provider/include",
"${datashare_common_napi_path}/include",
"${datashare_common_native_path}/include",
"${datashare_native_consumer_path}/include",
"${datashare_native_provider_path}/include",
"//foundation/window/window_manager/interfaces/innerkits/wm",
]
}
ohos_shared_library("datashare_abilitykit") {
include_dirs = []
sources = [
"${datashare_native_consumer_path}/src/datashare_connection.cpp",
"${datashare_native_consumer_path}/src/datashare_helper.cpp",
"${datashare_native_consumer_path}/src/datashare_proxy.cpp",
"${datashare_native_provider_path}/src/datashare_ext_ability.cpp",
"${datashare_native_provider_path}/src/datashare_ext_ability_context.cpp",
"${datashare_native_provider_path}/src/datashare_stub.cpp",
"${datashare_native_provider_path}/src/datashare_stub_impl.cpp",
"${datashare_native_provider_path}/src/datashare_uv_queue.cpp",
"${datashare_native_provider_path}/src/js_datashare_ext_ability.cpp",
"${datashare_native_provider_path}/src/js_datashare_ext_ability_context.cpp",
]
configs = [ ":ability_config" ]
public_configs = [ ":ability_public_config" ]
deps = [
"${ability_runtime_inner_api_path}/dataobs_manager:dataobs_manager",
"${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native",
"${ability_runtime_path}/frameworks/native/appkit:app_context",
"${datashare_innerapi_path}/common:datashare_common",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"ability_runtime:ability_context_native",
"ability_runtime:ability_manager",
"ability_runtime:runtime",
"access_token:libaccesstoken_sdk",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"ipc:ipc_core",
"ipc_js:rpc",
"relational_store:native_dataability",
"relational_store:native_rdb",
]
public_deps = [
"//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog",
"//foundation/arkui/napi:ace_napi",
]
subsystem_name = "distributeddatamgr"
part_name = "data_share"
}
ohos_shared_library("datashare_ext_ability_module") {
include_dirs = [ "${datashare_native_provider_path}/include" ]
sources = [ "${datashare_native_provider_path}/src/datashare_ext_ability_module_loader.cpp" ]
configs = [ ":ability_config" ]
public_configs = [ ":ability_public_config" ]
deps = [
":datashare_abilitykit",
"${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native",
"//foundation/bundlemanager/bundle_framework/common:libappexecfwk_common",
]
external_deps = [
"ability_base:want",
"ability_runtime:runtime",
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"relational_store:native_appdatafwk",
]
subsystem_name = "distributeddatamgr"
part_name = "data_share"
}

View File

@ -1,73 +0,0 @@
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
import("//foundation/distributeddatamgr/data_share/datashare.gni")
config("ability_config") {
visibility = [ ":*" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
}
ohos_shared_library("datashare_common") {
include_dirs = [
"${datashare_common_napi_path}/include",
"${datashare_common_native_path}/include",
"${datashare_base_path}/interfaces/inner_api/common/include",
"${datashare_base_path}/interfaces/inner_api/consumer/include",
"${datashare_base_path}/interfaces/inner_api/provider/include",
]
sources = [
"${datashare_common_napi_path}/src/datashare_js_utils.cpp",
"${datashare_common_napi_path}/src/datashare_predicates_proxy.cpp",
"${datashare_common_napi_path}/src/datashare_result_set_proxy.cpp",
"${datashare_common_napi_path}/src/napi_datashare_values_bucket.cpp",
"${datashare_common_native_path}/src/datashare_abs_result_set.cpp",
"${datashare_common_native_path}/src/datashare_block_writer_impl.cpp",
"${datashare_common_native_path}/src/datashare_operation.cpp",
"${datashare_common_native_path}/src/datashare_operation_builder.cpp",
"${datashare_common_native_path}/src/datashare_predicates.cpp",
"${datashare_common_native_path}/src/datashare_predicates_object.cpp",
"${datashare_common_native_path}/src/datashare_result.cpp",
"${datashare_common_native_path}/src/datashare_result_set.cpp",
"${datashare_common_native_path}/src/datashare_value_object.cpp",
"${datashare_common_native_path}/src/datashare_values_bucket.cpp",
"${datashare_common_native_path}/src/ishared_result_set.cpp",
"${datashare_common_native_path}/src/ishared_result_set_proxy.cpp",
"${datashare_common_native_path}/src/ishared_result_set_stub.cpp",
]
configs = [ ":ability_config" ]
deps = [
"//foundation/bundlemanager/bundle_framework/common:libappexecfwk_common",
]
external_deps = [
"ability_base:zuri",
"bundle_framework:appexecfwk_base",
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"napi:ace_napi",
"relational_store:native_appdatafwk",
]
subsystem_name = "distributeddatamgr"
part_name = "data_share"
}

View File

@ -1,74 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_ABSPREDICATES_H
#define DATASHARE_ABSPREDICATES_H
#include <string>
#include <vector>
#include <list>
#include "datashare_predicates_def.h"
namespace OHOS {
namespace DataShare {
class DataShareAbsPredicates {
public:
virtual ~DataShareAbsPredicates() {}
virtual DataShareAbsPredicates *EqualTo(const std::string &field, const DataSharePredicatesObject &value) = 0;
virtual DataShareAbsPredicates *NotEqualTo(const std::string &field, const DataSharePredicatesObject &value) = 0;
virtual DataShareAbsPredicates *GreaterThan(const std::string &field, const DataSharePredicatesObject &value) = 0;
virtual DataShareAbsPredicates *LessThan(const std::string &field, const DataSharePredicatesObject &value) = 0;
virtual DataShareAbsPredicates *GreaterThanOrEqualTo(const std::string &field,
const DataSharePredicatesObject &value) = 0;
virtual DataShareAbsPredicates *LessThanOrEqualTo(const std::string &field,
const DataSharePredicatesObject & value) = 0;
virtual DataShareAbsPredicates *In(const std::string &field, const DataSharePredicatesObject &value) = 0;
virtual DataShareAbsPredicates *NotIn(const std::string &field, const DataSharePredicatesObject &value) = 0;
virtual DataShareAbsPredicates *BeginWrap() = 0;
virtual DataShareAbsPredicates *EndWrap() = 0;
virtual DataShareAbsPredicates *Or() = 0;
virtual DataShareAbsPredicates *And() = 0;
virtual DataShareAbsPredicates *Contains(const std::string &field, const std::string &value) = 0;
virtual DataShareAbsPredicates *BeginsWith(const std::string &field, const std::string &value) = 0;
virtual DataShareAbsPredicates *EndsWith(const std::string &field, const std::string &value) = 0;
virtual DataShareAbsPredicates *IsNull(const std::string &field) = 0;
virtual DataShareAbsPredicates *IsNotNull(const std::string &field) = 0;
virtual DataShareAbsPredicates *Like(const std::string &field, const std::string &value) = 0;
virtual DataShareAbsPredicates *Glob(const std::string &field, const std::string &value) = 0;
virtual DataShareAbsPredicates *Between(const std::string &field,
const std::string &low, const std::string &high) = 0;
virtual DataShareAbsPredicates *NotBetween(const std::string &field,
const std::string &low, const std::string &high) = 0;
virtual DataShareAbsPredicates *OrderByAsc(const std::string &field) = 0;
virtual DataShareAbsPredicates *OrderByDesc(const std::string &field) = 0;
virtual DataShareAbsPredicates *Distinct() = 0;
virtual DataShareAbsPredicates *Limit(const int number, const int offset) = 0;
virtual DataShareAbsPredicates *GroupBy(const std::vector<std::string> &fields) = 0;
virtual DataShareAbsPredicates *IndexedBy(const std::string &indexName) = 0;
virtual DataShareAbsPredicates *KeyPrefix(const std::string &prefix) = 0;
virtual DataShareAbsPredicates *InKeys(const std::vector<std::string> &keys) = 0;
virtual const std::list<OperationItem>& GetOperationList() const = 0;
virtual std::string GetWhereClause() const = 0;
virtual int SetWhereClause(const std::string &whereClause) = 0;
virtual std::vector<std::string> GetWhereArgs() const = 0;
virtual int SetWhereArgs(const std::vector<std::string> &whereArgs) = 0;
virtual std::string GetOrder() const = 0;
virtual int SetOrder(const std::string &order) = 0;
virtual SettingMode GetSettingMode() const = 0;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,70 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_ERRNO_H
#define DATASHARE_ERRNO_H
namespace OHOS {
namespace DataShare {
constexpr int E_OK = 0;
constexpr int E_BASE = 1000;
constexpr int E_ERROR = (E_BASE + 1);
constexpr int E_CANNOT_UPDATE_READONLY = (E_BASE + 2);
constexpr int E_REMOVE_FILE = (E_BASE + 3);
constexpr int E_EMPTY_FILE_NAME = (E_BASE + 4);
constexpr int E_EMPTY_TABLE_NAME = (E_BASE + 5);
constexpr int E_EMPTY_VALUES_BUCKET = (E_BASE + 6);
constexpr int E_INVALID_STATEMENT = (E_BASE + 7);
constexpr int E_INVALID_COLUMN_INDEX = (E_BASE + 8);
constexpr int E_INVALID_COLUMN_TYPE = (E_BASE + 9);
constexpr int E_INVALID_COLUMN_NAME = (E_BASE + 10);
constexpr int E_QUERY_IN_EXECUTE = (E_BASE + 11);
constexpr int E_TRANSACTION_IN_EXECUTE = (E_BASE + 12);
constexpr int E_EXECUTE_IN_STEP_QUERY = (E_BASE + 13);
constexpr int E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14);
constexpr int E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15);
constexpr int E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16);
constexpr int E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17);
constexpr int E_NO_ROW_IN_QUERY = (E_BASE + 18);
constexpr int E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19);
constexpr int E_INVALID_OBJECT_TYPE = (E_BASE + 20);
constexpr int E_INVALID_CONFLICT_FLAG = (E_BASE + 21);
constexpr int E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22);
constexpr int E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23);
constexpr int E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24);
constexpr int E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25);
constexpr int E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26);
constexpr int E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27);
constexpr int E_STATEMENT_NOT_PREPARED = (E_BASE + 28);
constexpr int E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29);
constexpr int E_STEP_RESULT_CLOSED = (E_BASE + 30);
constexpr int E_RELATIVE_PATH = (E_BASE + 31);
constexpr int E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32);
constexpr int E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33);
constexpr int E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34);
constexpr int E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35);
constexpr int E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36);
constexpr int E_CREATE_FOLDER_FAIL = (E_BASE + 37);
constexpr int E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38);
constexpr int E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39);
constexpr int E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40);
constexpr int E_NOT_SUPPORT = (E_BASE + 41);
constexpr int E_INVALID_PARCEL = (E_BASE + 42);
constexpr int E_INVALID_FILE_PATH = (E_BASE + 43);
constexpr int E_SET_PERSIST_WAL = (E_BASE + 44);
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,88 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_PREDICATES_H
#define DATASHARE_PREDICATES_H
#include "datashare_abs_predicates.h"
#include <parcel.h>
#include <string>
#include "datashare_predicates_object.h"
namespace OHOS {
namespace DataShare {
class DataSharePredicates : public virtual DataShareAbsPredicates, public virtual OHOS::Parcelable {
public:
DataSharePredicates();
explicit DataSharePredicates(Predicates &predicates);
~DataSharePredicates();
DataSharePredicates *EqualTo(const std::string &field, const DataSharePredicatesObject &value)override;
DataSharePredicates *NotEqualTo(const std::string &field, const DataSharePredicatesObject &value)override;
DataSharePredicates *GreaterThan(const std::string &field, const DataSharePredicatesObject &value)override;
DataSharePredicates *LessThan(const std::string &field, const DataSharePredicatesObject &value)override;
DataSharePredicates *GreaterThanOrEqualTo(const std::string &field, const DataSharePredicatesObject &value)override;
DataSharePredicates *LessThanOrEqualTo(const std::string &field, const DataSharePredicatesObject &value)override;
DataSharePredicates *In(const std::string &field, const DataSharePredicatesObject &values)override;
DataSharePredicates *NotIn(const std::string &field, const DataSharePredicatesObject &values)override;
DataSharePredicates *BeginWrap()override;
DataSharePredicates *EndWrap()override;
DataSharePredicates *Or()override;
DataSharePredicates *And()override;
DataSharePredicates *Contains(const std::string &field, const std::string &value)override;
DataSharePredicates *BeginsWith(const std::string &field, const std::string &value)override;
DataSharePredicates *EndsWith(const std::string &field, const std::string &value)override;
DataSharePredicates *IsNull(const std::string &field)override;
DataSharePredicates *IsNotNull(const std::string &field)override;
DataSharePredicates *Like(const std::string &field, const std::string &value)override;
DataSharePredicates *Unlike(const std::string &field, const std::string &value);
DataSharePredicates *Glob(const std::string &field, const std::string &value)override;
DataSharePredicates *Between(const std::string &field, const std::string &low, const std::string &high)override;
DataSharePredicates *NotBetween(const std::string &field, const std::string &low, const std::string &high)override;
DataSharePredicates *OrderByAsc(const std::string &field)override;
DataSharePredicates *OrderByDesc(const std::string &field)override;
DataSharePredicates *Distinct()override;
DataSharePredicates *Limit(const int number, const int offset)override;
DataSharePredicates *GroupBy(const std::vector<std::string> &fields)override;
DataSharePredicates *IndexedBy(const std::string &indexName)override;
DataSharePredicates *KeyPrefix(const std::string &prefix)override;
DataSharePredicates *InKeys(const std::vector<std::string> &keys)override;
const std::list<OperationItem>& GetOperationList() const override;
std::string GetWhereClause() const override;
int SetWhereClause(const std::string &whereClause)override;
std::vector<std::string> GetWhereArgs() const override;
int SetWhereArgs(const std::vector<std::string> &whereArgs)override;
std::string GetOrder() const override;
int SetOrder(const std::string &order)override;
SettingMode GetSettingMode() const override;
bool Marshalling(OHOS::Parcel &parcel) const override;
static DataSharePredicates *Unmarshalling(OHOS::Parcel &parcel);
std::string GetTableName() const;
private:
void SetOperationList(OperationType operationType, const DataSharePredicatesObject &para1,
const DataSharePredicatesObject &para2, const DataSharePredicatesObject &para3, ParameterCount parameterCount);
void ClearQueryLanguage();
void SetSettingMode(const SettingMode &settingMode);
Predicates predicates_;
std::string whereClause_;
std::vector<std::string> whereArgs_;
std::string order_;
SettingMode settingMode_ = {};
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,90 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_PREDICATES_DEF_H
#define DATASHARE_PREDICATES_DEF_H
#include <string>
#include <vector>
#include "datashare_predicates_object.h"
namespace OHOS {
namespace DataShare {
typedef enum {
ZERO_COUNT = 0x0,
ONE_COUNT,
TWO_COUNT,
THREE_COUNT,
INVALID_COUNT,
} ParameterCount;
typedef enum {
INVALID_OPERATION = 0x0,
EQUAL_TO,
NOT_EQUAL_TO,
GREATER_THAN,
LESS_THAN,
GREATER_THAN_OR_EQUAL_TO,
LESS_THAN_OR_EQUAL_TO,
AND,
OR,
IS_NULL,
IS_NOT_NULL,
IN,
NOT_IN,
LIKE,
UNLIKE,
ORDER_BY_ASC,
ORDER_BY_DESC,
LIMIT,
OFFSET,
BEGIN_WARP,
END_WARP,
BEGIN_WITH,
END_WITH,
IN_KEY,
DISTINCT,
GROUP_BY,
INDEXED_BY,
CONTAINS,
GLOB,
BETWEEN,
NOTBETWEEN,
KEY_PREFIX,
LAST_TYPE
} OperationType;
typedef struct {
OperationType operation;
DataSharePredicatesObject para1;
DataSharePredicatesObject para2;
DataSharePredicatesObject para3;
ParameterCount parameterCount;
} OperationItem;
typedef struct {
std::string tableName;
std::list<OperationItem> operationList;
} Predicates;
typedef enum {
INVALID_MODE,
QUERY_LANGUAGE,
PREDICATES_METHOD
} SettingMode;
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,117 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_PREDICATES_OBJECT_H
#define DATASHARE_PREDICATES_OBJECT_H
#include <parcel.h>
#include <variant>
#include <string>
#include <vector>
namespace OHOS {
namespace DataShare {
enum class DataSharePredicatesObjectType {
TYPE_NULL = 0,
TYPE_INT,
TYPE_DOUBLE,
TYPE_STRING,
TYPE_BOOL,
TYPE_LONG,
TYPE_INT_VECTOR,
TYPE_LONG_VECTOR,
TYPE_DOUBLE_VECTOR,
TYPE_STRING_VECTOR,
};
class DataSharePredicatesObject : public virtual OHOS::Parcelable {
public:
DataSharePredicatesObject();
~DataSharePredicatesObject();
DataSharePredicatesObject(DataSharePredicatesObject &&DataSharePredicatesObject) noexcept;
DataSharePredicatesObject(const DataSharePredicatesObject &DataSharePredicatesObject);
DataSharePredicatesObject &operator=(DataSharePredicatesObject &&DataSharePredicatesObject) noexcept;
DataSharePredicatesObject &operator=(const DataSharePredicatesObject &DataSharePredicatesObject);
DataSharePredicatesObject(int val);
DataSharePredicatesObject(int64_t val);
DataSharePredicatesObject(double val);
DataSharePredicatesObject(bool val);
DataSharePredicatesObject(const std::string &val);
DataSharePredicatesObject(const std::vector<int> &val);
DataSharePredicatesObject(const std::vector<int64_t> &val);
DataSharePredicatesObject(const std::vector<double> &val);
DataSharePredicatesObject(const std::vector<std::string> &val);
DataSharePredicatesObjectType GetType() const;
int GetInt(int &val) const;
int GetLong(int64_t &val) const;
int GetDouble(double &val) const;
int GetBool(bool &val) const;
int GetString(std::string &val) const;
int GetIntVector(std::vector<int> &val) const;
int GetLongVector(std::vector<int64_t> &val) const;
int GetDoubleVector(std::vector<double> &val) const;
int GetStringVector(std::vector<std::string> &val) const;
bool Marshalling(Parcel &parcel) const override;
static DataSharePredicatesObject *Unmarshalling(Parcel &parcel);
DataSharePredicatesObjectType type;
std::variant<std::monostate, int, int64_t, double, std::string, bool, std::vector<int>, std::vector<int64_t>,
std::vector<std::string>, std::vector<double>> value;
operator int () const
{
return std::get<int>(value);
}
operator int64_t () const
{
return std::get<int64_t>(value);
}
operator double () const
{
return std::get<double>(value);
}
operator bool () const
{
return std::get<bool>(value);
}
operator std::string () const
{
return std::get<std::string>(value);
}
operator std::vector<int> () const
{
return std::get<std::vector<int>>(value);
}
operator std::vector<int64_t> () const
{
return std::get<std::vector<int64_t>>(value);
}
operator std::vector<std::string> () const
{
return std::get<std::vector<std::string>>(value);
}
operator std::vector<double> () const
{
return std::get<std::vector<double>>(value);
}
private:
void MarshallingVector(Parcel &parcel) const;
static void UnmarshallingVector(DataSharePredicatesObjectType type, DataSharePredicatesObject *pValueObject,
Parcel &parcel);
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,107 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_VALUE_OBJECT_H
#define DATASHARE_VALUE_OBJECT_H
#include <parcel.h>
#include <variant>
#include <string>
#include <vector>
namespace OHOS {
namespace DataShare {
enum DataShareValueObjectType : int32_t {
TYPE_NULL = 0,
TYPE_INT,
TYPE_DOUBLE,
TYPE_STRING,
TYPE_BOOL,
TYPE_BLOB,
};
class DataShareValueObject {
public:
DataShareValueObject() : type(TYPE_NULL){};
~DataShareValueObject() = default;
DataShareValueObject(DataShareValueObject &&object) noexcept : type(object.type), value(std::move(object.value)){};
DataShareValueObject(const DataShareValueObject &object) : type(object.type), value(object.value){};
DataShareValueObject(int val) : DataShareValueObject(static_cast<int64_t>(val)) {};
DataShareValueObject(int64_t val) : type(TYPE_INT), value(val){};
DataShareValueObject(double val) : type(TYPE_DOUBLE), value(val){};
DataShareValueObject(bool val) : type(TYPE_BOOL), value(val){};
DataShareValueObject(const std::string &val) : type(TYPE_STRING), value(val){};
DataShareValueObject(const char *val) : DataShareValueObject(std::string(val)){};
DataShareValueObject(std::vector<uint8_t> blob) : type(TYPE_BLOB), value(std::move(blob)){};
DataShareValueObject &operator=(DataShareValueObject &&object) noexcept
{
if (this == &object) {
return *this;
}
type = object.type;
value = std::move(object.value);
object.type = TYPE_NULL;
return *this;
};
DataShareValueObject &operator=(const DataShareValueObject &object)
{
if (this == &object) {
return *this;
}
type = object.type;
value = object.value;
return *this;
}
DataShareValueObjectType GetType() const;
int GetInt(int &val) const;
int GetLong(int64_t &val) const;
int GetDouble(double &val) const;
int GetBool(bool &val) const;
int GetString(std::string &val) const;
int GetBlob(std::vector<uint8_t> &val) const;
static bool Marshalling(const DataShareValueObject &valueObject, Parcel &parcel);
static DataShareValueObject *Unmarshalling(Parcel &parcel);
operator int () const
{
return static_cast<int>(std::get<int64_t>(value));
}
operator int64_t () const
{
return std::get<int64_t>(value);
}
operator double () const
{
return std::get<double>(value);
}
operator bool () const
{
return std::get<bool>(value);
}
operator std::string () const
{
return std::get<std::string>(value);
}
operator std::vector<uint8_t> () const
{
return std::get<std::vector<uint8_t>>(value);
}
DataShareValueObjectType type;
std::variant<std::monostate, int, int64_t, double, std::string, bool, std::vector<uint8_t>> value;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_VALUES_BUCKET_H
#define DATASHARE_VALUES_BUCKET_H
#include "datashare_value_object.h"
#include <parcel.h>
#include <map>
#include <set>
namespace OHOS {
namespace DataShare {
class DataShareValuesBucket {
public:
DataShareValuesBucket() = default;
explicit DataShareValuesBucket(std::map<std::string, DataShareValueObject> &values) : valuesMap(values){};
~DataShareValuesBucket() = default;
void Put(const std::string &columnName, const DataShareValueObject &value = {})
{
valuesMap.insert(std::make_pair(columnName, value));
}
void PutString(const std::string &columnName, const std::string &value);
void PutInt(const std::string &columnName, int value);
void PutLong(const std::string &columnName, int64_t value);
void PutDouble(const std::string &columnName, double value);
void PutBool(const std::string &columnName, bool value);
void PutBlob(const std::string &columnName, const std::vector<uint8_t> &value);
void PutNull(const std::string &columnName);
void Delete(const std::string &columnName);
void Clear();
int Size() const;
bool IsEmpty() const;
bool HasColumn(const std::string &columnName) const;
bool GetObject(const std::string &columnName, DataShareValueObject &value) const;
void GetAll(std::map<std::string, DataShareValueObject> &valuesMap) const;
static bool Marshalling(const DataShareValuesBucket &valuesBucket, Parcel &parcel);
static DataShareValuesBucket *Unmarshalling(Parcel &parcel);
std::map<std::string, DataShareValueObject> valuesMap;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

@ -1,269 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_HELPER_H
#define DATASHARE_HELPER_H
#include <mutex>
#include <map>
#include <string>
#include "context.h"
#include "datashare_connection.h"
#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h"
#include "idatashare.h"
#include "uri.h"
#include "datashare_operation.h"
using Uri = OHOS::Uri;
namespace OHOS {
namespace AppExecFwk {
class PacMap;
class IDataAbilityObserver;
}
namespace DataShare {
using string = std::string;
class DataShareHelper final : public std::enable_shared_from_this<DataShareHelper> {
public:
~DataShareHelper();
/**
* @brief Creates a DataShareHelper instance with the Uri specified based on the given Context.
*
* @param context Indicates the Context object on OHOS.
* @param strUri Indicates the database table or disk file to operate.
*
* @return Returns the created DataShareHelper instance with a specified Uri.
*/
static std::shared_ptr<DataShareHelper> Creator(const std::shared_ptr<Context> &context,
const std::string &strUri);
/**
* @brief Creates a DataShareHelper instance with the Uri specified based on the given Context.
*
* @param context Indicates the Context object on OHOS.
* @param StrUri Indicates the database table or disk file to operate.
*
* @return Returns the created DataShareHelper instance with a specified Uri.
*/
static std::shared_ptr<DataShareHelper> Creator(const std::shared_ptr<OHOS::AbilityRuntime::Context> &context,
const std::string &strUri);
/**
* @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
* between the ability using the Data template (data share for short) and the associated client process in
* a DataShareHelper instance.
*
* @param token Indicates the System token.
* @param strUri Indicates the database table or disk file to operate.
*
* @return Returns the created DataShareHelper instance.
*/
static std::shared_ptr<DataShareHelper> Creator(const sptr<IRemoteObject> &token, const std::string &strUri);
/**
* @brief Releases the client resource of the Data share.
* You should call this method to releases client resource after the data operations are complete.
*
* @return Returns true if the resource is successfully released; returns false otherwise.
*/
bool Release();
/**
* @brief Obtains the MIME types of files supported.
*
* @param uri Indicates the path of the files to obtain.
* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
*
* @return Returns the matched MIME types. If there is no match, null is returned.
*/
std::vector<std::string> GetFileTypes(Uri &uri, const std::string &mimeTypeFilter);
/**
* @brief Opens a file in a specified remote path.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
* or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the file descriptor.
*/
int OpenFile(Uri &uri, const std::string &mode);
/**
* @brief This is like openFile, open a file that need to be able to return sub-sections of filesoften assets
* inside of their .hap.
*
* @param uri Indicates the path of the file to open.
* @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
* (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
* "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
* data, or "rwt" for read and write access that truncates any existing file.
*
* @return Returns the RawFileDescriptor object containing file descriptor.
*/
int OpenRawFile(Uri &uri, const std::string &mode);
/**
* @brief Inserts a single data record into the database.
*
* @param uri Indicates the path of the data to operate.
* @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
*
* @return Returns the index of the inserted data record.
*/
int Insert(Uri &uri, const DataShareValuesBucket &value);
/**
* @brief Updates data records in the database.
*
* @param uri Indicates the path of data to update.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param value Indicates the data to update. This parameter can be null.
*
* @return Returns the number of data records updated.
*/
int Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of the data to operate.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
*
* @return Returns the number of data records deleted.
*/
int Delete(Uri &uri, const DataSharePredicates &predicates);
/**
* @brief Deletes one or more data records from the database.
*
* @param uri Indicates the path of data to query.
* @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
* @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
*
* @return Returns the query result.
*/
std::shared_ptr<DataShareResultSet> Query(
Uri &uri, const DataSharePredicates &predicates, std::vector<std::string> &columns);
/**
* @brief Obtains the MIME type matching the data specified by the URI of the Data share. This method should be
* implemented by a Data share. Data abilities supports general data types, including text, HTML, and JPEG.
*
* @param uri Indicates the URI of the data.
*
* @return Returns the MIME type that matches the data specified by uri.
*/
std::string GetType(Uri &uri);
/**
* @brief Inserts multiple data records into the database.
*
* @param uri Indicates the path of the data to operate.
* @param values Indicates the data records to insert.
*
* @return Returns the number of data records inserted.
*/
int BatchInsert(Uri &uri, const std::vector<DataShareValuesBucket> &values);
/**
* @brief Registers an observer to DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
void RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver);
/**
* @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
*
* @param uri, Indicates the path of the data to operate.
* @param dataObserver, Indicates the IDataAbilityObserver object.
*/
void UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver);
/**
* @brief Notifies the registered observers of a change to the data resource specified by Uri.
*
* @param uri, Indicates the path of the data to operate.
*/
void NotifyChange(const Uri &uri);
/**
* @brief Converts the given uri that refer to the Data share into a normalized URI. A normalized URI can be used
* across devices, persisted, backed up, and restored. It can refer to the same item in the Data share even if the
* context has changed. If you implement URI normalization for a Data share, you must also implement
* denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
* any method that is called on the Data share must require normalization verification and denormalization. The
* default implementation of this method returns null, indicating that this Data share does not support URI
* normalization.
*
* @param uri Indicates the Uri object to normalize.
*
* @return Returns the normalized Uri object if the Data share supports URI normalization; returns null otherwise.
*/
Uri NormalizeUri(Uri &uri);
/**
* @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
* The default implementation of this method returns the original URI passed to it.
*
* @param uri uri Indicates the Uri object to denormalize.
*
* @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed
* to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found
* in the current environment.
*/
Uri DenormalizeUri(Uri &uri);
private:
DataShareHelper(const sptr<IRemoteObject> &token, const Uri &uri, const sptr<IDataShare> &dataShareProxy,
const sptr<DataShareConnection> dataShareConnection);
void AddDataShareDeathRecipient(const sptr<IRemoteObject> &token);
void OnSchedulerDied(const wptr<IRemoteObject> &remote);
bool CheckUriParam(const Uri &uri);
bool CheckOhosUri(const Uri &uri);
sptr<IRemoteObject> token_ = {};
Uri uri_ = Uri("");
sptr<IDataShare> dataShareProxy_ = nullptr;
static std::mutex oplock_;
sptr<IRemoteObject::DeathRecipient> callerDeathRecipient_ = nullptr;
std::map<sptr<AAFwk::IDataAbilityObserver>, sptr<IDataShare>> registerMap_;
std::map<sptr<AAFwk::IDataAbilityObserver>, std::string> uriMap_;
sptr<DataShareConnection> dataShareConnection_ = nullptr;
};
class DataShareDeathRecipient : public IRemoteObject::DeathRecipient {
public:
using RemoteDiedHandler = std::function<void(const wptr<IRemoteObject> &)>;
explicit DataShareDeathRecipient(RemoteDiedHandler handler);
virtual ~DataShareDeathRecipient();
virtual void OnRemoteDied(const wptr<IRemoteObject> &remote);
private:
RemoteDiedHandler handler_;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_HELPER_H

View File

@ -1,81 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_RESULT_SET_H
#define DATASHARE_RESULT_SET_H
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "datashare_abs_result_set.h"
#include "message_parcel.h"
#include "parcel.h"
#include "shared_block.h"
#include "datashare_shared_result_set.h"
#include "result_set_bridge.h"
#include "datashare_block_writer_impl.h"
namespace OHOS {
namespace DataShare {
class DataShareResultSet : public DataShareAbsResultSet, public DataShareSharedResultSet {
public:
DataShareResultSet();
explicit DataShareResultSet(std::shared_ptr<ResultSetBridge> &bridge);
virtual ~DataShareResultSet();
int GetBlob(int columnIndex, std::vector<uint8_t> &blob) override;
int GetString(int columnIndex, std::string &value) override;
int GetInt(int columnIndex, int &value) override;
int GetLong(int columnIndex, int64_t &value) override;
int GetDouble(int columnIndex, double &value) override;
int IsColumnNull(int columnIndex, bool &isNull) override;
int GetDataType(int columnIndex, DataType &dataType) override;
int GoToRow(int position) override;
int GetAllColumnNames(std::vector<std::string> &columnNames) override;
int GetRowCount(int &count) override;
AppDataFwk::SharedBlock *GetBlock() const override;
bool OnGo(int startRowIndex, int targetRowIndex) override;
void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) override;
virtual void SetBlock(AppDataFwk::SharedBlock *block);
int Close() override;
bool HasBlock() const;
protected:
int CheckState(int columnIndex);
void ClearBlock();
void ClosedBlock();
virtual void Finalize();
friend class ISharedResultSetStub;
friend class ISharedResultSetProxy;
bool Unmarshalling(MessageParcel &parcel);
bool Marshalling(MessageParcel &parcel);
private:
static int blockId_;
// The actual position of the first row of data in the shareblock
int startRowPos_ = -1;
// The actual position of the last row of data in the shareblock
int endRowPos_ = -1;
// The SharedBlock owned by this DataShareResultSet
AppDataFwk::SharedBlock *sharedBlock_ = nullptr;
std::shared_ptr<DataShareBlockWriterImpl> blockWriter_ = nullptr;
std::shared_ptr<ResultSetBridge> bridge_ = nullptr;
};
} // namespace DataShare
} // namespace OHOS
#endif // DATASHARE_RESULT_SET_H

View File

@ -1,84 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DATASHARE_RESULT_SET_BRIDGE_H
#define DATASHARE_RESULT_SET_BRIDGE_H
#include <string>
namespace OHOS {
namespace DataShare {
// build the bridge between the database's ResultSet and DataShare's ResultSet
class ResultSetBridge {
public:
class Creator {
public:
virtual std::shared_ptr<ResultSetBridge> Create() = 0;
};
class Writer {
public:
/**
* Allocate a row unit and its directory.
*/
virtual int AllocRow() = 0;
/**
* Write Null data to the shared block.
*/
virtual int Write(uint32_t column) = 0;
/**
* Write long data to the shared block.
*/
virtual int Write(uint32_t column, int64_t value) = 0;
/**
* Write Double data to the shared block.
*/
virtual int Write(uint32_t column, double value) = 0;
/**
* Write blob data to the shared block.
*/
virtual int Write(uint32_t column, const uint8_t *value, size_t size) = 0;
/**
* Write string data to the shared block.
*/
virtual int Write(uint32_t column, const char *value, size_t size) = 0;
};
virtual ~ResultSetBridge() {}
/**
* Return a string array holding the names of all of the columns in the
* result set.
*
* return the names of the columns contains in this query result.
*/
virtual int GetAllColumnNames(std::vector<std::string> &columnNames) = 0;
/**
* Return the numbers of rows in the result set.
*/
virtual int GetRowCount(int32_t &count) = 0;
/**
* Called when the position of the result set changes
*/
virtual bool OnGo(int32_t startRowIndex, int32_t targetRowIndex, Writer &writer) = 0;
};
} // namespace DataShare
} // namespace OHOS
#endif

View File

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

Before

Width:  |  Height:  |  Size: 8.1 KiB

After

Width:  |  Height:  |  Size: 8.1 KiB

Some files were not shown because too many files have changed in this diff Show More