1# Persisting KV Store Data (ArkTS) 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<void>): void | Deletes a KV pair based on the specified key.| 31| closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void | Closes the distributed KV store of the given **storeId**.| 32| deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): 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 if (kvManager !== undefined) { 66 kvManager = kvManager as distributedKVStore.KVManager; 67 // Perform subsequent operations. 68 //... 69 } 70 } catch (e) { 71 let error = e as BusinessError; 72 console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`); 73 } 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 if (kvStore !== undefined) { 135 kvStore = kvStore as distributedKVStore.SingleKVStore; 136 // Perform subsequent operations. 137 //... 138 } 139 }); 140 } catch (e) { 141 let error = e as BusinessError; 142 console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); 143 } 144 ``` 145 1463. Call **put()** to add data to the KV store. <br>Example: 147 148 ```js 149 kvStore = kvStore as distributedKVStore.SingleKVStore; 150 const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 151 const VALUE_TEST_STRING_ELEMENT = 'value_test_string'; 152 try { 153 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { 154 if (err !== undefined) { 155 console.error(`Failed to put data. Code:${err.code},message:${err.message}`); 156 return; 157 } 158 console.info('Succeeded in putting data.'); 159 }); 160 } catch (e) { 161 let error = e as BusinessError; 162 console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); 163 } 164 ``` 165 166 > **NOTE** 167 > 168 > The **put()** method adds a KV pair if the specified key does not exists and changes the value if the specified key already exists. 169 1704. Call **get()** to obtain the value of a key. <br>Example: 171 172 ```js 173 try { 174 kvStore = kvStore as distributedKVStore.SingleKVStore; 175 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { 176 if (err !== undefined) { 177 console.error(`Failed to put data. Code:${err.code},message:${err.message}`); 178 return; 179 } 180 console.info('Succeeded in putting data.'); 181 kvStore = kvStore as distributedKVStore.SingleKVStore; 182 kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => { 183 if (err != undefined) { 184 console.error(`Failed to get data. Code:${err.code},message:${err.message}`); 185 return; 186 } 187 console.info(`Succeeded in getting data. Data:${data}`); 188 }); 189 }); 190 } catch (e) { 191 let error = e as BusinessError; 192 console.error(`Failed to get data. Code:${error.code},message:${error.message}`); 193 } 194 ``` 195 1965. Call **delete()** to delete the data of the specified key. <br>Example: 197 198 ```js 199 try { 200 kvStore = kvStore as distributedKVStore.SingleKVStore; 201 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { 202 if (err !== undefined) { 203 console.error(`Failed to put data. Code:${err.code},message:${err.message}`); 204 return; 205 } 206 console.info('Succeeded in putting data.'); 207 kvStore = kvStore as distributedKVStore.SingleKVStore; 208 kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => { 209 if (err !== undefined) { 210 console.error(`Failed to delete data. Code:${err.code},message:${err.message}`); 211 return; 212 } 213 console.info('Succeeded in deleting data.'); 214 }); 215 }); 216 } catch (e) { 217 let error = e as BusinessError; 218 console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); 219 } 220 ``` 221 2226. Close the distributed KV store of the given **storeId**. <br>Example: 223 224 ```js 225 try { 226 // appId is the bundle name of the application. 227 kvManager = kvManager as distributedKVStore.KVManager; 228 kvStore = undefined; 229 kvManager.closeKVStore('appId', 'storeId', (err: BusinessError)=> { 230 if (err) { 231 console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); 232 return; 233 } 234 console.info('Succeeded in closing KVStore'); 235 }); 236 } catch (e) { 237 let error = e as BusinessError; 238 console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); 239 } 240 ``` 241 2427. Delete the distributed KV store of the given **storeId**. <br>Example: 243 244 ```js 245 try { 246 // appId is the bundle name of the application. 247 kvManager = kvManager as distributedKVStore.KVManager; 248 kvStore = undefined; 249 kvManager.deleteKVStore('appId', 'storeId', (err: BusinessError)=> { 250 if (err) { 251 console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); 252 return; 253 } 254 console.info('Succeeded in deleting KVStore'); 255 }); 256 } catch (e) { 257 let error = e as BusinessError; 258 console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); 259 } 260 ``` 261