未验证 提交 845959f9 编写于 作者: O openharmony_ci 提交者: Gitee

!12458 [翻译完成】#I5WO3F

Merge pull request !12458 from Annie_wang/PR10840
...@@ -6,15 +6,15 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -6,15 +6,15 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## Available APIs
For details about the APIs, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis-distributedKVStore.md).
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| API | Description | | 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.| | 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**.| | 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; | Creates and obtains a KV store.|
| 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. | | 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. | | 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. | | get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
...@@ -28,8 +28,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -28,8 +28,9 @@ The following uses a single KV store as an example to describe the development p
1. Import the distributed data module. 1. Import the distributed data module.
```js ```js
import distributedData from '@ohos.data.distributedData'; import distributedKVStore from '@ohos.data.distributedKVStore';
``` ```
2. Apply for the required permission if data synchronization is required. 2. Apply for the required permission if data synchronization is required.
Add the permission required (FA model) in the **config.json** file. The sample code is as follows: Add the permission required (FA model) in the **config.json** file. The sample code is as follows:
...@@ -45,6 +46,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -45,6 +46,7 @@ The following uses a single KV store as an example to describe the development p
} }
} }
``` ```
For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model). 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: This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
...@@ -88,10 +90,10 @@ The following uses a single KV store as an example to describe the development p ...@@ -88,10 +90,10 @@ The following uses a single KV store as an example to describe the development p
grantPermission(); grantPermission();
``` ```
3. Create a **kvManager** instance based on the specified **kvManagerConfig** object. 3. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **kvManagerConfig** object based on the application context. 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: The sample code is as follows:
...@@ -113,22 +115,18 @@ The following uses a single KV store as an example to describe the development p ...@@ -113,22 +115,18 @@ The following uses a single KV store as an example to describe the development p
try { try {
const kvManagerConfig = { const kvManagerConfig = {
bundleName: 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
userInfo: {
context:context, context:context,
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
} }
distributedData.createKVManager(kvManagerConfig, function (err, manager) { distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) {
if (err) { if (err) {
console.log('Failed to create KVManager: ${error}'); console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Created KVManager successfully'); console.log('Created KVManager successfully');
kvManager = manager; kvManager = manager;
}); });
} catch (e) { } catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -147,19 +145,19 @@ The following uses a single KV store as an example to describe the development p ...@@ -147,19 +145,19 @@ The following uses a single KV store as an example to describe the development p
encrypt: false, encrypt: false,
backup: false, backup: false,
autoSync: false, autoSync: false,
kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
securityLevel: distributedData.SecurityLevel.S0 securityLevel: distributedKVStore.SecurityLevel.S1
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.log('Failed to get KVStore: ${err}'); console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Got KVStore successfully'); console.log('Obtained KVStore successfully');
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -172,9 +170,13 @@ The following uses a single KV store as an example to describe the development p ...@@ -172,9 +170,13 @@ The following uses a single KV store as an example to describe the development p
The following is the sample code for subscribing to the data changes of a single KV store: The following is the sample code for subscribing to the data changes of a single KV store:
```js ```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { try{
console.log("dataChange callback call data: ${data}"); kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log(`dataChange callback call data: ${data}`);
}); });
}catch(e){
console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`);
}
``` ```
6. Write data to the single KV store. 6. Write data to the single KV store.
...@@ -188,15 +190,15 @@ The following uses a single KV store as an example to describe the development p ...@@ -188,15 +190,15 @@ The following uses a single KV store as an example to describe the development p
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { 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) { if (err != undefined) {
console.log('Failed to put data: ${error}'); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log('Put data successfully');
}); });
} catch (e) { }catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -211,18 +213,22 @@ The following uses a single KV store as an example to describe the development p ...@@ -211,18 +213,22 @@ The following uses a single KV store as an example to describe the development p
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try { 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) { if (err != undefined) {
console.log('Failed to put data: ${error}'); console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
return; return;
} }
console.log('Put data successfully'); console.log('Put data successfully');
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
console.log('Got data successfully: ${data}'); if (err != undefined) {
console.error(`Failed to get data.code is ${err.code},message is ${err.message}`);
return;
}
console.log(`Obtained data successfully:${data}`);
}); });
}); });
} catch (e) { }catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
} }
``` ```
...@@ -254,9 +260,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -254,9 +260,9 @@ The following uses a single KV store as an example to describe the development p
} }
try{ try{
// 1000 indicates that the maximum delay is 1000 ms. // 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) { } catch (e) {
console.log('An unexpected error occurred. Error: ${e}'); console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`);
} }
} }
}); });
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
- [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - [@ohos.application.StartOptions](js-apis-application-StartOptions.md)
- [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md)
- [@ohos.application.WindowExtensionAbility](js-apis-application-WindowExtensionAbility.md) - [@ohos.application.WindowExtensionAbility](js-apis-application-windowExtensionAbility.md)
- application/[AbilityContext](js-apis-ability-context.md) - application/[AbilityContext](js-apis-ability-context.md)
- application/[ApplicationContext](js-apis-application-applicationContext.md) - application/[ApplicationContext](js-apis-application-applicationContext.md)
- application/[AbilityStageContext](js-apis-abilitystagecontext.md) - application/[AbilityStageContext](js-apis-abilitystagecontext.md)
...@@ -127,6 +127,7 @@ ...@@ -127,6 +127,7 @@
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md)
- [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md)
...@@ -173,7 +174,7 @@ ...@@ -173,7 +174,7 @@
- Basic Features - Basic Features
- [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility](js-apis-accessibility.md)
- [@ohos.accessibility.config](js-apis-accessibility-config.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md)
- [@ohos.application.AccessibilityExtensionAbility](js-apis-application-AccessibilityExtensionAbility.md) - [@ohos.application.AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md)
- [@ohos.faultLogger](js-apis-faultLogger.md) - [@ohos.faultLogger](js-apis-faultLogger.md)
- [@ohos.hichecker](js-apis-hichecker.md) - [@ohos.hichecker](js-apis-hichecker.md)
- [@ohos.hidebug](js-apis-hidebug.md) - [@ohos.hidebug](js-apis-hidebug.md)
...@@ -181,8 +182,8 @@ ...@@ -181,8 +182,8 @@
- [@ohos.hiSysEvent](js-apis-hisysevent.md) - [@ohos.hiSysEvent](js-apis-hisysevent.md)
- [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceChain](js-apis-hitracechain.md)
- [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md)
- [@ohos.inputMethod](js-apis-inputmethod.md) - [@ohos.inputmethod](js-apis-inputmethod.md)
- [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) - [@ohos.inputmethodengine](js-apis-inputmethodengine.md)
- [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md)
- [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md)
- [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.pasteboard](js-apis-pasteboard.md)
...@@ -224,7 +225,7 @@ ...@@ -224,7 +225,7 @@
- [@ohos.account.osAccount](js-apis-osAccount.md) - [@ohos.account.osAccount](js-apis-osAccount.md)
- Custom Management - Custom Management
- [@ohos.configPolicy](js-apis-configPolicy.md) - [@ohos.configPolicy](js-apis-configPolicy.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- Language Base Class Library - Language Base Class Library
- [@ohos.buffer](js-apis-buffer.md) - [@ohos.buffer](js-apis-buffer.md)
- [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.convertxml](js-apis-convertxml.md)
......
...@@ -13,7 +13,9 @@ This module provides the following functions: ...@@ -13,7 +13,9 @@ This module provides the following functions:
>**NOTE**<br/> >**NOTE**<br/>
> >
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. >- The APIs provided by this module are no longer maintained since API version 9. You are advised to use `@ohos.data.distributedKVStore`](js-apis-distributedKVStore.md).
>
>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -39,21 +41,15 @@ Creates a **KVManager** instance to manage KV stores. This API uses an asynchron ...@@ -39,21 +41,15 @@ Creates a **KVManager** instance to manage KV stores. This API uses an asynchron
| callback | AsyncCallback&lt;[KVManager](#kvmanager)&gt; | Yes | Callback invoked to return the **KVManager** instance created.| | callback | AsyncCallback&lt;[KVManager](#kvmanager)&gt; | Yes | Callback invoked to return the **KVManager** instance created.|
**Example** **Example**
```js
Stage model:
```ts
import AbilityStage from '@ohos.application.Ability'
let kvManager; let kvManager;
export default class MyAbilityStage extends AbilityStage { try {
onCreate() {
console.log("MyAbilityStage onCreate")
let context = this.context
const kvManagerConfig = { const kvManagerConfig = {
context: context, bundleName : 'com.example.datamanagertest',
bundleName: 'com.example.datamanagertest', userInfo : {
userInfo: { userId : '0',
userId: '0', userType : distributedData.UserType.SAME_USER_ID
userType: distributedData.UserType.SAME_USER_ID
} }
} }
distributedData.createKVManager(kvManagerConfig, function (err, manager) { distributedData.createKVManager(kvManagerConfig, function (err, manager) {
...@@ -64,31 +60,9 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -64,31 +60,9 @@ export default class MyAbilityStage extends AbilityStage {
console.log("Created KVManager successfully"); console.log("Created KVManager successfully");
kvManager = manager; kvManager = manager;
}); });
} } catch (e) {
} console.log("An unexpected error occurred. Error:" + e);
```
FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
let kvManager;
let context = featureAbility.getContext()
const kvManagerConfig = {
context: context,
bundleName: 'com.example.datamanagertest',
userInfo: {
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
} }
distributedData.createKVManager(kvManagerConfig, function (err, manager) {
if (err) {
console.log("Failed to create KVManager: " + JSON.stringify(err));
return;
}
console.log("Created KVManager successfully");
kvManager = manager;
});
``` ```
## distributedData.createKVManager ## distributedData.createKVManager
...@@ -112,52 +86,28 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to ...@@ -112,52 +86,28 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to
| Promise&lt;[KVManager](#kvmanager)&gt; | Promise used to return the **KVManager** instance created.| | Promise&lt;[KVManager](#kvmanager)&gt; | Promise used to return the **KVManager** instance created.|
**Example** **Example**
```js
Stage model:
```ts
import AbilityStage from '@ohos.application.Ability'
let kvManager; let kvManager;
export default class MyAbilityStage extends AbilityStage { try {
onCreate() {
console.log("MyAbilityStage onCreate")
let context = this.context
const kvManagerConfig = { const kvManagerConfig = {
context: context, bundleName : 'com.example.datamanagertest',
bundleName: 'com.example.datamanagertest', userInfo : {
userInfo: { userId : '0',
userId: '0', userType : distributedData.UserType.SAME_USER_ID
userType: distributedData.UserType.SAME_USER_ID
} }
} }
distributedData.createKVManager(kvManagerConfig).then((manager) => { distributedData.createKVManager(kvManagerConfig, function (err, manager) {
console.log("Created KVManager successfully"); if (err) {
kvManager = manager;
}).catch((err) => {
console.log("Failed to create KVManager: " + JSON.stringify(err)); console.log("Failed to create KVManager: " + JSON.stringify(err));
}); return;
}
}
```
FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
let kvManager;
let context = featureAbility.getContext()
const kvManagerConfig = {
context: context,
bundleName: 'com.example.datamanagertest',
userInfo: {
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
} }
}
distributedData.createKVManager(kvManagerConfig).then((manager) => {
console.log("Created KVManager successfully"); console.log("Created KVManager successfully");
kvManager = manager; kvManager = manager;
}).catch((err) => { });
console.log("Failed to create KVManager: " + JSON.stringify(err)); } catch (e) {
}); console.log("An unexpected error occurred. Error:" + e);
}
``` ```
## KVManagerConfig ## KVManagerConfig
...@@ -168,7 +118,6 @@ Provides configuration of the **KVManager** object, including the bundle name an ...@@ -168,7 +118,6 @@ Provides configuration of the **KVManager** object, including the bundle name an
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ | | ----- | ------ | ------ | ------ |
| context<sup>9+<sup> | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| userInfo | [UserInfo](#userinfo) | Yes | User information.| | userInfo | [UserInfo](#userinfo) | Yes | User information.|
| bundleName | string | Yes | Bundle name.| | bundleName | string | Yes | Bundle name.|
...@@ -179,9 +128,9 @@ Defines user information. ...@@ -179,9 +128,9 @@ Defines user information.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ | | ----- | ------ |------ | ------ |
| userId | string | Yes | User ID.| | userId | string | No | User ID.|
| userType | [UserType](#usertype) | Yes | User type.| | userType | [UserType](#usertype) | No | User type.|
## UserType ## UserType
...@@ -213,7 +162,7 @@ Creates and obtains a KV store. This API uses an asynchronous callback to return ...@@ -213,7 +162,7 @@ Creates and obtains a KV store. This API uses an asynchronous callback to return
| ----- | ------ | ------ | ------ | | ----- | ------ | ------ | ------ |
| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
| options | [Options](#options) | Yes | Configuration of the KV store.| | options | [Options](#options) | Yes | Configuration of the KV store.|
| callback | AsyncCallback&lt;T&gt; , &lt;T extends [KVStore](#kvstore)&gt;| Yes | Callback invoked to return the KV store created.| | callback | AsyncCallback&lt;T&gt; | Yes | Callback invoked to return the KV store created.|
**Example** **Example**
...@@ -500,7 +449,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) ...@@ -500,7 +449,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore)
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| appId | string | Yes | Bundle name of the app that invokes the KV store. | | appId | string | Yes | Bundle name of the app that invokes the KV store. |
| callback | AsyncCallback&lt;string[]&gt; | Yes |Callback invoked to return the KV store IDs obtained. | | callback | AsyncCallback&lt;string[]&gt; | Yes |Callback invoked to return the KV store IDs obtained.|
**Example** **Example**
...@@ -560,7 +509,7 @@ try { ...@@ -560,7 +509,7 @@ try {
on(event: 'distributedDataServiceDie', deathCallback: Callback&lt;void&gt;): void on(event: 'distributedDataServiceDie', deathCallback: Callback&lt;void&gt;): void
Subscribes to service status changes. This API returns the result synchronously. Subscribes to service status changes.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -591,7 +540,7 @@ try { ...@@ -591,7 +540,7 @@ try {
off(event: 'distributedDataServiceDie', deathCallback?: Callback&lt;void&gt;): void off(event: 'distributedDataServiceDie', deathCallback?: Callback&lt;void&gt;): void
Unsubscribes from service status changes. This API returns the result synchronously. Unsubscribes from service status changes.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
...@@ -625,7 +574,7 @@ Provides KV store configuration. ...@@ -625,7 +574,7 @@ Provides KV store configuration.
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ------ | -------------------|
| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| backup | boolean | No|Whether to back up database files. By default, database files are backed up. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | backup | boolean | No|Whether to back up database files. By default, database files are backed up. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
...@@ -642,8 +591,8 @@ Enumerates the KV store types. ...@@ -642,8 +591,8 @@ Enumerates the KV store types.
| Name | Value| Description | | Name | Value| Description |
| --- | ---- | ----------------------- | | --- | ---- | ----------------------- |
| DEVICE_COLLABORATION | 0 | Device KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | | DEVICE_COLLABORATION | 0 | Device KV store.<br> The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| SINGLE_VERSION | 1 | Single KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | SINGLE_VERSION | 1 | Single KV store.<br> The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| | MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
...@@ -682,12 +631,12 @@ Defines the schema of a KV store. You can create a **Schema** object and place i ...@@ -682,12 +631,12 @@ Defines the schema of a KV store. You can create a **Schema** object and place i
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
| Name | Type| Description | | Name | Type| Readable| Writable| Description |
| --- | ---- | ----------------------- | | --- | ---- | ---- | ---- | ----------------------- |
| root<sup>8+</sup> | [FieldNode](#fieldnode8) | JSON root object.| | root<sup>8+</sup> | [FieldNode](#fieldnode8) | Yes| Yes| JSON root object.|
| indexes<sup>8+</sup> | Array\<string> | String array in JSON format. | | indexes<sup>8+</sup> | Array\<string> | Yes| Yes| String array in JSON format. |
| mode<sup>8+</sup> | number | Schema mode. | | mode<sup>8+</sup> | number | Yes| Yes| Schema mode. |
| skip<sup>8+</sup> | number | Size of a skip of the schema. | | skip<sup>8+</sup> | number | Yes| Yes| Size of a skip of the schema. |
### constructor<sup>8+</sup> ### constructor<sup>8+</sup>
...@@ -703,11 +652,11 @@ Represents a **Schema** instance, which provides the methods for defining the va ...@@ -703,11 +652,11 @@ Represents a **Schema** instance, which provides the methods for defining the va
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
| Name | Type| Description | | Name | Type| Readable| Writable| Description |
| --- | ---- | ----------------------- | | --- | ---- | ---- | ---- | ----------------------- |
| nullable<sup>8+</sup> | boolean | Whether the database field can be null. | | nullable<sup>8+</sup> | boolean | Yes| Yes| Whether the database field can be null. |
| default<sup>8+</sup> | string | Default value of a **FieldNode**.| | default<sup>8+</sup> | string | Yes| Yes| Default value of a **FieldNode**.|
| type<sup>8+</sup> | number | Value of the data type corresponding to the specified node.| | type<sup>8+</sup> | number | Yes| Yes| Value of the data type corresponding to the specified node.|
### constructor<sup>8+</sup> ### constructor<sup>8+</sup>
...@@ -1389,7 +1338,7 @@ Creates a **Query** object to match the specified field whose value is less than ...@@ -1389,7 +1338,7 @@ Creates a **Query** object to match the specified field whose value is less than
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| fieId | string | Yes |Field to match. It cannot contain '^'. | | fieId | string | Yes |Field to match. It cannot contain '^'. |
| value | number\|string\|boolean | Yes | Value specified.| | value | number\|string | Yes | Value specified.|
**Return value** **Return value**
...@@ -1424,7 +1373,7 @@ Creates a **Query** object to match the specified field whose value is greater t ...@@ -1424,7 +1373,7 @@ Creates a **Query** object to match the specified field whose value is greater t
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| fieId | string | Yes |Field to match. It cannot contain '^'. | | fieId | string | Yes |Field to match. It cannot contain '^'. |
| value | number\|string\|boolean | Yes | Value specified.| | value | number\|string | Yes | Value specified.|
**Return value** **Return value**
...@@ -1459,7 +1408,7 @@ Creates a **Query** object to match the specified field whose value is less than ...@@ -1459,7 +1408,7 @@ Creates a **Query** object to match the specified field whose value is less than
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| fieId | string | Yes |Field to match. It cannot contain '^'. | | fieId | string | Yes |Field to match. It cannot contain '^'. |
| value | number\|string\|boolean | Yes | Value specified.| | value | number\|string | Yes | Value specified.|
**Return value** **Return value**
...@@ -2160,7 +2109,6 @@ try { ...@@ -2160,7 +2109,6 @@ try {
} }
``` ```
### put ### put
put(key: string, value: Uint8Array | string | number | boolean): Promise&lt;void&gt; put(key: string, value: Uint8Array | string | number | boolean): Promise&lt;void&gt;
...@@ -2282,681 +2230,296 @@ try { ...@@ -2282,681 +2230,296 @@ try {
} }
``` ```
### delete<sup>9+</sup> ### on('dataChange')
delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;void&gt;)
Deletes KV pairs that meet the specified conditions. This API uses an asynchronous callback to return the result. on(event: 'dataChange', type: SubscribeType, listener: Callback&lt;ChangeNotification&gt;): void
**System API**: This is a system API. Subscribes to data changes of the specified type.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- |
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| | event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.|
| callback | AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. | | type | [SubscribeType](#subscribetype) | Yes | Type of data change. |
| listener |Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes |Callback invoked to return a data change event.|
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore; let kvStore;
try { kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
let predicates = new dataSharePredicates.DataSharePredicates(); console.log("dataChange callback call data: " + JSON.stringify(data));
kvStore.delete(predicates, function (err, data) { });
if (err == undefined) {
console.log('delete success');
} else {
console.log('delete fail' + err);
}
});
} catch (e) {
console.log('An unexpected error occurred. Error:' + e);
}
``` ```
### delete<sup>9+</sup> ### on('syncComplete')
delete(predicates: dataSharePredicates.DataSharePredicates): Promise&lt;void&gt;
Deletes KV pairs that meet the specified conditions. This API uses a promise to return the result. on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
**System API**: This is a system API. Subscribes to synchronization complete events.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ |
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| | event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.|
| syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes | Callback invoked to return a synchronization complete event. |
**Return value**
| Type | Description |
| ------ | ------- |
| Promise&lt;void&gt; |Promise that returns no value.|
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore; let kvStore;
try { kvStore.on('syncComplete', function (data) {
let predicates = new dataSharePredicates.DataSharePredicates(); console.log("callback call data: " + data);
let arr = ["name"]; });
predicates.inKeys(arr);
kvStore.put("name", "bob").then((data) => {
console.log('put success' + JSON.stringify(data));
kvStore.delete(predicates).then((data) => {
console.log('delete success');
}).catch((err) => {
console.log('delete fail' + JSON.stringify(err));
});
}) .catch((err) => {
console.log(' put fail' + err);
});
}catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
``` ```
### backup<sup>9+</sup> ### off('dataChange')<sup>8+</sup>
backup(file:string, callback: AsyncCallback&lt;void&gt;):void off(event:'dataChange', listener?: Callback&lt;ChangeNotification&gt;): void
Backs up an RDB store. This API uses an asynchronous callback to return the result. Unsubscribes from data changes.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- |
| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| | event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is the error object.| | listener |Callback&lt;[ChangeNotification](#changenotification)&gt; |No |Callback for the data change event.|
**Example** **Example**
```js ```js
let kvStore; let kvStore;
let file = "BK001"; class KvstoreModel {
try { call(data) {
kvStore.backup(file, (err, data) => { console.log("dataChange: " + data);
if (err) { }
console.info("backup err : " + err); subscribeDataChange() {
} else { if (kvStore != null) {
console.info("backup data : " + data); kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
}
}
unsubscribeDataChange() {
if (kvStore != null) {
kvStore.off('dataChange', this.call);
}
} }
});
} catch (e) {
console.log("An unexpected error occurred. Error : " + e);
} }
``` ```
### backup<sup>9+</sup> ### off('syncComplete')<sup>8+</sup>
backup(file:string): Promise&lt;void&gt; off(event: 'syncComplete', syncCallback?: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Backs up an RDB store. This API uses a promise to return the result. Unsubscribes from synchronization complete events.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description | | Name | Type | Mandatory| Description |
| ------ | -------- | ---- | ------------------------------------------------------------ | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- |
| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| | event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.|
| syncCallback |Callback&lt;Array&lt;[string, number]&gt;&gt; | No |Callback for the synchronization complete event. |
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
```js ```js
let kvStore; let kvStore;
let file = "BK001"; class KvstoreModel {
try { call(data) {
kvStore.backup(file).then((data) => { console.log("syncComplete: " + data);
console.info("backup data : " + data); }
}).catch((err) => { subscribeSyncComplete() {
console.info("backup err : " + err); if (kvStore != null) {
}); kvStore.on('syncComplete', this.call);
} catch (e) { }
console.log("An unexpected error occurred. Error : " + e); }
unsubscribeSyncComplete() {
if (kvStore != null) {
kvStore.off('syncComplete', this.call);
}
}
} }
``` ```
### restore<sup>9+</sup> ### putBatch<sup>8+</sup>
restore(file:string, callback: AsyncCallback&lt;void&gt;):void putBatch(entries: Entry[], callback: AsyncCallback&lt;void&gt;): void
Restores an RDB store from a database file. This API uses an asynchronous callback to return the result. Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type| Mandatory | Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ | | ----- | ------ | ---- | ----------------------- |
| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| | callback |AsyncCallback&lt;void&gt; |Yes |Callback invoked to return the result.|
**Example** **Example**
```js ```js
let kvStore; let kvStore;
let file = "BK001";
try { try {
kvStore.restore(file, (err, data) => { let entries = [];
if (err) { for (var i = 0; i < 10; i++) {
console.info("restore err : " + err); var key = 'batch_test_string_key';
} else { var entry = {
console.info("restore data : " + data); key : key + i,
value : {
type : distributedData.ValueType.STRING,
value : 'batch_test_string_value'
}
}
entries.push(entry);
} }
console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success');
kvStore.getEntries('batch_test_string_key', function (err,entries) {
console.log('getEntries success');
console.log('entries.length: ' + entries.length);
console.log('entries[0]: ' + JSON.stringify(entries[0]));
}); });
} catch (e) { });
console.log("An unexpected error occurred. Error : " + e); }catch(e) {
console.log('PutBatch e ' + JSON.stringify(e));
} }
``` ```
### restore<sup>9+</sup>
restore(file:string): Promise&lt;void&gt; ### putBatch<sup>8+</sup>
putBatch(entries: Entry[]): Promise&lt;void&gt;
Restores an RDB store from a database file. This API uses a promise to return the result. Inserts KV pairs in batches to this KV store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description | | Name | Type| Mandatory | Description |
| ------ | -------- | ---- | ------------------------------------------------------------ | | ----- | ------ | ---- | ----------------------- |
| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ------------------------- | | ------ | ------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; |Promise that returns no value.|
**Example** **Example**
```js ```js
let kvStore; let kvStore;
let file = "BK001";
try { try {
kvStore.restore(file).then((data) => { let entries = [];
console.info("restore data : " + data); for (var i = 0; i < 10; i++) {
var key = 'batch_test_string_key';
var entry = {
key : key + i,
value : {
type : distributedData.ValueType.STRING,
value : 'batch_test_string_value'
}
}
entries.push(entry);
}
console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success');
kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('getEntries success');
console.log('PutBatch ' + JSON.stringify(entries));
}).catch((err) => { }).catch((err) => {
console.info("restore err : " + err); console.log('getEntries fail ' + JSON.stringify(err));
}); });
} catch (e) { }).catch((err) => {
console.log("An unexpected error occurred. Error : " + e); console.log('putBatch fail ' + JSON.stringify(err));
});
}catch(e) {
console.log('PutBatch e ' + JSON.stringify(e));
} }
``` ```
### deleteBackup<sup>9+</sup> ### deleteBatch<sup>8+</sup>
deleteBackup(files:Array&lt;string&gt;, callback: AsyncCallback&lt;Array&lt;[string, number]&gt;&gt;):void deleteBatch(keys: string[], callback: AsyncCallback&lt;void&gt;): void
Deletes a backup file. This API uses an asynchronous callback to return the result. Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type| Mandatory | Description |
| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | | ----- | ------ | ---- | ----------------------- |
| files | Array&lt;string&gt; | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | | keys |string[] | Yes |KV pairs to delete in batches. |
| callback | AsyncCallback&lt;Array&lt;[string, number]&gt;&gt; | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | | callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example** **Example**
```js ```js
let kvStore; let kvStore;
let files = ["BK001", "BK002"];
try { try {
kvStore.deleteBackup(files, (err, data) => { let entries = [];
if (err) { let keys = [];
console.info("deleteBackup err : " + err); for (var i = 0; i < 5; i++) {
} else { var key = 'batch_test_string_key';
console.info("deleteBackup data : " + data); var entry = {
key : key + i,
value : {
type : distributedData.ValueType.STRING,
value : 'batch_test_string_value'
} }
}
entries.push(entry);
keys.push(key + i);
}
console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success');
kvStore.deleteBatch(keys, async function (err,data) {
console.log('deleteBatch success');
}); });
} catch (e) { });
console.log("An unexpected error occurred. Error : " + e); }catch(e) {
console.log('DeleteBatch e ' + e);
} }
``` ```
### deleteBackup<sup>9+</sup>
deleteBackup(files:Array&lt;string&gt;): Promise&lt;Array&lt;[string, number]&gt;&gt; ### deleteBatch<sup>8+</sup>
deleteBatch(keys: string[]): Promise&lt;void&gt;
Deletes a backup file. This API uses a promise to return the result. Deletes KV pairs in batches from this KV store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description | | Name | Type| Mandatory | Description |
| ------ | -------- | ---- | ------------------------------------------------------------ | | ----- | ------ | ---- | ----------------------- |
| files | Array&lt;string&gt; | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| | keys |string[] | Yes |KV pairs to delete in batches. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------------------------------------- | ----------------------------------------------- | | ------ | ------- |
| Promise&lt;Array&lt;[string, number]&gt;&gt; | Promise used to return the name of the backup file deleted and the operation result.| | Promise&lt;void&gt; |Promise that returns no value.|
**Example**
```js
let kvStore;
let files = ["BK001", "BK002"];
try {
kvStore.deleteBackup(files).then((data) => {
console.info("deleteBackup data : " + data);
}).catch((err) => {
console.info("deleteBackup err : " + err);
})
} catch (e) {
console.log("An unexpected error occurred. Error : " + e);
}
```
### on('dataChange')
on(event: 'dataChange', type: SubscribeType, listener: Callback&lt;ChangeNotification&gt;): void
Subscribes to data changes of the specified type. This API returns the result synchronously.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. |
| type |[SubscribeType](#subscribetype) | Yes |Type of data change. |
| listener |Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes |Callback invoked to return a data change event.|
**Example**
```js
let kvStore;
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
});
```
### on('syncComplete')
on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Subscribes to synchronization complete events. This API returns the result synchronously.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. |
| syncCallback |Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes |Callback invoked to return a synchronization complete event.|
**Example**
```js
let kvStore;
kvStore.on('syncComplete', function (data) {
console.log("callback call data: " + data);
});
```
### off('dataChange')<sup>8+</sup>
off(event:'dataChange', listener?: Callback&lt;ChangeNotification&gt;): void
Unsubscribes from data changes. This API returns the result synchronously.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. |
| listener |Callback&lt;[ChangeNotification](#changenotification)&gt; |No |Callback for the data change event.|
**Example**
```js
let kvStore;
class KvstoreModel {
call(data) {
console.log("dataChange: " + data);
}
subscribeDataChange() {
if (kvStore != null) {
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
}
}
unsubscribeDataChange() {
if (kvStore != null) {
kvStore.off('dataChange', this.call);
}
}
}
```
### off('syncComplete')<sup>9+</sup>
off(event: 'syncComplete', syncCallback?: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Unsubscribes from the synchronization complete events. This API returns the result synchronously.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. |
| syncCallback |Callback&lt;Array&lt;[string, number]&gt;&gt; | No |Callback for the synchronization complete event. |
**Example**
```js
let kvStore;
class KvstoreModel {
call(data) {
console.log("syncComplete: " + data);
}
subscribeSyncComplete() {
if (kvStore != null) {
kvStore.on('syncComplete', this.call);
}
}
unsubscribeSyncComplete() {
if (kvStore != null) {
kvStore.off('syncComplete', this.call);
}
}
}
```
### putBatch<sup>8+</sup>
putBatch(entries: Entry[], callback: AsyncCallback&lt;void&gt;): void
Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
| callback |Asyncallback&lt;void&gt; |Yes |Callback invoked to return the result.|
**Example**
```js
let kvStore;
try {
let entries = [];
for (var i = 0; i < 10; i++) {
var key = 'batch_test_string_key';
var entry = {
key : key + i,
value : {
type : distributedData.ValueType.STRING,
value : 'batch_test_string_value'
}
}
entries.push(entry);
}
console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success');
kvStore.getEntries('batch_test_string_key', function (err,entries) {
console.log('getEntries success');
console.log('entries.length: ' + entries.length);
console.log('entries[0]: ' + JSON.stringify(entries[0]));
});
});
}catch(e) {
console.log('PutBatch e ' + JSON.stringify(e));
}
```
### putBatch<sup>8+</sup>
putBatch(entries: Entry[]): Promise&lt;void&gt;
Inserts KV pairs in batches to this KV store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
**Return value**
| Type | Description |
| ------ | ------- |
| Promise&lt;void&gt; |Promise that returns no value.|
**Example**
```js
let kvStore;
try {
let entries = [];
for (var i = 0; i < 10; i++) {
var key = 'batch_test_string_key';
var entry = {
key : key + i,
value : {
type : distributedData.ValueType.STRING,
value : 'batch_test_string_value'
}
}
entries.push(entry);
}
console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success');
kvStore.getEntries('batch_test_string_key').then((entries) => {
console.log('getEntries success');
console.log('PutBatch ' + JSON.stringify(entries));
}).catch((err) => {
console.log('getEntries fail ' + JSON.stringify(err));
});
}).catch((err) => {
console.log('putBatch fail ' + JSON.stringify(err));
});
}catch(e) {
console.log('PutBatch e ' + JSON.stringify(e));
}
```
### putBatch<sup>9+</sup>
putBatch(value: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;void&gt;): void
Writes data to this KV store. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| value |Array&lt;[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)&gt; | Yes |Data to write. |
| callback |Asyncallback&lt;void&gt; |Yes |Callback invoked to return the result.|
**Example**
```js
let kvStore;
try {
let v8Arr = [];
let arr = new Uint8Array([4,5,6,7]);
let vb1 = {key : "name_1", value : 32}
let vb2 = {key : "name_2", value : arr};
let vb3 = {key : "name_3", value : "lisi"};
v8Arr.push(vb1);
v8Arr.push(vb2);
v8Arr.push(vb3);
kvStore.putBatch(v8Arr, async function (err,data) {
console.log('putBatch success');
}).catch((err) => {
console.log('putBatch fail ' + JSON.stringify(err));
});
}catch(e) {
console.log('putBatch e ' + JSON.stringify(e));
}
```
### putBatch<sup>9+</sup>
putBatch(value: Array&lt;ValuesBucket&gt;): Promise&lt;void&gt;
Write data to this KV store. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| value |Array&lt;[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)&gt; | Yes |Data to write. |
**Return value**
| Type | Description |
| ------ | ------- |
| Promise&lt;void&gt; |Promise that returns no value.|
**Example**
```js
let kvStore;
try {
let v8Arr = [];
let arr = new Uint8Array([4,5,6,7]);
let vb1 = {key : "name_1", value : 32}
let vb2 = {key : "name_2", value : arr};
let vb3 = {key : "name_3", value : "lisi"};
v8Arr.push(vb1);
v8Arr.push(vb2);
v8Arr.push(vb3);
kvStore.putBatch(v8Arr).then(async (err) => {
console.log('putBatch success');
}).catch((err) => {
console.log('putBatch fail ' + JSON.stringify(err));
});
}catch(e) {
console.log('PutBatch e ' + JSON.stringify(e));
}
```
### deleteBatch<sup>8+</sup>
deleteBatch(keys: string[], callback: AsyncCallback&lt;void&gt;): void
Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| keys |string[] | Yes |KV pairs to delete in batches. |
| callback |AsyncCallback&lt;void&gt; | Yes |Callback invoked to return the result. |
**Example**
```js
let kvStore;
try {
let entries = [];
let keys = [];
for (var i = 0; i < 5; i++) {
var key = 'batch_test_string_key';
var entry = {
key : key + i,
value : {
type : distributedData.ValueType.STRING,
value : 'batch_test_string_value'
}
}
entries.push(entry);
keys.push(key + i);
}
console.log('entries: ' + JSON.stringify(entries));
kvStore.putBatch(entries, async function (err,data) {
console.log('putBatch success');
kvStore.deleteBatch(keys, async function (err,data) {
console.log('deleteBatch success');
});
});
}catch(e) {
console.log('DeleteBatch e ' + e);
}
```
### deleteBatch<sup>8+</sup>
deleteBatch(keys: string[]): Promise&lt;void&gt;
Deletes KV pairs in batches from this KV store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| keys |string[] | Yes |KV pairs to delete in batches. |
**Return value**
| Type | Description |
| ------ | ------- |
| Promise&lt;void&gt; |Promise that returns no value.|
**Example** **Example**
...@@ -3364,12 +2927,12 @@ Defines the content of data change notifications, including inserted data, updat ...@@ -3364,12 +2927,12 @@ Defines the content of data change notifications, including inserted data, updat
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Type |Readable |Writable | Description | | Name | Type |Mandatory | Description |
| ----- | ------- | -----| ------|------------------------ | | ----- | ------- | ------|------------------------ |
| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. | | insertEntries | [Entry](#entry)[] | Yes|Data inserted. |
| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. | | updateEntries | [Entry](#entry)[] | Yes|Data updated. |
| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. | | deleteEntries | [Entry](#entry)[] | Yes|Data deleted. |
| deviceId | string | Yes | Yes|UUID of the device. | | deviceId | string | Yes|UUID of the device. |
## Entry ## Entry
...@@ -3377,10 +2940,10 @@ Defines the KV pairs stored in the KV store. ...@@ -3377,10 +2940,10 @@ Defines the KV pairs stored in the KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Type |Readable |Writable | Description | | Name | Type |Mandatory | Description |
| ----- | ------- | -----| ------|------------------------ | | ----- | ------- | ------|------------------------ |
| key | string | Yes | Yes|Key of the KV pair stored in the KV store. | | key | string | Yes|Key of the KV pair stored in the KV store. |
| value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. | | value | [Value](#value) | Yes|Value of the KV pair stored in the KV store. |
## Value ## Value
...@@ -3389,10 +2952,10 @@ Defines the **value** object in a KV store. ...@@ -3389,10 +2952,10 @@ Defines the **value** object in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Type |Readable |Writable | Description | | Name | Type |Mandatory | Description |
| ----- | ------- | -----| ------|------------------------ | | ----- | ------- | ------|------------------------ |
| type | [ValueType](#value) | Yes | Yes|Type of the value. | | type | [ValueType](#value) | Yes|Type of the value. |
| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | | value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. |
## ValueType ## ValueType
...@@ -3430,7 +2993,7 @@ Obtains the value of the specified key. This API uses an asynchronous callback t ...@@ -3430,7 +2993,7 @@ Obtains the value of the specified key. This API uses an asynchronous callback t
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
| callback |AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;) | Yes |Callback invoked to return the value obtained. | | callback |AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt; | Yes |Callback invoked to return the value obtained. |
**Example** **Example**
...@@ -3896,113 +3459,34 @@ try { ...@@ -3896,113 +3459,34 @@ try {
let resultSet; let resultSet;
let entries = []; let entries = [];
for (var i = 0; i < 10; i++) { for (var i = 0; i < 10; i++) {
var key = 'batch_test_string_key'; var key = 'batch_test_string_key';
var entry = { var entry = {
key : key + i, key : key + i,
value : { value : {
type : distributedData.ValueType.STRING, type : distributedData.ValueType.STRING,
value : 'batch_test_string_value' value : 'batch_test_string_value'
} }
} }
entries.push(entry); entries.push(entry);
} }
kvStore.putBatch(entries).then(async (err) => { kvStore.putBatch(entries).then(async (err) => {
console.log('putBatch success'); console.log('putBatch success');
}).catch((err) => { }).catch((err) => {
console.log('putBatch fail ' + JSON.stringify(err)); console.log('putBatch fail ' + JSON.stringify(err));
}); });
const query = new distributedData.Query(); const query = new distributedData.Query();
query.prefixKey("batch_test"); query.prefixKey("batch_test");
kvStore.getResultSet(query).then((result) => { kvStore.getResultSet(query).then((result) => {
console.log(' getResultSet succeed.'); console.log(' getResultSet succeed.');
resultSet = result;
}).catch((err) => {
console.log('getResultSet failed: ' + JSON.stringify(err));
});
}catch(e) {
console.log('GetResultSet e ' + e);
}
```
### getResultSet<sup>9+</sup>
getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KvStoreResultSet&gt;): void
Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.|
**Example**
```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try {
let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet(predicates, async function (err, result) {
console.log(' GetResultSet success');
resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) {
console.log(' closeResultSet success');
})
});
}catch(e) {
console.log('An unexpected error occurred. Error:' + e);
}
```
### getResultSet<sup>9+</sup>
getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KvStoreResultSet&gt;
Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. |
**Return value**
| Type | Description |
| ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise that returns no value.|
**Example**
```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';
let kvStore;
try {
let resultSet;
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.prefixKey("batch_test_string_key");
kvStore.getResultSet(predicates) .then((result) => {
console.log(' GetResultSet success');
resultSet = result; resultSet = result;
kvStore.closeResultSet(resultSet, function (err, data) { }).catch((err) => {
console.log(' closeResultSet success'); console.log('getResultSet failed: ' + JSON.stringify(err));
})
}); });
}catch(e) { }catch(e) {
console.log('An unexpected error occurred. Error:' + e); console.log('GetResultSet e ' + e);
} }
``` ```
### closeResultSet<sup>8+</sup> ### closeResultSet<sup>8+</sup>
closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback&lt;void&gt;): void closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback&lt;void&gt;): void
...@@ -4265,118 +3749,105 @@ try { ...@@ -4265,118 +3749,105 @@ try {
} }
``` ```
### sync
### on('syncComplete')<sup>8+</sup>
on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
Subscribes to synchronization complete events. This API returns the result synchronously. Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md).
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | --------- | --------------------- | ---- | ---------------------------------------------- |
| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | | deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.|
| syncCallback |Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes |Callback invoked to return a synchronization complete event. | | mode | [SyncMode](#syncmode) | Yes | Synchronization mode. |
| delayMs | number | No | Allowed synchronization delay time, in ms. |
**Example** **Example**
```js ```js
let kvStore; let kvStore;
const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; kvStore.sync(['deviceIds'], distributedData.SyncMode.PULL_ONLY, 1000);
const VALUE_TEST_FLOAT_ELEMENT = 321.12;
try {
kvStore.on('syncComplete', function (data) {
console.log('syncComplete ' + data)
});
kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
console.log('syncComplete put success');
}).catch((error) => {
console.log('syncComplete put fail ' + error);
});
}catch(e) {
console.log('syncComplete put e ' + e);
}
``` ```
### on('dataChange')<sup>8+</sup>
### off('syncComplete')<sup>8+</sup> on(event: 'dataChange', type: SubscribeType, listener: Callback&lt;ChangeNotification&gt;): void
off(event: 'syncComplete', syncCallback?: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Unsubscribes from synchronization complete events. This API returns the result synchronously. Subscribes to data changes of the specified type.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- |
| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | | event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.|
| syncCallback |Callback&lt;Array&lt;[string, number]&gt;&gt; | No |Callback for the synchronization complete event. | | type | [SubscribeType](#subscribetype) | Yes | Type of data change. |
| listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
```js ```js
let kvStore; let kvStore;
class KvstoreModel { kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
call(data) { console.log("dataChange callback call data: " + JSON.stringify(data));
console.log("syncComplete: " + data); });
}
subscribeSyncComplete() {
if (kvStore != null) {
kvStore.on('syncComplete', this.call);
}
}
unsubscribeSyncComplete() {
if (kvStore != null) {
kvStore.off('syncComplete', this.call);
}
}
}
``` ```
### on('dataChange')<sup>9+</sup> ### on('syncComplete')<sup>8+</sup>
on(event: 'dataChange', type: SubscribeType, listener: Callback&lt;ChangeNotification&gt;): void on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Subscribes to data changes of the specified type. This API returns the result synchronously. Subscribes to synchronization complete events.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ |
| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | | event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.|
| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | | syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes | Callback invoked to return a synchronization complete event. |
| listener |Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes |Callback invoked to return a data change event.|
**Example** **Example**
```js ```js
let kvStore; let kvStore;
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
console.log("dataChange callback call data: " + JSON.stringify(data)); const VALUE_TEST_FLOAT_ELEMENT = 321.12;
}); try {
kvStore.on('syncComplete', function (data) {
console.log('syncComplete ' + data)
});
kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
console.log('syncComplete put success');
}).catch((error) => {
console.log('syncComplete put fail ' + error);
});
}catch(e) {
console.log('syncComplete put e ' + e);
}
``` ```
### off('dataChange')<sup>9+</sup> ### off('dataChange')<sup>8+</sup>
off(event:'dataChange', listener?: Callback&lt;ChangeNotification&gt;): void off(event:'dataChange', listener?: Callback&lt;ChangeNotification&gt;): void
Unsubscribes from data changes. This API returns the result synchronously. Unsubscribes from data changes.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- |
| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | | event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.|
| listener |Callback&lt;[ChangeNotification](#changenotification)&gt; |No |Callback for the data change event.| | listener |Callback&lt;[ChangeNotification](#changenotification)&gt; |No |Callback for the data change event.|
**Example** **Example**
...@@ -4399,71 +3870,40 @@ class KvstoreModel { ...@@ -4399,71 +3870,40 @@ class KvstoreModel {
} }
} }
``` ```
### sync<sup>7+</sup>
sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md).
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. |
| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
| delayMs |number | No |Allowed synchronization delay time, in ms. |
**Example**
```js
let kvStore;
kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000);
```
### sync<sup>9+</sup> ### off('syncComplete')<sup>8+</sup>
sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). off(event: 'syncComplete', syncCallback?: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC Unsubscribes from synchronization complete events.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- |
| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | | event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.|
| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | | syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | No | Callback for a synchronization complete event. |
| query |[Query](#query8) | Yes |**Query** object to match. |
| delayMs |number | No |Allowed synchronization delay time, in ms. |
**Example** **Example**
```js ```js
let kvStore; let kvStore;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; class KvstoreModel {
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; call(data) {
try { console.log("syncComplete: " + data);
kvStore.on('syncComplete', function (data) { }
console.log('Sync dataChange'); subscribeSyncComplete() {
}); if (kvStore != null) {
kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { kvStore.on('syncComplete', this.call);
console.log('Sync put success'); }
const devices = ['deviceList']; }
const mode = distributedData.SyncMode.PULL_ONLY; unsubscribeSyncComplete() {
const query = new distributedData.Query(); if (kvStore != null) {
query.prefixKey("batch_test"); kvStore.off('syncComplete', this.call);
query.deviceId('localDeviceId'); }
kvStore.sync(devices, query, mode , 1000); }
});
}catch(e) {
console.log('Sync e' + e);
} }
``` ```
...@@ -5026,7 +4466,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k ...@@ -5026,7 +4466,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes |ID of the target device. | | deviceId |string | Yes |ID of the target device. |
| keyPrefix |string | Yes |Key prefix to match. | | keyPrefix |string | Yes |Key prefix to match. |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | | callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
**Example** **Example**
...@@ -5066,7 +4506,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k ...@@ -5066,7 +4506,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k
| Type | Description | | Type | Description |
| ------ | ------- | | ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.| |Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
**Example** **Example**
...@@ -5104,7 +4544,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec ...@@ -5104,7 +4544,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec
| Name | Type| Mandatory | Description | | Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| query |[Query](#query8) | Yes |**Query** object to match. | | query |[Query](#query8) | Yes |**Query** object to match. |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | | callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
**Example** **Example**
...@@ -5161,7 +4601,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec ...@@ -5161,7 +4601,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec
| Type | Description | | Type | Description |
| ------ | ------- | | ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.| |Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
**Example** **Example**
...@@ -5221,7 +4661,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and * ...@@ -5221,7 +4661,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and *
| ----- | ------ | ---- | ----------------------- | | ----- | ------ | ---- | ----------------------- |
| deviceId |string | Yes |ID of the target device. | | deviceId |string | Yes |ID of the target device. |
| query |[Query](#query8) | Yes |**Query** object to match. | | query |[Query](#query8) | Yes |**Query** object to match. |
| callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | | callback |AsyncCallback&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
**Example** **Example**
...@@ -5278,7 +4718,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and * ...@@ -5278,7 +4718,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and *
| Type | Description | | Type | Description |
| ------ | ------- | | ------ | ------- |
|Promise&lt;[KvStoreResultSet](#kvstoreresultset8)[]&gt; |Promise used to return the **KvStoreResultSet** object obtained.| |Promise&lt;[KvStoreResultSet](#kvstoreresultset8)&gt; |Promise used to return the **KvStoreResultSet** object obtained.|
**Example** **Example**
...@@ -5734,62 +5174,45 @@ try { ...@@ -5734,62 +5174,45 @@ try {
} }
``` ```
### sync<sup>9+</sup> ### on('dataChange')<sup>8+</sup>
sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). on(event: 'dataChange', type: SubscribeType, listener: Callback&lt;ChangeNotification&gt;): void
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC Subscribes to data changes of the specified type.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- |
| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| | event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.|
| query |[Query](#query8) | Yes | **Query** object to match.| | type | [SubscribeType](#subscribetype) | Yes | Type of data change. |
| delayMs |number | No |Allowed synchronization delay time, in ms. | | listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
```js ```js
let kvStore; let kvStore;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; console.log("dataChange callback call data: " + JSON.stringify(data));
try { });
kvStore.on('syncComplete', function (data) {
console.log('Sync dataChange');
});
kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) {
console.log('Sync put success');
const devices = ['deviceList'];
const mode = distributedData.SyncMode.PULL_ONLY;
const query = new distributedData.Query();
query.prefixKey("batch_test");
query.deviceId('localDeviceId');
kvStore.sync(devices, query, 1000);
});
}catch(e) {
console.log('Sync e' + e);
}
``` ```
### on('syncComplete')<sup>8+</sup> ### on('syncComplete')<sup>8+</sup>
on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Subscribes to synchronization complete events. This API returns the result synchronously. Subscribes to synchronization complete events.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ |
| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| | event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.|
| syncCallback |Callback<Array&lt;[string, number]&gt;> | Yes |Callback invoked to return a synchronization complete event. | | syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes | Callback invoked to return a synchronization complete event. |
**Example** **Example**
...@@ -5811,21 +5234,20 @@ try { ...@@ -5811,21 +5234,20 @@ try {
} }
``` ```
### off('dataChange')<sup>8+</sup>
### off('syncComplete')<sup>8+</sup> off(event:'dataChange', listener?: Callback&lt;ChangeNotification&gt;): void
off(event: 'syncComplete', syncCallback?: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Unsubscribes from synchronization complete events. This API returns the result synchronously. Unsubscribes from data changes.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- |
| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| | event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.|
| syncCallback |Callback<Array&lt;[string, number]&gt;&gt; | No |Callback for the synchronization complete event. | | listener |Callback&lt;[ChangeNotification](#changenotification)&gt; |No |Callback for the data change event.|
**Example** **Example**
...@@ -5833,61 +5255,35 @@ Unsubscribes from synchronization complete events. This API returns the result s ...@@ -5833,61 +5255,35 @@ Unsubscribes from synchronization complete events. This API returns the result s
let kvStore; let kvStore;
class KvstoreModel { class KvstoreModel {
call(data) { call(data) {
console.log("syncComplete: " + data); console.log("dataChange: " + data);
} }
subscribeSyncComplete() { subscribeDataChange() {
if (kvStore != null) { if (kvStore != null) {
kvStore.on('syncComplete', this.call); kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
} }
} }
unsubscribeSyncComplete() { unsubscribeDataChange() {
if (kvStore != null) { if (kvStore != null) {
kvStore.off('syncComplete', this.call); kvStore.off('dataChange', this.call);
} }
} }
} }
``` ```
### on('dataChange')<sup>9+</sup> ### off('syncComplete')<sup>8+</sup>
on(event: 'dataChange', type: SubscribeType, listener: Callback&lt;ChangeNotification&gt;): void
Subscribes to data changes of the specified type. This API returns the result synchronously.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters**
| Name | Type| Mandatory | Description |
| ----- | ------ | ---- | ----------------------- |
| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. |
| type |[SubscribeType](#subscribetype) | Yes |Type of data change. |
| listener |Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes |Callback invoked to return a data change event.|
**Example**
```js
let kvStore;
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
});
```
### off('dataChange')<sup>9+</sup>
off(event:'dataChange', listener?: Callback&lt;ChangeNotification&gt;): void off(event: 'syncComplete', syncCallback?: Callback&lt;Array&lt;[string, number]&gt;&gt;): void
Unsubscribes from data changes. This API returns the result synchronously. Unsubscribes from synchronization complete events.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Parameters** **Parameters**
| Name | Type| Mandatory | Description | | Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ----------------------- | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- |
| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | | event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.|
| listener |Callback&lt;[ChangeNotification](#changenotification)&gt; |No |Callback for the data change event.| | syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | No | Callback for a synchronization complete event. |
**Example** **Example**
...@@ -5895,16 +5291,16 @@ Unsubscribes from data changes. This API returns the result synchronously. ...@@ -5895,16 +5291,16 @@ Unsubscribes from data changes. This API returns the result synchronously.
let kvStore; let kvStore;
class KvstoreModel { class KvstoreModel {
call(data) { call(data) {
console.log("dataChange: " + data); console.log("syncComplete: " + data);
} }
subscribeDataChange() { subscribeSyncComplete() {
if (kvStore != null) { if (kvStore != null) {
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); kvStore.on('syncComplete', this.call);
} }
} }
unsubscribeDataChange() { unsubscribeSyncComplete() {
if (kvStore != null) { if (kvStore != null) {
kvStore.off('dataChange', this.call); kvStore.off('syncComplete', this.call);
} }
} }
} }
......
因为 它太大了无法显示 source diff 。你可以改为 查看blob
# Distributed KV Store Error Codes
## 15100001 Subscription Count Reaches the Limit
**Error Message**
Over max subscribe limits.
**Description**
The number of subscriptions has reached the limit for **on('dataChange')**.
**Possible Causes**
The number of subscriptions has reached the limit for **on('dataChange')**.
**Solution**
Unregister unnecessary subscriptions and try again.
## 15100002 Parameter Configuration Changes
**Error Message**
Open existed database with changed options.
**Description**
The **options** configuration changes when **getKVStore()** is called to obtain a KV store.
**Possible Causes**
The possible causes are as follows:
1. An existing **storeId** is used to create a KV store.
2. You want to change the **options** parameter of a KV store.
**Solution**
1. When creating a KV store, do not use a duplicate **storeId**.
2. Currently, the **options** parameter of a KV store cannot be changed. To apply the change, delete the KV store and create a KV store with the required **options** settings.
## 15100003 KV Store Corrupted
**Error Message**
Database corrupted.
**Description**
The target KV store is corrupted.
**Possible Causes**
The target KV store is corrupted.
**Solution**
1. Restore the KV store from a backup file.
2. If no backup file is available, delete the corrupted KV store and create a new one.
## 15100004 Failed to Find Data
**Error Message**
Not found.
**Description**
Related data is found when **deleteKVStore()**, **delete()**, **deleteBatch()**, or **get()** is called.
**Possible Causes**
The possible causes are as follows:
1. The KV store to delete does not exist or has been deleted.
2. The data queried does not exist or has been deleted.
3. The data to delete does not exist or has been deleted.
**Solution**
1. Before deleting a KV store, check that the KV store exists.
2. When querying data in a KV store, check whether the query keywords are correct.
3. When deleting data from a KV store, check that the keyword for the deletion is correct and the data to delete exists.
## 15100005 KV Store or Result Set Closed
**Error Message**
Database or result set already closed.
**Description**
The KV store or result set to operate is already closed.
**Possible Causes**
The KV store or result set is closed manually before the operation.
**Solution**
1. Obtain the KV store and try again.
2. Obtain the result set and try again.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册