diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index 8cec5ca111cd814d599d159ab7b333259f669ea8..73f785de4ddccaa1e10c6049066a5f3908d85fc6 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -6,20 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat ## 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 -| API | Description | -| ------------------------------------------------------------ | ----------------------------------------------- | -| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| -| getKVStore<TextendsKVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<TextendsKVStore>(storeId: string, options: Options): Promise<T> | Obtains a KV store with the specified **Options** and **storeId**.| -| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. | -| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | -| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Queries data. | -| on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string,number]>>): void | Subscribes to data changes in the KV store. | -| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KvManager** object for database management. | +| getKVStore<TextendsKVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<TextendsKVStore>(storeId: string, options: Options): Promise<T> | Creates and obtains a KV store.| +| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. | +| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | +| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Queries data. | +| on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string,number]>>): void | Subscribes to data changes in the KV store. | +| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | ## How to Develop @@ -28,23 +28,25 @@ The following uses a single KV store as an example to describe the development p 1. Import the distributed data module. ```js - import distributedData from '@ohos.data.distributedData'; + import distributedKVStore from '@ohos.data.distributedKVStore'; ``` + 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: ```json - { - "module": { - "reqPermissions": [ - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } - ] - } - } + { + "module": { + "reqPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } + ] + } + } ``` + For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model). This permission must also be granted by the user when the application is started for the first time. The sample code is as follows: @@ -52,7 +54,7 @@ The following uses a single KV store as an example to describe the development p ```js // FA model import featureAbility from '@ohos.ability.featureAbility'; - + function grantPermission() { console.info('grantPermission'); let context = featureAbility.getContext(); @@ -62,21 +64,21 @@ The following uses a single KV store as an example to describe the development p console.info('failed: ${error}'); }) } - + grantPermission(); - + // Stage model import Ability from '@ohos.application.Ability'; - + let context = null; - + function grantPermission() { class MainAbility extends Ability { onWindowStageCreate(windowStage) { let context = this.context; } } - + let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; context.requestPermissionsFromUser(permissions).then((data) => { console.log('success: ${data}'); @@ -84,14 +86,14 @@ The following uses a single KV store as an example to describe the development p console.log('failed: ${error}'); }); } - + 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. - 2. Create a **kvManager** instance. + 2. Create a **KvManager** instance. The sample code is as follows: @@ -99,7 +101,7 @@ The following uses a single KV store as an example to describe the development p // Obtain the context of the FA model. import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); - + // Obtain the context of the stage model. import AbilityStage from '@ohos.application.Ability'; let context = null; @@ -108,27 +110,23 @@ The following uses a single KV store as an example to describe the development p context = this.context; } } - + let kvManager; try { const kvManagerConfig = { bundleName: 'com.example.datamanagertest', - userInfo: { - context:context, - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } + context:context, } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { + distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { if (err) { - console.log('Failed to create KVManager: ${error}'); + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); return; } console.log('Created KVManager successfully'); kvManager = manager; }); } 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,34 +145,38 @@ The following uses a single KV store as an example to describe the development p encrypt: false, backup: false, autoSync: false, - kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, - securityLevel: distributedData.SecurityLevel.S0 + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + securityLevel: distributedKVStore.SecurityLevel.S1 }; kvManager.getKVStore('storeId', options, function (err, store) { if (err) { - console.log('Failed to get KVStore: ${err}'); + console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`); return; } - console.log('Got KVStore successfully'); + console.log('Obtained KVStore successfully'); kvStore = store; }); } catch (e) { - console.log('An unexpected error occurred. Error: ${e}'); + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` > **NOTE**
> > For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. - + 5. Subscribe to changes in the distributed data. The following is the sample code for subscribing to the data changes of a single KV store: ```js - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { - console.log("dataChange callback call data: ${data}"); - }); + try{ + 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. @@ -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 VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { - console.log('Failed to put data: ${error}'); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } console.log('Put data successfully'); }); - } catch (e) { - console.log('An unexpected error occurred. Error: ${e}'); + }catch (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 const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { - console.log('Failed to put data: ${error}'); + console.error(`Failed to put.code is ${err.code},message is ${err.message}`); return; } console.log('Put data successfully'); - kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { - console.log('Got data successfully: ${data}'); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,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) { - console.log('An unexpected error occurred. Error: ${e}'); + }catch (e) { + console.error(`Failed to get.code is ${e.code},message is ${e.message}`); } ``` @@ -233,7 +239,7 @@ The following uses a single KV store as an example to describe the development p > **NOTE**
> > The APIs of the `deviceManager` module are system interfaces. - + The following is the example code for synchronizing data in a single KV store: ```js @@ -254,9 +260,9 @@ The following uses a single KV store as an example to describe the development p } try{ // 1000 indicates that the maximum delay is 1000 ms. - kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); + kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000); } catch (e) { - console.log('An unexpected error occurred. Error: ${e}'); + console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`); } } }); diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 32c2d5b1d1d7d78c1247a375cf17d53505050478..feb018281da35356278e1e16bddbc8638a323a47 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -18,7 +18,7 @@ - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - [@ohos.application.StartOptions](js-apis-application-StartOptions.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/[ApplicationContext](js-apis-application-applicationContext.md) - application/[AbilityStageContext](js-apis-abilitystagecontext.md) @@ -127,6 +127,7 @@ - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.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.rdb](js-apis-data-rdb.md) - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) @@ -173,7 +174,7 @@ - Basic Features - [@ohos.accessibility](js-apis-accessibility.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.hichecker](js-apis-hichecker.md) - [@ohos.hidebug](js-apis-hidebug.md) @@ -181,8 +182,8 @@ - [@ohos.hiSysEvent](js-apis-hisysevent.md) - [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - - [@ohos.inputMethod](js-apis-inputmethod.md) - - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.inputmethod](js-apis-inputmethod.md) + - [@ohos.inputmethodengine](js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) - [@ohos.pasteboard](js-apis-pasteboard.md) @@ -224,7 +225,7 @@ - [@ohos.account.osAccount](js-apis-osAccount.md) - Custom Management - [@ohos.configPolicy](js-apis-configPolicy.md) - - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - Language Base Class Library - [@ohos.buffer](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index b1ceeabca8640799415596532a757f67d62e92c8..772a7372c276270eaa9a2e2d63d9eec009b06e58 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -13,7 +13,9 @@ This module provides the following functions: >**NOTE**
> ->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 @@ -39,56 +41,28 @@ Creates a **KVManager** instance to manage KV stores. This API uses an asynchron | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| **Example** +```js -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); - } -} -``` - -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; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); } -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 @@ -112,52 +86,28 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to | Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| **Example** +```js -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; - }).catch((err) => { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - }); - } -} -``` - -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; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); } -distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; -}).catch((err) => { - console.log("Failed to create KVManager: " + JSON.stringify(err)); -}); ``` ## KVManagerConfig @@ -168,7 +118,6 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| @@ -179,9 +128,9 @@ Defines user information. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| userId | string | Yes | User ID.| -| userType | [UserType](#usertype) | Yes | User type.| +| ----- | ------ |------ | ------ | +| userId | string | No | User ID.| +| userType | [UserType](#usertype) | No | User type.| ## UserType @@ -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).| | options | [Options](#options) | Yes | Configuration of the KV store.| -| callback | AsyncCallback<T> , <T extends [KVStore](#kvstore)>| Yes | Callback invoked to return the KV store created.| +| callback | AsyncCallback<T> | Yes | Callback invoked to return the KV store created.| **Example** @@ -500,7 +449,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | -| callback | AsyncCallback<string[]> | Yes |Callback invoked to return the KV store IDs obtained. | +| callback | AsyncCallback<string[]> | Yes |Callback invoked to return the KV store IDs obtained.| **Example** @@ -560,7 +509,7 @@ try { on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void -Subscribes to service status changes. This API returns the result synchronously. +Subscribes to service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -591,7 +540,7 @@ try { off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -Unsubscribes from service status changes. This API returns the result synchronously. +Unsubscribes from service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -624,8 +573,8 @@ try { 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.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | @@ -642,8 +591,8 @@ Enumerates the KV store types. | Name | Value| Description | | --- | ---- | ----------------------- | -| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | -| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| DEVICE_COLLABORATION | 0 | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| SINGLE_VERSION | 1 | Single KV store.
The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**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 **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| Name | Type| Description | -| --- | ---- | ----------------------- | -| root8+ | [FieldNode](#fieldnode8) | JSON root object.| -| indexes8+ | Array\ | String array in JSON format. | -| mode8+ | number | Schema mode. | -| skip8+ | number | Size of a skip of the schema. | +| Name | Type| Readable| Writable| Description | +| --- | ---- | ---- | ---- | ----------------------- | +| root8+ | [FieldNode](#fieldnode8) | Yes| Yes| JSON root object.| +| indexes8+ | Array\ | Yes| Yes| String array in JSON format. | +| mode8+ | number | Yes| Yes| Schema mode. | +| skip8+ | number | Yes| Yes| Size of a skip of the schema. | ### constructor8+ @@ -703,11 +652,11 @@ Represents a **Schema** instance, which provides the methods for defining the va **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| Name | Type| Description | -| --- | ---- | ----------------------- | -| nullable8+ | boolean | Whether the database field can be null. | -| default8+ | string | Default value of a **FieldNode**.| -| type8+ | number | Value of the data type corresponding to the specified node.| +| Name | Type| Readable| Writable| Description | +| --- | ---- | ---- | ---- | ----------------------- | +| nullable8+ | boolean | Yes| Yes| Whether the database field can be null. | +| default8+ | string | Yes| Yes| Default value of a **FieldNode**.| +| type8+ | number | Yes| Yes| Value of the data type corresponding to the specified node.| ### constructor8+ @@ -1389,7 +1338,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| value | number\|string | Yes | Value specified.| **Return value** @@ -1424,7 +1373,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| value | number\|string | Yes | Value specified.| **Return value** @@ -1459,7 +1408,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| value | number\|string | Yes | Value specified.| **Return value** @@ -2160,7 +2109,6 @@ try { } ``` - ### put put(key: string, value: Uint8Array | string | number | boolean): Promise<void> @@ -2282,317 +2230,20 @@ try { } ``` -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) - -Deletes KV pairs that meet the specified conditions. 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 |Conditions for deleting data. If this parameter is **null**, define the processing logic.| -| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - 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); -} -``` - -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> - -Deletes KV pairs that meet the specified conditions. 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 |Conditions for deleting data. If this parameter is **null**, define the processing logic.| - - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - 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); -} - -``` - -### backup9+ - -backup(file:string, callback: AsyncCallback<void>):void - -Backs up an RDB store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is the error object.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.backup(file, (err, data) => { - if (err) { - console.info("backup err : " + err); - } else { - console.info("backup data : " + data); - } - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### backup9+ - -backup(file:string): Promise<void> - -Backs up an RDB store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.backup(file).then((data) => { - console.info("backup data : " + data); - }).catch((err) => { - console.info("backup err : " + err); - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### restore9+ - -restore(file:string, callback: AsyncCallback<void>):void - -Restores an RDB store from a database file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.restore(file, (err, data) => { - if (err) { - console.info("restore err : " + err); - } else { - console.info("restore data : " + data); - } - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### restore9+ - -restore(file:string): Promise<void> - -Restores an RDB store from a database file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.restore(file).then((data) => { - console.info("restore data : " + data); - }).catch((err) => { - console.info("restore err : " + err); - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### deleteBackup9+ - -deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void - -Deletes a backup file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | -| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | -| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | - -**Example** - -```js -let kvStore; -let files = ["BK001", "BK002"]; -try { - kvStore.deleteBackup(files, (err, data) => { - if (err) { - console.info("deleteBackup err : " + err); - } else { - console.info("deleteBackup data : " + data); - } - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### deleteBackup9+ - -deleteBackup(files:Array<string>): Promise<Array<[string, number]>> - -Deletes a backup file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | ------------------------------------------------------------ | -| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| - -**Return value** - -| Type | Description | -| -------------------------------------------- | ----------------------------------------------- | -| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| - -**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<ChangeNotification>): void -Subscribes to data changes of the specified type. This API returns the result synchronously. +Subscribes to data changes of the specified type. **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. | +| 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<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| **Example** @@ -2604,21 +2255,20 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun }); ``` - ### on('syncComplete') on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to synchronization complete events. This API returns the result synchronously. +Subscribes to synchronization complete events. **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<Array<[string, number]>> | Yes |Callback invoked to return a synchronization complete event.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | **Example** @@ -2633,17 +2283,19 @@ kvStore.on('syncComplete', function (data) { off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from data changes. This API returns the result synchronously. +Unsubscribes from data changes. **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. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| | listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| + + **Example** ```js @@ -2665,19 +2317,19 @@ class KvstoreModel { } ``` -### off('syncComplete')9+ +### off('syncComplete')8+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization complete events. This API returns the result synchronously. +Unsubscribes from synchronization complete events. **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. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| | syncCallback |Callback<Array<[string, number]>> | No |Callback for the synchronization complete event. | **Example** @@ -2701,7 +2353,6 @@ class KvstoreModel { } ``` - ### putBatch8+ putBatch(entries: Entry[], callback: AsyncCallback<void>): void @@ -2715,7 +2366,7 @@ Inserts KV pairs in batches to this KV store. This API uses an asynchronous call | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | -| callback |Asyncallback<void> |Yes |Callback invoked to return the result.| +| callback |AsyncCallback<void> |Yes |Callback invoked to return the result.| **Example** @@ -2803,13 +2454,11 @@ try { } ``` -### putBatch9+ - -putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void +### deleteBatch8+ -Writes data to this KV store. This API uses an asynchronous callback to return the result. +deleteBatch(keys: string[], callback: AsyncCallback<void>): void -**System API**: This is a system API. +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 @@ -2817,94 +2466,8 @@ Writes data to this KV store. This API uses an asynchronous callback to return | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | -| callback |Asyncallback<void> |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)); -} -``` - -### putBatch9+ - -putBatch(value: Array<ValuesBucket>): Promise<void> - -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<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |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)); -} - -``` - -### deleteBatch8+ - -deleteBatch(keys: string[], callback: AsyncCallback<void>): 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<void> | Yes |Callback invoked to return the result. | +| keys |string[] | Yes |KV pairs to delete in batches. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -3364,12 +2927,12 @@ Defines the content of data change notifications, including inserted data, updat **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. | -| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. | -| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. | -| deviceId | string | Yes | Yes|UUID of the device. | +| Name | Type |Mandatory | Description | +| ----- | ------- | ------|------------------------ | +| insertEntries | [Entry](#entry)[] | Yes|Data inserted. | +| updateEntries | [Entry](#entry)[] | Yes|Data updated. | +| deleteEntries | [Entry](#entry)[] | Yes|Data deleted. | +| deviceId | string | Yes|UUID of the device. | ## Entry @@ -3377,10 +2940,10 @@ Defines the KV pairs stored in the KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| key | string | Yes | 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. | +| Name | Type |Mandatory | Description | +| ----- | ------- | ------|------------------------ | +| key | string | Yes|Key of the KV pair stored in the KV store. | +| value | [Value](#value) | Yes|Value of the KV pair stored in the KV store. | ## Value @@ -3389,10 +2952,10 @@ Defines the **value** object in a KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | +| Name | Type |Mandatory | Description | +| ----- | ------- | ------|------------------------ | +| type | [ValueType](#value) | Yes|Type of the value. | +| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. | ## ValueType @@ -3430,7 +2993,7 @@ Obtains the value of the specified key. This API uses an asynchronous callback t | 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). | -| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. | +| callback |AsyncCallback<Uint8Array \| string \| boolean \| number> | Yes |Callback invoked to return the value obtained. | **Example** @@ -3924,85 +3487,6 @@ try { } ``` -### getResultSet9+ - -getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): 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<[KvStoreResultSet](#kvstoreresultset8)> | 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); -} -``` -### getResultSet9+ - -getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> - -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<[KvStoreResultSet](#kvstoreresultset8)> |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; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` ### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void @@ -4265,118 +3749,105 @@ try { } ``` +### sync -### on('syncComplete')8+ -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void +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). -Subscribes to synchronization complete events. This API returns the result synchronously. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **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<Array<[string, number]>> | Yes |Callback invoked to return a synchronization complete event. | +| 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; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -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); -} +kvStore.sync(['deviceIds'], distributedData.SyncMode.PULL_ONLY, 1000); ``` +### on('dataChange')8+ -### off('syncComplete')8+ - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): 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 **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback for the synchronization complete event. | +| 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<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | **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); - } - } -} +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); ``` -### on('dataChange')9+ +### on('syncComplete')8+ -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void +on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): 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 **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<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | **Example** ```js let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); - +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +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')9+ +### off('dataChange')8+ off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from data changes. This API returns the result synchronously. +Unsubscribes from data changes. **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. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| | listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| **Example** @@ -4399,71 +3870,40 @@ class KvstoreModel { } } ``` -### sync7+ +### off('syncComplete')8+ -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); -``` - -### sync9+ -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<Array<[string, number]>>): void -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Unsubscribes from synchronization complete events. **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. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback for a synchronization complete event. | **Example** ```js let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -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, mode , 1000); - }); -}catch(e) { - console.log('Sync e' + e); +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); + } + } } ``` @@ -5026,7 +4466,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -5066,7 +4506,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** @@ -5104,7 +4544,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -5161,7 +4601,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** @@ -5221,7 +4661,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and * | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -5278,7 +4718,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and * | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** @@ -5734,62 +5174,45 @@ try { } ``` -### sync9+ +### on('dataChange')8+ -sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): 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). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Subscribes to data changes of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| -| query |[Query](#query8) | Yes | **Query** object to match.| -| delayMs |number | No |Allowed synchronization delay time, in ms. | +| 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<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | **Example** ```js let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -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); -} +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); ``` ### on('syncComplete')8+ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to synchronization complete events. This API returns the result synchronously. +Subscribes to synchronization complete events. **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 | Yes |Callback invoked to return a synchronization complete event. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | **Example** @@ -5811,21 +5234,20 @@ try { } ``` +### off('dataChange')8+ -### off('syncComplete')8+ - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void +off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from synchronization complete events. This API returns the result synchronously. +Unsubscribes from data changes. **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 |Callback9+
- -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): 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<[ChangeNotification](#changenotification)> | 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')9+ +### off('syncComplete')8+ -off(event:'dataChange', listener?: Callback<ChangeNotification>): void +off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from data changes. This API returns the result synchronously. +Unsubscribes from synchronization complete events. **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<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback for a synchronization complete event. | **Example** @@ -5895,16 +5291,16 @@ Unsubscribes from data changes. This API returns the result synchronously. let kvStore; class KvstoreModel { call(data) { - console.log("dataChange: " + data); + console.log("syncComplete: " + data); } - subscribeDataChange() { + subscribeSyncComplete() { if (kvStore != null) { - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + kvStore.on('syncComplete', this.call); } } - unsubscribeDataChange() { + unsubscribeSyncComplete() { if (kvStore != null) { - kvStore.off('dataChange', this.call); + kvStore.off('syncComplete', this.call); } } } diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md new file mode 100644 index 0000000000000000000000000000000000000000..81308054abd5ef5f55ad9d4c78b52f427c16792c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -0,0 +1,6657 @@ +# Distributed KV Store + +The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. + +The **distributedKVStore** module provides the following functions: + +- [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information. +- [KVStoreResultSet](#kvstoreresultset): provides APIs for obtaining KV store result sets. +- [Query](#query): provides APIs for setting predicates and querying data using predicates. +- [SingleKVStore](#singlekvstore): provides APIs for querying data in single KV stores and synchronizing data. The single KV stores manage data without distinguishing devices. +- [DeviceKVStore](#devicekvstore): provides APIs for querying in device KV stores and synchronizing data. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. + +> **NOTE**
+> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import distributedKVStore from '@ohos.data.distributedKVStore'; +``` + +## KVManagerConfig + +Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory| Description | +| ---------- | --------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes |Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| bundleName | string | Yes | Bundle name. | + +## Constants + +Provides constants of the distributed KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the distributed KV store, in bytes. | +| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the distributed KV store, in bytes.| +| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes. | +| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | +| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes. | +| MAX_BATCH_SIZE | 128 | Maximum number of batch operations. | + +## ValueType + +Enumerates the data types. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| ---------- | ---------------------- | +| STRING | String. | +| INTEGER | Integer. | +| FLOAT | Float (single-precision floating point). | +| BYTE_ARRAY | Byte array.| +| BOOLEAN | Boolean. | +| DOUBLE | Double (double-precision floating point).| + +## Value + +Defines the **value** object in a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type |Mandatory | Description | +| ----- | ------- |-----|------------------------ | +| type | [ValueType](#valuetype) | Yes|Type of the value. | +| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. | + +## Entry + +Defines the KV pairs stored in the KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory| Description | +| ----- | --------------- | ---- | -------- | +| key | string | Yes | Key of the KV pair stored in the KV store. | +| value | [Value](#value) | Yes | Value of the KV pair stored in the KV store.| + +## ChangeNotification + +Defines the content of a data change notification, including inserted data, updated data, deleted data, and device ID. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory | Description | +| ------------- | ----------------- | ---- | ------------------------ | +| insertEntries | [Entry](#entry)[] | Yes | Data inserted. | +| updateEntries | [Entry](#entry)[] | Yes | Data updated. | +| deleteEntries | [Entry](#entry)[] | Yes | Data deleted. | +| deviceId | string | Yes | UUID of the device.| + +## SyncMode + +Enumerates the synchronization modes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| --------- | ---------------------------------------------------- | +| PULL_ONLY | Pull data from the peer end to the local end only. | +| PUSH_ONLY | Push data from the local end to the peer end only. | +| PUSH_PULL | Push data from the local end to the peer end and then pull data from the peer end to the local end.| + +## SubscribeType + +Enumerates the subscription types. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| --------------------- | ---------------------------- | +| SUBSCRIBE_TYPE_LOCAL | Local data changes. | +| SUBSCRIBE_TYPE_REMOTE | Remote data changes. | +| SUBSCRIBE_TYPE_ALL | Local and remote data changes.| + +## KVStoreType + +Enumerates the distributed KV store types. + +| Name | Description | +| -------------------- | ------------------------------------------------------------ | +| DEVICE_COLLABORATION | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| +| SINGLE_VERSION | Single KV store.
The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| + +## SecurityLevel + +Enumerates the KV store security levels. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| -------: | ------------------------------------------------------------ | +| S1 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| +| S2 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| +| S3 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| +| S4 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| + +## Options + +Provides KV store configuration. + +| 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.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| encrypt | boolean | No | Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| backup | boolean | No | Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| autoSync | boolean | No | Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC| +| kvStoreType | [KVStoreType](#kvstoretype) | No | Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| securityLevel | [SecurityLevel](#securitylevel) | Yes |Security level of the KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| schema | [Schema](#schema) | No | Schema used to define the values stored in the KV store. By default, **schema** is not used.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| + +## Schema + +Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +| Name | Type | Readable| Writable| Description | +| ------- | ----------------------- | ---- | ---- | -------------------------- | +| root | [FieldNode](#fieldnode) | Yes | Yes | JSON root object. | +| indexes | Array\ | Yes | Yes | String array in JSON format.| +| mode | number | Yes | Yes | Schema mode. | +| skip | number | Yes | Yes | Size of a skip of the schema. | + +### constructor + +constructor() + +A constructor used to create a **Schema** instance. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +## FieldNode + +Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +| Name | Type | Readable| Writable| Description | +| -------- | ------- | ---- | ---- | ------------------------------ | +| nullable | boolean | Yes | Yes | Whether the database field can be null. | +| default | string | Yes | Yes | Default value of a **FieldNode**. | +| type | number | Yes | Yes | Value of the data type corresponding to the specified node.| + +### constructor + +constructor(name: string) + +A constructor used to create a **FieldNode** instance with a string field. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | --------------- | +| name | string | Yes | Value of **FieldNode**.| + +### appendChild + +appendChild(child: FieldNode): boolean + +Appends a child node to this **FieldNode**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------- | +| child | [FieldNode](#fieldnode) | Yes | Child node to append.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import ddm from '@ohos.data.distributedKVStore'; + +try { + let node = new ddm.FieldNode("root"); + let child1 = new ddm.FieldNode("child1"); + let child2 = new ddm.FieldNode("child2"); + let child3 = new ddm.FieldNode("child3"); + node.appendChild(child1); + node.appendChild(child2); + node.appendChild(child3); + console.log("appendNode " + JSON.stringify(node)); + child1 = null; + child2 = null; + child3 = null; + node = null; +} catch (e) { + console.log("AppendChild " + e); +} +``` + +## distributedKVStore.createKVManager + +createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void + +Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ----------------------------------------------------------- | +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name of the invoker and the context of the application.| +| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created. | + +**Example** + +Stage model: + +```js +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + } + try { + distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); + } catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); + } + } +} +``` + +FA model: + +```js +import featureAbility from '@ohos.ability.featureAbility' +let kvManager; +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', +} +try { + distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); +} catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); +} +``` + +## distributedKVStore.createKVManager + +createKVManager(config: KVManagerConfig): Promise<KVManager> + +Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | --------------------------------------------------------- | +| config | [KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| + +**Return value** + +| Type | Description | +| -------------------------------------- | ------------------------------------------ | +| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| + +**Example** + +Stage model: + +```js +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + } + try { + distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; + }).catch((err) => { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + }); + } catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); + } + } +} +``` + +FA model: + +```js +import featureAbility from '@ohos.ability.featureAbility' +let kvManager; +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', +} +try { + distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; + }).catch((err) => { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); +} +``` + +## KVManager + +Provides an instance to obtain information about a distributed KV store. Before calling any API in **KVManager**, you must use [createKVManager](#distributedkvstorecreatekvmanager) to create a **KVManager** instance. + +### getKVStore + +getKVStore<T >(storeId: string, options: Options, callback: AsyncCallback<T>): void + +Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| 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 to create. | +| callback | AsyncCallback<T> | Yes | Callback invoked to return the distributed single or device KV store created. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| ID| **Error Message** | +| ------------ | ------------------------------------------- | +| 15100002 | Open existed database with changed options. | +| 15100003 | Database corrupted. | + +**Example** + +```js +let kvStore; +let kvManager; +try { + const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + securityLevel: distributedKVStore.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options, function (err, store) { + if (err) { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Obtained the KVStore successfully."); + kvStore = store; + }); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### getKVStore + +getKVStore<T >(storeId: string, options: Options): Promise<T> + +Creates and obtains a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| 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 distributed KV store to create. | + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise<T> | Promise used to return the distributed single or device KV store created.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| ID| **Error Message** | +| ------------ | ------------------------------------------- | +| 15100002 | Open existed database with changed options. | +| 15100003 | Database corrupted. | + +**Example** + +```js +let kvStore; +let kvManager; +try { + const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + securityLevel: distributedKVStore.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options).then((store) => { + console.log("Obtained the KVStore successfully."); + kvStore = store; + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### closeKVStore + +closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void + +Closes a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +let kvManager; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options, async function (err, store) { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId', function (err, data) { + if (err != undefined) { + console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the KVStore successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### closeKVStore + +closeKVStore(appId: string, storeId: string): Promise<void> + +Closes a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId').then(() => { + console.log('Closed the KVStore successfully.'); + }).catch((err) => { + console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to close KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteKVStore + +deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void + +Deletes a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message**| +| ------------ | ------------ | +| 15100004 | Not found. | + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('store', options, async function (err, store) { + if (err != undefined) { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + if (err != undefined) { + console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Deleted the KVStore successfully.`); + }); + }); +} catch (e) { + console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteKVStore + +deleteKVStore(appId: string, storeId: string): Promise<void> + +Deletes a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message**| +| ------------ | ------------ | +| 15100004 | Not found. | + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.deleteKVStore('appId', 'storeId').then(() => { + console.log('Deleted the KVStore successfully.'); + }).catch((err) => { + console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### getAllKVStoreId + +getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void + +Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | --------------------------------------------------- | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| callback | AsyncCallback<string[]> | Yes | Callback invoked to return the IDs of the distributed KV stores obtained.| + +**Example** + +```js +let kvManager; +try { + kvManager.getAllKVStoreId('appId', function (err, data) { + if (err != undefined) { + console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained all KV store IDs successfully.'); + console.log(`GetAllKVStoreId size = ${data.length}`); + }); +} catch (e) { + console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); +} +``` + +### getAllKVStoreId + +getAllKVStoreId(appId: string): Promise<string[]> + +Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| appId | string | Yes | Bundle name of the app that invokes the KV store.| + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------------------------------------ | +| Promise<string[]> | Promise used to return the IDs of the distributed KV stores obtained.| + +**Example** + +```js +let kvManager; +try { + console.log('GetAllKVStoreId'); + kvManager.getAllKVStoreId('appId').then((data) => { + console.log('Obtained all KV store IDs successfully.'); + console.log(`GetAllKVStoreId size = ${data.length}`); + }).catch((err) => { + console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); +} +``` + +### on('distributedDataServiceDie') + +on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void + +Subscribes to service status changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ------------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvManager; +try { + console.log('KVManagerOn'); + const deathCallback = function () { + console.log('death callback call'); + } + kvManager.on('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### off('distributedDataServiceDie') + +off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void + +Unsubscribes from service status changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ------------------------------------------------------------ | +| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | No | Callback for the service status change event. | + +**Example** + +```js +let kvManager; +try { + console.log('KVManagerOff'); + const deathCallback = function () { + console.log('death callback call'); + } + kvManager.off('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +## KVStoreResultSet + +Provides APIs for obtaining the distributed KV store result sets. + +Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance. + +### getCount + +getCount(): number + +Obtains the total number of rows in the result set. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Total number of rows obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const count = resultSet.getCount(); + console.log("getCount succeed:" + count); +} catch (e) { + console.log("getCount failed: " + e); +} +``` + +### getPosition + +getPosition(): number + +Obtains the current data read position (position from which data is read) in the result set. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Current data read position obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const position = resultSet.getPosition(); + console.log("getPosition succeed:" + position); +} catch (e) { + console.log("getPosition failed: " + e); +} +``` + +### moveToFirst + +moveToFirst(): boolean + +Moves the data read position to the first row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved1 = resultSet.moveToFirst(); + console.log("moveToFirst succeed: " + moved1); +} catch (e) { + console.log("moveToFirst failed " + e); +} +``` + +### moveToLast + +moveToLast(): boolean + +Moves the data read position to the last row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved2 = resultSet.moveToLast(); + console.log("moveToLast succeed:" + moved2); +} catch (e) { + console.log("moveToLast failed: " + e); +} +``` + +### moveToNext + +moveToNext(): boolean + +Moves the data read position to the next row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved3 = resultSet.moveToNext(); + console.log("moveToNext succeed: " + moved3); +} catch (e) { + console.log("moveToNext failed: " + e); +} +``` + +### moveToPrevious + +moveToPrevious(): boolean + +Moves the data read position to the previous row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved4 = resultSet.moveToPrevious(); + console.log("moveToPrevious succeed:" + moved4); +} catch (e) { + console.log("moveToPrevious failed: " + e); +} +``` + +### move + +move(offset: number): boolean + +Moves the data read position with the specified offset from the current position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + const moved5 = resultSet.move(1); + console.log(`Succeeded in moving.moved5 = ${moved5}`); +} catch (e) { + console.log(`Fail to move.code is ${e.code},message is ${e.message}`); +} +``` + +### moveToPosition + +moveToPosition(position: number): boolean + +Moves the data read position from 0 to an absolute position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | -------------- | +| position | number | Yes | Absolute position to move to.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + const moved6 = resultSet.moveToPosition(1); + console.log(`Succeeded in moving to position.moved6=${moved6}`); +} catch (e) { + console.error(`Fail to move to position.code is ${e.code},message is ${e.message}`); +} +``` + +### isFirst + +isFirst(): boolean + +Checks whether the data read position is the first row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the first row is being read; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isfirst = resultSet.isFirst(); + console.log("Check isFirst succeed:" + isfirst); +} catch (e) { + console.log("Check isFirst failed: " + e); +} +``` + +### isLast + +isLast(): boolean + +Checks whether the data read position is the last row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the last row is being read; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const islast = resultSet.isLast(); + console.log("Check isLast succeed: " + islast); +} catch (e) { + console.log("Check isLast failed: " + e); +} +``` + +### isBeforeFirst + +isBeforeFirst(): boolean + +Checks whether the data read position is before the first row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the data read position is before the first row; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isbeforefirst = resultSet.isBeforeFirst(); + console.log("Check isBeforeFirst succeed: " + isbeforefirst); +} catch (e) { + console.log("Check isBeforeFirst failed: " + e); +} +``` + +### isAfterLast + +isAfterLast(): boolean + +Checks whether the data read position is after the last row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the data read position is after the last row; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isafterlast = resultSet.isAfterLast(); + console.log("Check isAfterLast succeed:" + isafterlast); +} catch (e) { + console.log("Check isAfterLast failed: " + e); +} +``` + +### getEntry + +getEntry(): Entry + +Obtains the KV pair from the current position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| --------------- | ------------ | +| [Entry](#entry) | KV pair obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const entry = resultSet.getEntry(); + console.log("getEntry succeed:" + JSON.stringify(entry)); +} catch (e) { + console.log("getEntry failed: " + e); +} +``` + +## Query + +Provides methods to create a **Query** object, which defines different data query criteria. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +### constructor + +constructor() + +A constructor used to create a **Schema** instance. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +### reset + +reset(): Query + +Resets the **Query** object. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------------- | +| [Query](query) | **Query** object reset.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.equalTo("key", "value"); + console.log("query is " + query.getSqlLike()); + query.reset(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("simply calls should be ok :" + e); +} +``` + +### equalTo + +equalTo(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is equal to the given value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.equalTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`); +} +``` + +### notEqualTo + +notEqualTo(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### greaterThan + +greaterThan(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.greaterThan("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### lessThan + +lessThan(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.lessThan("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.greaterThanOrEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.lessThanOrEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### isNull + +isNull(field: string): Query + +Creates a **Query** object to match the specified field whose value is **null**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.isNull("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### inNumber + +inNumber(field: string, valueList: number[]): Query + +Creates a **Query** object to match the specified field whose value is within the specified list of numbers. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | number[] | Yes | List of numbers. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.inNumber("field", [0, 1]); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### inString + +inString(field: string, valueList: string[]): Query + +Creates a **Query** object to match the specified field whose value is within the specified list of strings. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | string[] | Yes | List of strings. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.inString("field", ['test1', 'test2']); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### notInNumber + +notInNumber(field: string, valueList: number[]): Query + +Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | number[] | Yes | List of numbers. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notInNumber("field", [0, 1]); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### notInString + +notInString(field: string, valueList: string[]): Query + +Creates a **Query** object to match the specified field whose value is not within the specified list of strings. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | string[] | Yes | List of strings. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notInString("field", ['test1', 'test2']); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### like + +like(field: string, value: string): Query + +Creates a **Query** object to match the specified field whose value is similar to the specified string. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| value | string | Yes | String specified. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.like("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### unlike + +unlike(field: string, value: string): Query + +Creates a **Query** object to match the specified field whose value is not similar to the specified string. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| value | string | Yes | String specified. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.unlike("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### and + +and(): Query + +Creates a **Query** object with the AND condition. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | -------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value1"); + query.and(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### or + +or(): Query + +Creates a **Query** object with the OR condition. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | -------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value1"); + query.or(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### orderByAsc + +orderByAsc(field: string): Query + +Creates a **Query** object to sort the query results in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.orderByAsc("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### orderByDesc + +orderByDesc(field: string): Query + +Creates a **Query** object to sort the query results in descending order. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.orderByDesc("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### limit + +limit(total: number, offset: number): Query + +Creates a **Query** object to specify the number of results and where to start. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| total | number | Yes | Number of results to query.| +| offset | number | Yes | Start position for query. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +let total = 10; +let offset = 1; +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.limit(total, offset); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### isNotNull + +isNotNull(field: string): Query + +Creates a **Query** object to match the specified field whose value is not **null**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.isNotNull("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### beginGroup + +beginGroup(): Query + +Creates a **Query** object for a query condition group with a left parenthesis. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### endGroup + +endGroup(): Query + +Creates a **Query** object for a query condition group with a right parenthesis. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### prefixKey + +prefixKey(prefix: string): Query + +Creates a **Query** object with a specified key prefix. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| prefix | string | Yes | Key prefix.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.prefixKey("$.name"); + query.prefixKey("0"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### setSuggestIndex + +setSuggestIndex(index: string): Query + +Creates a **Query** object with an index preferentially used for query. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| index | string | Yes | Index preferentially used for query.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.setSuggestIndex("$.name"); + query.setSuggestIndex("0"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### deviceId + +deviceId(deviceId:string):Query + +Creates a **Query** object with the device ID as the key prefix. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ------------------ | +| deviceId | string | Yes | Device ID.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.deviceId("deviceId"); + console.log(`query is ${query.getSqlLike()}`); +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### getSqlLike + +getSqlLike():string + +Obtains the query statement of the **Query** object. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Returns the query statement obtained.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + let sql1 = query.getSqlLike(); + console.log(`GetSqlLike sql= ${sql1}`); +} catch (e) { + console.log("duplicated calls should be ok : " + e); +} +``` + +## SingleKVStore + +Implements data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or data synchronization completion. + +Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. + +### put + +put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void + +Adds a KV pair of the specified type 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 | +| ----- | ------ | ---- | ----------------------- | +| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### put + +put(key: string, value: Uint8Array | string | number | boolean): Promise<void> + +Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### putBatch + +putBatch(entries: Entry[], callback: AsyncCallback<void>): void + +Batch inserts KV pairs to this single 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 | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### putBatch + +putBatch(entries: Entry[]): Promise<void> + +Batch inserts KV pairs to this single 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<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### putBatch + +putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void + +Writes data to this single 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<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + }) +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### putBatch + +putBatch(value: Array<ValuesBucket>): Promise<void> + +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<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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 (data) => { + console.log(`Batch put data successfully.`); + }).catch((err) => { + console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`putBatch fail.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(key: string, callback: AsyncCallback<void>): void + +Deletes a KV pair 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 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Deleted data successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(key: string): Promise<void> + +Deletes a KV pair from this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully: ${data}`); + kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) + +Deletes KV pairs from this KV store. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + kvStore.delete(predicates, function (err, data) { + if (err == undefined) { + console.log('Deleted data successfully.'); + } else { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> + +Deletes KV pairs from this KV store. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let arr = ["name"]; + predicates.inKeys(arr); + kvStore.put("name", "bob").then((data) => { + console.log(`Put data successfully: ${data}`); + kvStore.delete(predicates).then((data) => { + console.log('Deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBatch + +deleteBatch(keys: string[], callback: AsyncCallback<void>): void + +Batch deletes KV pairs from this single 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<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + keys.push(key + i); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.deleteBatch(keys, async function (err, data) { + if (err != undefined) { + console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch deleted data successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBatch + +deleteBatch(keys: string[]): Promise<void> + +Batch deletes KV pairs from this single 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<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + keys.push(key + i); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (data) => { + console.log('Batch put data successfully.'); + kvStore.deleteBatch(keys).then((err) => { + console.log('Batch deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### removeDeviceData + +removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void + +Deletes data of a device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| deviceId | string | Yes | ID of the target device.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + console.log('Put data successfully.'); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid, async function (err, data) { + if (err == undefined) { + console.log('Removed device data successfully.'); + } else { + console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) { + console.log('Obtained data successfully.'); + }); + } + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`) +} +``` + +### removeDeviceData + +removeDeviceData(deviceId: string): Promise<void> + +Deletes data of a device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ---------------------- | +| deviceId | string | Yes | ID of the target device.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + console.log('Put data successfully.'); + }).catch((err) => { + console.error(`Fail to put data.code is ${err.code},message is ${err.message} `); + }); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid).then((err) => { + console.log('Removed device data successfully.'); + }).catch((err) => { + console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + }); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Obtained data successfully.'); + }).catch((err) => { + console.error(`Fail to get data.code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`) +} +``` + +### get + +get(key: string, callback: AsyncCallback): void + +Obtains the value of the specified key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| 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). | +| callback |AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes |Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Obtained data successfully. data=${data}`); + }); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(key: string): Promise<boolean | string| number | Uint8Array> + +Obtains the value of the specified key. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| 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).| + +**Return value** + +| Type | Description | +| ------ | ------- | +|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log(`Obtained data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------- | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ----------------------------------------------- | +| query | [Query](query) | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query): Promise<Entry[]> + +Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | -------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a result set with the specified prefix from this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getResultSet('batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a result set with the specified prefix from this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------------- | +| query | Query | Yes | **Query** object to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### closeResultSet + +closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>): void + +Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------- | ---- | ---------------------------------- | +| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err == undefined) { + console.log('Closed the result set successfully'); + } else { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### closeResultSet + +closeResultSet(resultSet: KVStoreResultSet): Promise<void> + +Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------- | ---- | ---------------------------------- | +| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet).then(() => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query, callback: AsyncCallback<number>): void + +Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------- | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set size successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query): Promise<number> + +Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------- | +| Promise<number> | Promise used to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('Obtained the result set size successfully'); + }).catch((err) => { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### backup + +backup(file:string, callback: AsyncCallback<void>):void + +Backs up a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file, (err, data) => { + if (err) { + console.error(`Fail to backup.code is ${err.code},message is ${err.message} `); + } else { + console.info(`Backed up data successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### backup + +backup(file:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file).then((data) => { + console.info(`Backed up data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to backup.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### restore + +restore(file:string, callback: AsyncCallback<void>):void + +Restores a distributed KV store from a database file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file, (err, data) => { + if (err) { + console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + } else { + console.info(`Restored data successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### restore + +restore(file:string): Promise<void> + +Restores a distributed KV store from a database file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file).then((data) => { + console.info(`Restored data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBackup + +deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void + +Deletes a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files, (err, data) => { + if (err) { + console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + } else { + console.info(`Deleted the backup file successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBackup + +deleteBackup(files:Array<string>): Promise<Array<[string, number]>> + +Deletes a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------------------------------------- | ----------------------------------------------- | +| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files).then((data) => { + console.info(`Deleted the backup file successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + }) +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### startTransaction + +startTransaction(callback: AsyncCallback<void>): void + +Starts the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +function putBatchString(len, prefix) { + let entries = []; + for (var i = 0; i < len; i++) { + var entry = { + key: prefix + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + return entries; +} + +try { + var count = 0; + kvStore.on('dataChange', 0, function (data) { + console.log(`startTransaction 0 ${data}`); + count++; + }); + kvStore.startTransaction(async function (err, data) { + if (err != undefined) { + console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Started the transaction successfully.'); + let entries = putBatchString(10, 'batch_test_string_key'); + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + }); + }); +} catch (e) { + console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); +} +``` + +### startTransaction + +startTransaction(): Promise<void> + +Starts the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var count = 0; + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { + console.log(`startTransaction 0 ${data}`); + count++; + }); + kvStore.startTransaction().then(async (err) => { + console.log('Started the transaction successfully.'); + }).catch((err) => { + console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); +} +``` + +### commit + +commit(callback: AsyncCallback<void>): void + +Commits the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.commit(function (err, data) { + if (err == undefined) { + console.log('Committed the transaction successfully.'); + } else { + console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### commit + +commit(): Promise<void> + +Commits the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.commit().then(async (err) => { + console.log('Committed the transaction successfully.'); + }).catch((err) => { + console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.ode is ${e.code},message is ${e.message}`); +} +``` + +### rollback + +rollback(callback: AsyncCallback<void>): void + +Rolls back the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.rollback(function (err,data) { + if (err == undefined) { + console.log('Rolled back the transaction successfully'); + } else { + console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + } + }); +}catch(e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### rollback + +rollback(): Promise<void> + +Rolls back the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.rollback().then(async (err) => { + console.log('Rolled back the transaction successfully'); + }).catch((err) => { + console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### enableSync + +enableSync(enabled: boolean, callback: AsyncCallback<void>): void + +Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------------------- | +| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + kvStore.enableSync(true, function (err, data) { + if (err == undefined) { + console.log('Enabled sync successfully.'); + } else { + console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### enableSync + +enableSync(enabled: boolean): Promise<void> + +Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | --------------------------------------------------------- | +| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + kvStore.enableSync(true).then((err) => { + console.log('Enabled sync successfully.'); + }).catch((err) => { + console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncRange + +setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void + +Sets the data synchronization range. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------- | ---- | -------------------------------- | +| localLabels | string[] | Yes | Synchronization labels set for the local device. | +| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) { + if (err != undefined) { + console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Set syncRange successfully.'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncRange + +setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> + +Sets the data synchronization range. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------------------- | -------- | ---- | -------------------------------- | +| localLabels | string[] | Yes | Synchronization labels set for the local device. | +| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { + console.log('Set syncRange successfully.'); + }).catch((err) => { + console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncParam + +setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void + +Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------- | ------------------------- | ---- | -------------------------------------------- | +| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) { + if (err != undefined) { + console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Set syncParam successfully'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncParam + +setSyncParam(defaultAllowedDelayMs: number): Promise<void> + +Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------------------- | -------- | ---- | -------------------------------------------- | +| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { + console.log('Set syncParam successfully'); + }).catch((err) => { + console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### sync + +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. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | + +**Example** + +```js +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + const devices = ['deviceList']; + const mode = distributedKVStore.SyncMode.PULL_ONLY; + kvStore.sync(devices, mode, 1000); + }); +} catch (e) { + console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); +} +``` + +### sync + +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). + +**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. | +| query | [Query](query) | Yes | **Query** object to match. | +| delayMs | number | No | Allowed synchronization delay time, in ms. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | + +**Example** + +```js +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + const devices = ['deviceList']; + const mode = distributedKVStore.SyncMode.PULL_ONLY; + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + kvStore.sync(devices, query, mode, 1000); + }); +} catch (e) { + console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); +} +``` + +### on('dataChange') + +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void + +Subscribes to data changes of the specified type. + +**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<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100001 | Over max subscribe limits. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, 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}`); +} +``` + +### on('syncComplete') + +on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void + +Subscribes to synchronization complete events. + +**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<Array<[string, number]>> | Yes | Callback used to return the synchronization result. | + +**Example** + +```js +let kvStore; +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +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('Put data successfully.'); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to subscribe syncComplete.code is ${e.code},message is ${e.message}`); +} +``` + +### off('dataChange') + +off(event:'dataChange', listener?: Callback<ChangeNotification>): void + +Unsubscribes from data changes. + +**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<[ChangeNotification](#changenotification)> | No | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +class KvstoreModel { + call(data) { + console.log(`dataChange : ${data}`); + } + + subscribeDataChange() { + try { + if (kvStore != null) { + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } catch (err) { + console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } + + unsubscribeDataChange() { + try { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } catch (err) { + console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } +} +``` + +### off('syncComplete') + +off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void + +Unsubscribes from synchronization complete events. + +**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<Array<[string, number]>> | No | Callback used to return the synchronization result. | + +**Example** + +```js +let kvStore; +class KvstoreModel { + call(data) { + console.log(`syncComplete : ${data}`); + } + + subscribeDataChange() { + try { + if (kvStore != null) { + kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } catch (err) { + console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } + + unsubscribeDataChange() { + try { + if (kvStore != null) { + kvStore.off('dsyncComplete', this.call); + } + } catch (err) { + console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } +} +``` + +### getSecurityLevel + +getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void + +Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<[SecurityLevel](#securitylevel)> | Yes | Callback invoked to return the security level obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.getSecurityLevel(function (err, data) { + if (err != undefined) { + console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained securityLevel successfully'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getSecurityLevel + +getSecurityLevel(): Promise<SecurityLevel> + +Obtains the security level of this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------- | ----------------------------------- | +| Promise<[SecurityLevel](#securitylevel)> | Promise used to return the security level obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.getSecurityLevel().then((data) => { + console.log('Obtained securityLevel successfully'); + }).catch((err) => { + console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +## DeviceKVStore + +Provides APIs for querying and synchronizing data in a device KV store. This class inherits from **SingleKVStore**. + +Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. + +For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. + +Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. + +### get + +get(key: string, callback: AsyncCallback): void + +Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| 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).| +| callback | AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes | Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Obtained data successfully. data=${data}`); + }); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(key: string): Promise<boolean | string| number | Uint8Array> + +Obtains the value of the specified key for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| 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).| + +**Return value** + +| Type | Description | +| -------------------------------------------------------- | ------------------------------- | +| Promise<Uint8Array \| string \| boolean \| number> | Promise used to return the value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log(`Obtained data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void + +Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| deviceId |string | Yes |ID of the target device. | +| key |string | Yes |Key to match. | +| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained data successfully'); + }); + }) +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> + +Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| key | string | Yes | Key to match. | + +**Return value** + +| Type | Description | +| ------ | ------- | +|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { + console.log('Put data successfully.'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Obtained data successfully'); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((error) => { + console.error(`Fail to put.code is ${error.code},message is ${error.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified key prefix for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------- | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified key prefix for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries : ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| keyPrefix | string | Yes | Key prefix to match. | + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + console.log(`entries[0].value: ${entries[0].value}`); + console.log(`entries[0].value.value: ${entries[0].value.value}`); + }).catch((err) => { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ----------------------------------------------------- | +| query | [Query](query) | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query): Promise<Entry[]> + +Obtains all KV pairs that match the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | -------------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + var query = new distributedKVStore.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + kvStore.getEntries('localDeviceId', query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, query: Query): Promise<Entry[]> + +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | -------------------- | +| deviceId | string | Yes | ID of the target device.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| -------------------------------- | ---------------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + var query = new distributedKVStore.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + kvStore.getEntries('localDeviceId', query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a result set with the specified prefix for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getResultSet('batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a result set with the specified prefix for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the target device. | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully.'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully.'); + }) + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| keyPrefix | string | Yes | Key prefix to match. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully.'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully.'); + }) + }); + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); + +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); + +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the target device. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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('localDeviceId', predicates, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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('localDeviceId', predicates).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query, callback: AsyncCallback<number>): void + +Obtains the number of results that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------- | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results that match the specified **Query** object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set size successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query): Promise<number> + +Obtains the number of results that match the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------------------------- | +| Promise<number> | Promise used to return the number of results that match the specified **Query** object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('Obtained the result set size successfully'); + }).catch((err) => { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; + +Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained resultSize successfully'); + ; + }); + }); +} catch (e) { + console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSize + +getResultSize(deviceId: string, query: Query): Promise<number> + +Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------------ | +| Promise<number> | Promise used to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**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: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + var query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query).then((resultSize) => { + console.log('Obtained resultSize successfully'); + ; + }).catch((err) => { + console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); +} +``` diff --git a/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md b/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md new file mode 100644 index 0000000000000000000000000000000000000000..da3088db9008d5077568765065e62efa5e1bbd11 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @@ -0,0 +1,101 @@ +# 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.