提交 3a7961ff 编写于 作者: A Annie_wang

update docs

Signed-off-by: NAnnie_wang <annie.wangli@huawei.com>
上级 3cf2481d
......@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share
|query?(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void|Queries data from the database.|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void|Deletes data from the database.|
For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md).
For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md).
**Table 2** APIs of the data consumer
......@@ -25,11 +25,11 @@ For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-appl
| query(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;DataShareResultSet&gt;): void | Queries data from the database. |
| delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void | Deletes one or more data records from the database.|
For more details, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md).
For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md).
## When to Use
There are two roles in **DataShare**.
There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
......@@ -41,10 +41,10 @@ Examples are given below.
1. Import the dependencies.
```ts
import Extension from '@ohos.application.DataShareExtensionAbility'
import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.rdb';
import fileIo from '@ohos.fileio'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
import fileIo from '@ohos.fileio';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
```
2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API.
......@@ -80,7 +80,7 @@ Examples are given below.
}
// Override the query() API.
query(uri, predicates, columns, callback) {
query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) {
console.info('invalid predicates');
}
......@@ -144,48 +144,49 @@ Examples are given below.
let dseUri = ("datashare:///com.samples.datasharetest.DataShare");
```
2. Create a **DataShareHelper** instance.
3. Create a **DataShareHelper** instance.
```ts
let dsHelper;
let abilityContext;
export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err,data)=>{
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
dsHelper = data;
});
}
}
```
3. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data.
4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data.
```ts
// Construct a piece of data.
var valuesBucket = {"name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1,2,3])};
var updateBucket = {"name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1,2,3])};
let da = new dataSharePredicates.DataSharePredicates();
var valArray =new Array("*");
var valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
var updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let da = new dataSharePredicates.DataSharePredicates();
var valArray = new Array("*");
let people = new Array(
{"name": "LiSi", "age": 41, "Binary": ar},
{"name": "WangWu", "age": 21, "Binary": arr},
{"name": "ZhaoLiu", "age": 61, "Binary": arr});
{ "name": "LiSi", "age": 41, "Binary": ar },
{ "name": "WangWu", "age": 21, "Binary": arr },
{ "name": "ZhaoLiu", "age": 61, "Binary": arr });
// Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err,data) => {
console.log("dsHelper insert result: " + data);
dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data);
});
// Delete data.
dsHelper.delete(dseUri, da, (err,data) => {
console.log("dsHelper delete result: " + data);
dsHelper.delete(dseUri, da, (err, data) => {
console.log("dsHelper delete result: " + data);
});
// Update data.
dsHelper.update(dseUri, da, updateBucket, (err,data) => {
console.log("dsHelper update result: " + data);
dsHelper.update(dseUri, da, updateBucket, (err, data) => {
console.log("dsHelper update result: " + data);
});
// Query data.
dsHelper.query(dseUri, da, valArray, (err,data) => {
console.log("dsHelper query result: " + data);
dsHelper.query(dseUri, da, valArray, (err, data) => {
console.log("dsHelper query result: " + data);
});
```
......@@ -2,14 +2,13 @@
## When to Use
Distributed data objects allow data traversing across devices to be processed like local variables by shielding complex data interaction between devices. For the devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other devices. The devices can listen for data changes and online and offline status changes of other devices.
The distributed data objects support basic data types, such as number, string, and Boolean, as well as complex data types, such as array and nested basic types.
The **distributedDataObject** module provides APIs to implement data collaboration of the same application across multiple devices. In addition, the devices that form a Super Device can listen for object status and data changes with each other.
For example, when the data of the a distributed data object is added, deleted, or modified for application A on device 1, application A on device 2 can obtain the updated data. In addition, device 2 can listen for data changes and online/offline of the data objects on device 1.
## Available APIs
For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
For details about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
### Creating a Distributed Data Object Instance
......@@ -17,7 +16,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance
| Package | API | Description |
| Package| API| Description|
| -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.|
......@@ -26,35 +25,36 @@ Call **createDistributedObject()** to create a distributed data object instance.
Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object.
**Table 2** API for generating a session ID randomly
| Package | API | Description |
| Package| API| Description|
| -------- | -------- | -------- |
| ohos.data.distributedDataObject| genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object.|
### Setting a SessionID for Distributed Data Objects
### Setting a SessionID for a Distributed Data Object
Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID.
**Table 3** API for setting a session ID
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for a distributed data object.<br>**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
### Observing Data Changes
Call **on()** to subscribe to data changes of a distributed data object. In the case of data change, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
**Table 4** APIs for observing data changes of a distributed data object
| Class | API | Description |
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes.<br>**Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.|
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies the data changes to unsubscribe from. If this parameter is not specified, all data changes of this distributed data object will be unsubscribed from.|
### Observing Online or Offline Status
Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes.
**Table 5** APIs for observing status changes of a distributed data object
| Class | API | Description |
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to the status changes of a distributed data object.|
| DistributedDataObject| off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }>): void | Unsubscribes from status changes of a distributed data object.|
......@@ -63,7 +63,7 @@ Call **on()** to subscribe to status changes of a distributed data object. The s
Call **save()** to save a distributed data object. When the application is active, the saved data will not be released. When the application exits and restarts, the data saved on the device will be restored.
Call **revokeSave()** to revoke a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device.
Call **revokeSave()** to delete a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device.
The saved data will be released in the following cases:
......@@ -71,13 +71,11 @@ The saved data will be released in the following cases:
- The application has been uninstalled.
- Data is successfully restored.
**Table 6** APIs for saving a distributed data object and revoking the saving
| Class | API | Description |
**Table 6** APIs for saving a distributed data object and revoking the saving operation
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result. |
| DistributedDataObject | save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result. |
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. |
| DistributedDataObject | revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. |
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object.|
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation.|
## How to Develop
......@@ -89,12 +87,14 @@ The following example shows how to implement distributed data object synchroniza
import distributedObject from '@ohos.data.distributedDataObject';
```
2. Request the permission.
2. Apply for the permission.
Add the required permission (FA model) in the **config.json** file.
The sample code is as follows:
Add the required permission in the **config.json** file. The sample code is as follows:
```
{
```json
{
"module": {
"reqPermissions": [
{
......@@ -103,106 +103,125 @@ The following example shows how to implement distributed data object synchroniza
]
}
}
```
This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows:
```
```
For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
```json
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
}
grantPermission();
```
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
}
grantPermission();
```
3. Obtain a distributed data object instance.
The sample code is as follows:
```js
var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true,
parent:undefined, list:undefined});
var local_object = distributedObject.createDistributedObject({
name: undefined,
age: undefined,
isVis: true,
parent: undefined,
list: undefined
});
var sessionId = distributedObject.genSessionId();
```
4. Add the synchronization network. The data objects in the synchronization network include the local and remote objects.
4. Add the distributed data object instance to the synchronization network.
The sample code is as follows:
The data objects in the synchronization network include the local and remote objects.
The sample code is as follows:
```js
// Local object
var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true,
parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]});
var local_object = distributedObject.createDistributedObject({
name: "jack",
age: 18,
isVis: true,
parent: { mother: "jack mom", father: "jack Dad" },
list: [{ mother: "jack mom" }, { father: "jack Dad" }]
});
local_object.setSessionId(sessionId);
// Remote object
var remote_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true,
parent:undefined, list:undefined});
remote_object.setSessionId(sessionId);
var remote_object = distributedObject.createDistributedObject({
name: undefined,
age: undefined,
isVis: true,
parent: undefined,
list: undefined
});
// After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
remote_object.setSessionId(sessionId);
```
5. Observe the data changes of the distributed data object.
You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes.
You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes.
The sample code is as follows:
```js
function changeCallback(sessionId, changeData) {
console.info("change" + sessionId);
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
changeData.forEach(element => {
console.info("changed !" + element + " " + local_object[element]);
});
}
}
if (changeData != null && changeData != undefined) {
changeData.forEach(element => {
console.info("changed !" + element + " " + local_object[element]);
});
}
}
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
local_object.on("change", this.changeCallback.bind(this));
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
local_object.on("change", this.changeCallback.bind(this));
```
6. Modify object attributes.
6. Modify attributes of the distributed data object.
The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
The sample code is as follows:
```js
local_object.name = "jack";
local_object.age = 19;
local_object.isVis = false;
local_object.parent = {mother:"jack mom", father:"jack Dad"};
local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}];
local_object.parent = { mother: "jack mom", father: "jack Dad" };
local_object.list = [{ mother: "jack mom" }, { father: "jack Dad" }];
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified.
Example:
> **NOTE**<br>
> For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example:
```js
// Supported modification.
local_object.parent = {mother:"mom", father:"dad"};
local_object.parent = { mother: "mom", father: "dad" };
// Modification not supported.
local_object.parent.mother = "mom";
```
7. Access the distributed data object.
Obtain the distributed data object attribute, which is the latest data on the network.
Obtain the distributed data object attributes, which are the latest data on the network.
The sample code is as follows:
```js
console.info("name " + local_object["name"]);
```
......@@ -221,7 +240,6 @@ The following example shows how to implement distributed data object synchroniza
```
9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
The sample code is as follows:
```js
......@@ -234,53 +252,29 @@ The following example shows how to implement distributed data object synchroniza
10. Save a distributed data object and revoke the data saving operation.
- Callback
```
​```js
// Save a distributed data object.
local_object.save("local", (result, data) => {
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) => {
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
​```
```
- Promise
```
​```js
// Save a distributed data object.
g_object.save("local").then((result) => {
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result) => {
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
​```
```
```js
// Save a distributed data object.
g_object.save("local").then((result) => {
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result) => {
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result) => {
console.info("revokeSave success.");
}, (result) => {
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object.
The sample code is as follows:
```js
// Unregister the specified status change callback.
local_object.off("status", this.statusCallback);
......@@ -288,9 +282,12 @@ The following example shows how to implement distributed data object synchroniza
local_object.off("status");
```
12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object.
12. Remove a distributed data object from the synchronization network.
The sample code is as follows:
```js
local_object.setSessionId("");
```
Data changes on the local object will not be synchronized to the removed distributed data object.
The sample code is as follows:
```js
local_object.setSessionId("");
```
# Distributed Data Object Overview
The distributed data object management framework is an object-oriented in-memory data management framework. It provides application developers with basic data object management capabilities, such as creating, querying, deleting, modifying, and subscribing to in-memory objects. This management framework also provides distributed capabilities to implement data object collaboration for the same application between multiple devices that form a Super Device.
The distributed data object management framework provides object-oriented in-memory data management. It provides basic data management capabilities, such as creating, querying, deleting, and modifying distributed data objects, and observing data and status changes of the distributed data objects. This management framework also provides distributed capabilities to implement data object collaboration for the same application between multiple devices that form a Super Device.
## Key Concepts
## Basic Concepts
- **Distributed in-memory database**
The distributed in-memory database caches data in the memory, so that applications can quickly access data. This database, however, does not store data persistently. If the database is closed, the data is not retained.
The distributed in-memory database caches data in the memory so that applications can quickly access data. This database, however, does not store data persistently. If the database is closed, the data is not retained.
- **Distributed data object**
A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading or assigning values to distributed data objects is automatically mapped to the **put** or **get** operation of the corresponding database.
A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **put** and **get** operations in the corresponding database, respectively.
The distributed data object can be in the following states in its lifecycle:
- **Uninitialized**: The distributed data object is not instantiated or has been destroyed.
- **Local**: The data table is created, but the data cannot be synchronized.
- **Distributed**: The data table is created, there are at least two online with the same session ID, and data can be synchronized across devices. If the device is offline or the session ID is empty, the distributed data object changes to the local state.
- **Distributed**: The data table is created, and there are at least two online devices with the same session ID. In this case, data can be synchronized across devices. If a device is offline or the session ID is empty, the distributed data object changes to the local state.
## Working Principles
The distributed data objects are encapsulated into JS objects in distributed in-memory databases, which allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization.
The distributed data objects are encapsulated into JS objects in distributed in-memory databases. This allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization.
**Figure 1** Working mechanism
......@@ -34,7 +34,7 @@ The distributed data objects are encapsulated into JS objects in distributed in-
## Constraints
- Data synchronization can be implemented across devices only for the applications with the same bundleName.
- Data synchronization can be implemented across devices only for the applications with the same **bundleName**.
- Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects.
......
......@@ -6,113 +6,144 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
For details about the APIs, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
**Table 1** APIs provided by the DDS
| API | Description |
| ------------------------------------------------------------ | ----------------------------------------------- |
| createKVManager(config:KVManagerConfig,callback:AsyncCallback&lt;KVManager&gt;):void<br>createKVManager(config:KVManagerConfig):Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options,callback:AsyncCallback&lt;T&gt;):void<br>getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options):Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.|
| put(key:string,value:Uint8Array\|string\|number\|boolean,callback:AsyncCallback&lt;void&gt;):void<br>put(key:string,value:Uint8Array\|string\|number\|boolean):Promise&lt;void> | Inserts and updates data. |
| delete(key:string,callback:AsyncCallback&lt;void&gt;):void<br>delete(key:string):Promise&lt;void> | Deletes data. |
| get(key:string,callback:AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;):void<br>get(key:string):Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
| on(event:'dataChange',type:SubscribeType,observer:Callback&lt;ChangeNotification&gt;):void<br>on(event:'syncComplete',syncCallback:Callback&lt;Array&lt;[string,number]&gt;&gt;):void | Subscribes to data changes in the KV store. |
| sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): void | Subscribes to data changes in the KV store. |
| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
## How to Develop
The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module.
```js
import distributedData from '@ohos.data.distributedData';
```
2. Apply for the required permission if data synchronization is required.
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
(1) Create a **KvManagerConfig** object based on the application context.
Add the permission required (FA model) in the **config.json** file. The sample code is as follows:
```json
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
```js
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
}
grantPermission();
```
3. Create a **kvManager** instance based on the specified **kvManagerConfig** object.
1. Create a **kvManagerConfig** object based on the application context.
2. Create a **kvManager** instance.
(2) Create a **KvManager** instance.
The sample code is as follows:
```
```js
let kvManager;
try {
const kvManagerConfig = {
bundleName : 'com.example.datamanagertest',
userInfo : {
userId : '0',
userType : distributedData.UserType.SAME_USER_ID
}
const kvManagerConfig = {
bundleName: 'com.example.datamanagertest',
userInfo: {
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
distributedData.createKVManager(kvManagerConfig, function (err, manager) {
if (err) {
console.log("createKVManager err: " + JSON.stringify(err));
return;
}
console.log("createKVManager success");
kvManager = manager;
});
}
distributedData.createKVManager(kvManagerConfig, function (err, manager) {
if (err) {
console.log("createKVManager err: " + JSON.stringify(err));
return;
}
console.log("createKVManager success");
kvManager = manager;
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
console.log("An unexpected error occurred. Error: " + e);
}
```
3. Create and obtain a single KV store.
(1) Declare the ID of the single KV store to create.
4. Create and obtain a single KV store.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (`autoSync:false`) and call `sync` when a synchronization is required.
The sample code is as follows:
```js
let kvStore;
try {
const options = {
createIfMissing : true,
encrypt : false,
backup : false,
autoSync : false,
kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
securityLevel : distributedData.SecurityLevel.S0,
};
kvManager.getKVStore('storeId', options, function (err, store) {
if (err) {
console.log("getKVStore err: " + JSON.stringify(err));
return;
}
console.log("getKVStore success");
kvStore = store;
});
const options = {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: false,
kvStoreType: distributedData.KVStoreType.SINGLE_VERSION,
securityLevel: distributedData.SecurityLevel.S0
};
kvManager.getKVStore('storeId', options, function (err, store) {
if (err) {
console.log("getKVStore err: " + JSON.stringify(err));
return;
}
console.log("getKVStore success");
kvStore = store;
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
console.log("An unexpected error occurred. Error: " + e);
}
```
> **NOTE**
> **NOTE**<br>
>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
5. Subscribe to changes in the distributed data.
4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store:
```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
});
```
5. Write data to the single KV store.
(1) Construct the key and value to be written into the single KV store.
6. Write data to the single KV store.
(2) Write key-value pairs into the single KV store.
1. Construct the `Key` and `Value` to be written into the single KV store.
2. Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store:
......@@ -120,52 +151,54 @@ The following uses a single KV store as an example to describe the development p
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) {
console.log("put err: " + JSON.stringify(err));
return;
}
console.log("put success");
});
}catch (e) {
console.log("An unexpected error occurred. Error:" + e);
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
}
```
6. Query data in the single KV store.
(1) Construct the key to be queried from the single KV store.
7. Query data in the single KV store.
(2) Query data from the single KV store.
1. Construct the `Key` to be queried from the single KV store.
2. Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store:
```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) {
console.log("put err: " + JSON.stringify(err));
return;
}
console.log("put success");
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
console.log("get success data: " + data);
});
});
}catch (e) {
console.log("An unexpected error occurred. Error:" + e);
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
}
```
7. Synchronize data to other devices.<br/>
8. Synchronize data to other devices.
Select the devices in the same network and the synchronization mode to synchronize data.
> **NOTE**
> **NOTE**<br>
>
> The APIs of the `deviceManager` module are system interfaces.
The following is the example code for synchronizing data in a single KV store:
The following is the sample code for synchronizing data in a single KV store:
```js
import deviceManager from '@ohos.distributedHardware.deviceManager';
......@@ -185,8 +218,8 @@ The following uses a single KV store as an example to describe the development p
try{
// 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
}catch (e) {
console.log("An unexpected error occurred. Error:" + e);
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
}
}
});
......
......@@ -2,7 +2,7 @@
> **NOTE**
>
> This feature is supported since API Version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
> This feature is supported since API version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
## When to Use
......@@ -88,8 +88,30 @@ Use the following APIs to delete a **Preferences** instance or data file.
2. Obtain a **Preferences** instance.
Read the specified file and load its data to the **Preferences** instance for data operations.
FA model:
```js
let promise = data_preferences.getPreferences(this.context, 'mystore');
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
let promise = data_preferences.getPreferences(context, 'mystore');
```
Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
onWindowStageCreate(windowStage){
context = this.context
}
}
let promise = data_preferences.getPreferences(context, 'mystore');
```
3. Write data.
......@@ -115,12 +137,12 @@ Use the following APIs to delete a **Preferences** instance or data file.
```js
promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => {
console.info("The value of 'startup' is " + value);
}).catch((err) => {
console.info("Failed to get the value of 'startup'. Cause: " + err);
})
let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => {
console.info("The value of 'startup' is " + value);
}).catch((err) => {
console.info("Failed to get the value of 'startup'. Cause: " + err);
})
}).catch((err) => {
console.info("Failed to get the preferences.")
});
......@@ -139,24 +161,24 @@ Use the following APIs to delete a **Preferences** instance or data file.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data.
```js
var observer = function (key) {
console.info("The key" + key + " changed.");
}
preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
var observer = function (key) {
console.info("The key" + key + " changed.");
}
preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Put the value of 'startup' successfully.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data. Cause: " + err);
return;
}
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Flushed data successfully."); // The observer will be called.
})
})
})
})
```
7. Delete the specified file.
......@@ -164,10 +186,10 @@ Use the following APIs to delete a **Preferences** instance or data file.
Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored.
```js
let proDelete = data_preferences.deletePreferences(context, 'mystore');
proDelete.then(() => {
let proDelete = data_preferences.deletePreferences(context, 'mystore');
proDelete.then(() => {
console.info("Deleted data successfully.");
}).catch((err) => {
}).catch((err) => {
console.info("Failed to delete data. Cause: " + err);
})
})
```
......@@ -30,9 +30,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 2** API for inserting data
| Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | insert(table:string,values:ValuesBucket):Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.|
| RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.|
- **Updating Data**
......@@ -40,9 +41,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 3** API for updating data
| Class | API | Description |
| Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | update(values:ValuesBucket,predicates:RdbPredicates):Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br/>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data.<br/>Return value: number of rows updated. |
| RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>the number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data.|
- **Deleting Data**
......@@ -50,11 +52,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 4** API for deleting data
| Class | API | Description |
| -------- | ------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | delete(predicates:RdbPredicates):Promise&lt;number&gt; | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>- **predicates**: conditions for deleting data.<br/>Return value: number of rows updated. |
| Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return<br>the number of rows updated.<br>- **predicates**: conditions for deleting data.|
- **Querying Data**
......@@ -65,10 +66,11 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 5** APIs for querying data
| Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | query(predicates:RdbPredicates,columns?:Array&lt;string&gt;):Promise&lt;ResultSet&gt; | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.<br>- **predicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
| RdbStore | querySql(sql:string,bindArgs?:Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt; | Queries data using the specified SQL statement. This API uses a promise to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.|
| RdbStore | query(predicates: RdbPredicates, columns?: Array&lt;string&gt;): Promise&lt;ResultSet&gt; | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.<br>- **predicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
| RdbStore | querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;): Promise&lt;ResultSet&gt; | Queries data using the specified SQL statement. This API uses a promise to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.|
| RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt;): Promise&lt;ResultSet&gt; | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.<br>- **device**: network ID of the remote device.<br>- **table**: name of the table to be queried.<br>- **predicates**: **RdbPredicates** that specifies the query condition.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
### Using Predicates
......@@ -81,11 +83,11 @@ The following lists common predicates. For more information about predicates, se
| Class | API | Description |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.|
| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.|
| RdbPredicates | contains(field:string,value:string):RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.|
| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.|
| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
### Using the Result Set
......@@ -101,12 +103,12 @@ For details about how to use result set APIs, see [Result Set](../reference/apis
| Class | API | Description |
| --------- | ---------------------------------------------------- | ------------------------------------------ |
| ResultSet | goToFirstRow():boolean | Moves to the first row of the result set. |
| ResultSet | getString(columnIndex:number):string | Obtains the value in the form of a string based on the specified column and current row. |
| ResultSet | getBlob(columnIndex:number):Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.|
| ResultSet | getDouble(columnIndex:number):number | Obtains the value in the form of double based on the specified column and current row. |
| ResultSet | getLong(columnIndex:number):number | Obtains the value in the form of a long integer based on the specified column and current row. |
| ResultSet | close():void | Closes the result set. |
| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set. |
| ResultSet | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. |
| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.|
| ResultSet | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. |
| ResultSet | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. |
| ResultSet | close(): void | Closes the result set. |
......@@ -164,7 +166,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | backup(destName:string): Promise&lt;void&gt; | Backs up an RDB store. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
| RdbStore | backup(destName: string): Promise&lt;void&gt; | Backs up an RDB store. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
**Restoring an RDB Store**
......@@ -172,7 +174,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | restore(srcName:string): Promise&lt;void&gt; | Restores an RDB store from a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the backup file used to restore the RDB store.|
| RdbStore | restore(srcName: string): Promise&lt;void&gt; | Restores an RDB store from a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the backup file used to restore the RDB store.|
**Transaction**
......@@ -180,9 +182,9 @@ Table 15 Transaction APIs
| Class | API | Description |
| -------- | ----------------------- | --------------------------------- |
| RdbStore | beginTransaction():void | Starts the transaction before executing SQL statements.|
| RdbStore | commit():void | Commits the executed SQL statements. |
| RdbStore | rollBack():void | Rolls back the SQL statements that have been executed. |
| RdbStore | beginTransaction(): void | Starts the transaction before executing SQL statements.|
| RdbStore | commit(): void | Commits the executed SQL statements. |
| RdbStore | rollBack(): void | Rolls back the SQL statements that have been executed. |
## How to Develop
......@@ -200,10 +202,10 @@ Table 15 Transaction APIs
import data_rdb from '@ohos.data.rdb'
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = {name: "rdbstore.db"}
const STORE_CONFIG = { name: "rdbstore.db" }
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
```
......@@ -217,7 +219,7 @@ Table 15 Transaction APIs
```js
var u8 = new Uint8Array([1, 2, 3])
const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8}
const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }
let insertPromise = rdbStore.insert("test", valueBucket)
```
......@@ -316,6 +318,7 @@ Table 15 Transaction APIs
console.log('device=' + device[i] + 'data changed')
}
}
try {
rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver)
} catch (err) {
......@@ -366,9 +369,7 @@ Table 15 Transaction APIs
(1) Back up the current RDB store.
(2) Restore the RDB store using the backup file.
The sample code is as follows:
The sample code is as follows:
```js
let promiseBackup = rdbStore.backup("dbBackup.db")
......@@ -378,6 +379,10 @@ Table 15 Transaction APIs
console.info('Backup failed, err: ' + err)
})
```
(2) Restore the RDB store using the backup file.
The sample code is as follows:
```js
let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => {
......@@ -386,4 +391,3 @@ Table 15 Transaction APIs
console.info('Restore failed, err: ' + err)
})
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册