1# Persisting KV Store Data
2
3
4## When to Use
5
6The key-value (KV) database stores data in the form of KV pairs. You can use KV stores to store data organized in a simple model, for example, product names and prices or employee IDs and daily attendance. The simple data structure allows higher compatibility with different database versions and device types.
7
8
9## Constraints
10
11- For each record in a device KV store, the key cannot exceed 896 bytes and the value cannot exceed 4 MB.
12
13- For each record in a single KV store, the key cannot exceed 1 KB and the value cannot exceed 4 MB.
14
15- A maximum of 16 distributed KV stores can be opened simultaneously for an application.
16
17- Blocking operations, for example, modifying UI components, are not allowed in the KV store event callbacks.
18
19
20## Available APIs
21
22The following table lists the APIs used for KV data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed KV Store](../reference/apis-arkdata/js-apis-distributedKVStore.md).
23
24| API| Description|
25| -------- | -------- |
26| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** instance to manage database objects.|
27| getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void | Obtains a KV store of the specified type.|
28| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void | Adds a KV pair of the specified type to this KV store.|
29| get(key: string, callback: AsyncCallback\<boolean \| string \| number \| Uint8Array>): void | Obtains the value of the specified key.|
30| delete(key: string, callback: AsyncCallback&lt;void&gt;): void | Deletes a KV pair based on the specified key.|
31| closeKVStore(appId: string, storeId: string, callback: AsyncCallback&lt;void&gt;): void | Closes the distributed KV store of the given **storeId**.|
32| deleteKVStore(appId: string, storeId: string, callback: AsyncCallback&lt;void&gt;): void | Deletes the distributed KV store of the given **storeId**.|
33
34
35## How to Develop
36
371. Create a **KvManager** instance to manage database objects. <br>Example:
38
39   Stage model:
40
41
42   ```js
43   // Import the module.
44   import { distributedKVStore } from '@kit.ArkData';
45
46   // Stage model
47   import { window } from '@kit.ArkUI';
48   import { UIAbility } from '@kit.AbilityKit';
49   import { BusinessError } from '@kit.BasicServicesKit';
50
51   let kvManager: distributedKVStore.KVManager | undefined = undefined;
52
53   export default class EntryAbility extends UIAbility {
54     onCreate() {
55       let context = this.context;
56       const kvManagerConfig: distributedKVStore.KVManagerConfig = {
57         context: context,
58         bundleName: 'com.example.datamanagertest'
59       };
60       try {
61         // Create a KVManager instance.
62         kvManager = distributedKVStore.createKVManager(kvManagerConfig);
63         console.info('Succeeded in creating KVManager.');
64         // Create and obtain the database.
65       } catch (e) {
66         let error = e as BusinessError;
67         console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
68       }
69     }
70   }
71   if (kvManager !== undefined) {
72      kvManager = kvManager as distributedKVStore.KVManager;
73     // Perform subsequent operations.
74     //...
75   }
76   ```
77
78   FA model:
79
80
81   ```js
82   // Import the module.
83   import { distributedKVStore } from '@kit.ArkData';
84
85   // FA model
86   import { featureAbility } from '@kit.AbilityKit';
87   import { BusinessError } from '@kit.BasicServicesKit';
88
89   let kvManager: distributedKVStore.KVManager | undefined = undefined;
90   let context = featureAbility.getContext(); // Obtain the context.
91   const kvManagerConfig: distributedKVStore.KVManagerConfig = {
92     context: context,
93     bundleName: 'com.example.datamanagertest'
94   };
95   try {
96     kvManager = distributedKVStore.createKVManager(kvManagerConfig);
97     console.info('Succeeded in creating KVManager.');
98     // Create and obtain the database.
99   } catch (e) {
100      let error = e as BusinessError;
101      console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
102   }
103   if (kvManager !== undefined) {
104     kvManager = kvManager as distributedKVStore.KVManager;
105     // Perform subsequent operations.
106     //...
107   }
108
109   ```
110
1112. Create and obtain a KV store. <br>Example:
112
113   ```js
114   let kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
115   try {
116     const options: distributedKVStore.Options = {
117       createIfMissing: true,
118       encrypt: false,
119       backup: false,
120       autoSync: false,
121       // If kvStoreType is left empty, a device KV store is created by default.
122       kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
123       // Device KV store: kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION,
124       securityLevel: distributedKVStore.SecurityLevel.S3
125     };
126     kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => {
127       if (err) {
128         console.error(`Failed to get KVStore: Code:${err.code},message:${err.message}`);
129         return;
130       }
131       console.info('Succeeded in getting KVStore.');
132       kvStore = store;
133       // Before performing related data operations, obtain a KV store instance.
134     });
135   } catch (e) {
136     let error = e as BusinessError;
137     console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
138   }
139   if (kvStore !== undefined) {
140     kvStore = kvStore as distributedKVStore.SingleKVStore;
141       // Perform subsequent operations.
142       //...
143   }
144   ```
145
1463. Use **put()** to add data to the KV store. <br>Example:
147
148   ```js
149   const KEY_TEST_STRING_ELEMENT = 'key_test_string';
150   const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
151   try {
152     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
153       if (err !== undefined) {
154         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
155         return;
156       }
157       console.info('Succeeded in putting data.');
158     });
159   } catch (e) {
160     let error = e as BusinessError;
161     console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
162   }
163   ```
164
165   > **NOTE**
166   >
167   > The **put()** method adds a KV pair if the specified key does not exists and changes the value if the the specified key already exists.
168
1694. Use **get()** to obtain the value of a key. <br>Example:
170
171   ```js
172   try {
173     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
174       if (err !== undefined) {
175         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
176         return;
177       }
178       console.info('Succeeded in putting data.');
179       kvStore = kvStore as distributedKVStore.SingleKVStore;
180       kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => {
181         if (err != undefined) {
182           console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
183           return;
184         }
185         console.info(`Succeeded in getting data. Data:${data}`);
186       });
187     });
188   } catch (e) {
189     let error = e as BusinessError;
190     console.error(`Failed to get data. Code:${error.code},message:${error.message}`);
191   }
192   ```
193
1945. Use **delete()** to delete the data of the specified key. <br>Example:
195
196   ```js
197   try {
198     kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
199       if (err !== undefined) {
200         console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
201         return;
202       }
203       console.info('Succeeded in putting data.');
204       kvStore = kvStore as distributedKVStore.SingleKVStore;
205       kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => {
206         if (err !== undefined) {
207           console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
208           return;
209         }
210         console.info('Succeeded in deleting data.');
211       });
212     });
213   } catch (e) {
214     let error = e as BusinessError;
215     console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
216   }
217   ```
218
2196. Close the distributed KV store of the given **storeId**. <br>Example:
220
221    ```js
222    try {
223      kvStore = undefined;
224      kvManager.closeKVStore('appId', 'storeId', (err: BusinessError)=> {
225        if (err) {
226          console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
227          return;
228        }
229        console.info('Succeeded in closing KVStore');
230      });
231    } catch (e) {
232      let error = e as BusinessError;
233      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
234    }
235    ```
236
2377. Delete the distributed KV store of the given **storeId**. <br>Example:
238
239    ```js
240    try {
241      kvStore = undefined;
242      kvManager.deleteKVStore('appId', 'storeId', (err: BusinessError)=> {
243        if (err) {
244          console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
245          return;
246        }
247        console.info('Succeeded in closing KVStore');
248      });
249    } catch (e) {
250      let error = e as BusinessError;
251      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
252    }
253    ```
254