1# Data Ability Development 2 3## When to Use 4 5A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices. 6 7Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs. 8 9## Available APIs 10 11**Table 1** Data ability lifecycle APIs 12|API|Description| 13|:------|:------| 14|onInitialized(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).| 15|update(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Updates data in the database.| 16|query(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>): void|Queries data in the database.| 17|delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Deletes one or more data records from the database.| 18|normalizeUri(uri: string, callback: AsyncCallback\<string>): void|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.| 19|batchInsert(uri: string, valueBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void|Inserts multiple data records into the database.| 20|denormalizeUri(uri: string, callback: AsyncCallback\<string>): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| 21|insert(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|Inserts a data record into the database.| 22|openFile(uri: string, mode: string, callback: AsyncCallback\<number>): void|Opens a file.| 23|getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\<string>>): void|Obtains the MIME type of a file.| 24|getType(uri: string, callback: AsyncCallback\<string>): void|Obtains the MIME type matching the data specified by the URI.| 25|executeBatch(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|Operates data in the database in batches.| 26|call(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.| 27 28 29## How to Develop 30### Creating a Data Ability 31 321. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class. The **BatchInsert** and **ExecuteBatch** APIs have already implemented the traversal logic, but not batch data processing. 33 34 The following code snippet shows how to create a Data ability: 35 36 ```javascript 37 import featureAbility from '@ohos.ability.featureAbility' 38 import dataAbility from '@ohos.data.dataAbility' 39 import dataRdb from '@ohos.data.rdb' 40 41 const TABLE_NAME = 'book' 42 const STORE_CONFIG = { name: 'book.db' } 43 const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)' 44 let rdbStore: dataRdb.RdbStore = undefined 45 46 export default { 47 onInitialized(abilityInfo) { 48 console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) 49 let context = featureAbility.getContext() 50 dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => { 51 console.info('DataAbility getRdbStore callback') 52 store.executeSql(SQL_CREATE_TABLE, []) 53 rdbStore = store 54 }); 55 }, 56 insert(uri, valueBucket, callback) { 57 console.info('DataAbility insert start') 58 rdbStore.insert(TABLE_NAME, valueBucket, callback) 59 }, 60 batchInsert(uri, valueBuckets, callback) { 61 console.info('DataAbility batch insert start') 62 for (let i = 0;i < valueBuckets.length; i++) { 63 console.info('DataAbility batch insert i=' + i) 64 if (i < valueBuckets.length - 1) { 65 rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => { 66 console.info('DataAbility batch insert ret=' + num) 67 }) 68 } else { 69 rdbStore.insert(TABLE_NAME, valueBuckets[i], callback) 70 } 71 } 72 }, 73 query(uri, columns, predicates, callback) { 74 console.info('DataAbility query start') 75 let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) 76 rdbStore.query(rdbPredicates, columns, callback) 77 }, 78 update(uri, valueBucket, predicates, callback) { 79 console.info('DataAbilityupdate start') 80 let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) 81 rdbStore.update(valueBucket, rdbPredicates, callback) 82 }, 83 delete(uri, predicates, callback) { 84 console.info('DataAbilitydelete start') 85 let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) 86 rdbStore.delete(rdbPredicates, callback) 87 } 88 }; 89 ``` 90 912. Configure the submodule. 92 93 | JSON Field| Description | 94 | ------------ | ------------------------------------------------------------ | 95 | "name" | Ability name, corresponding to the **Data** class name derived from **Ability**. | 96 | "type" | Ability type, which is **Data** for a Data ability. | 97 | "uri" | URI used for communication. | 98 | "visible" | Whether the Data ability is visible to other applications. When this parameter is set to **true**, the Data ability can communicate with other applications.| 99 100 **config.json configuration example** 101 102 ```json 103 "abilities":[{ 104 "srcPath": "DataAbility", 105 "name": ".DataAbility", 106 "icon": "$media:icon", 107 "srcLanguage": "ets", 108 "description": "$string:description_dataability", 109 "type": "data", 110 "visible": true, 111 "uri": "dataability://ohos.samples.etsdataability.DataAbility" 112 }] 113 ``` 114 115### Accessing a Data ability 116#### Development Preparations 117 118Import the basic dependency packages and obtain the URI string for communicating with the Data submodule. 119 120The basic dependency packages include: 121- @ohos.ability.featureAbility 122- @ohos.data.dataAbility 123- @ohos.data.rdb 124 125#### Data Ability API Development 126 127 1281. Create a Data ability helper. 129 130 For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md). 131 ```js 132 // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). 133 import featureAbility from '@ohos.ability.featureAbility' 134 import ohos_data_ability from '@ohos.data.dataAbility' 135 import ohos_data_rdb from '@ohos.data.rdb' 136 137 var urivar = "dataability:///com.ix.DataAbility" 138 var DAHelper = featureAbility.acquireDataAbilityHelper( 139 urivar 140 ); 141 ``` 1422. Construct RDB data. 143 ```js 144 var valuesBucket = {"name": "gaolu"} 145 var da = new ohos_data_ability.DataAbilityPredicates() 146 var valArray =new Array("value1"); 147 var cars = new Array({"batchInsert1" : "value1",}); 148 ``` 1493. Use **insert** to insert data to the Data submodule. 150 ```js 151 // Callback mode: 152 DAHelper.insert( 153 urivar, 154 valuesBucket, 155 (error, data) => { 156 console.log("DAHelper insert result: " + data) 157 } 158 ); 159 ``` 160 161 ```js 162 // Promise mode: 163 var datainsert = await DAHelper.insert( 164 urivar, 165 valuesBucket 166 ); 167 ``` 1684. Use **delete** to delete data from the Data submodule. 169 ```js 170 // Callback mode: 171 DAHelper.delete( 172 urivar, 173 da, 174 (error, data) => { 175 console.log("DAHelper delete result: " + data) 176 } 177 ); 178 ``` 179 180 ```js 181 // Promise mode: 182 var datadelete = await DAHelper.delete( 183 urivar, 184 da, 185 ); 186 ``` 1875. Use **update** to update data in the Data submodule. 188 ```js 189 // Callback mode: 190 DAHelper.update( 191 urivar 192 valuesBucket, 193 da, 194 (error, data) => { 195 console.log("DAHelper update result: " + data) 196 } 197 ); 198 ``` 199 200 ```js 201 // Promise mode: 202 var dataupdate = await DAHelper.update( 203 urivar, 204 valuesBucket, 205 da, 206 ); 207 ``` 2086. Use **query** to query data in the Data submodule. 209 ```js 210 // Callback mode: 211 DAHelper.query( 212 urivar, 213 valArray, 214 da, 215 (error, data) => { 216 console.log("DAHelper query result: " + data) 217 } 218 ); 219 ``` 220 221 ```js 222 // Promise mode: 223 var dataquery = await DAHelper.query( 224 urivar, 225 valArray, 226 da 227 ); 228 ``` 2297. Use **batchInsert** to insert data in batches to the Data submodule. 230 ```js 231 // Callback mode: 232 DAHelper.batchInsert( 233 urivar, 234 cars, 235 (error, data) => { 236 console.log("DAHelper batchInsert result: " + data) 237 } 238 ); 239 ``` 240 241 ```js 242 // Promise mode: 243 var databatchInsert = await DAHelper.batchInsert( 244 urivar, 245 cars 246 ); 247 ``` 2488. Use **executeBatch** to process data in batches in the Data submodule. 249 ```js 250 // Callback mode: 251 DAHelper.executeBatch( 252 urivar, 253 [ 254 { 255 uri: urivar, 256 type: featureAbility.DataAbilityOperationType.TYPE_INSERT, 257 valuesBucket: {"executeBatch" : "value1",}, 258 predicates: da, 259 expectedCount:0, 260 predicatesBackReferences: null, 261 interrupted:true, 262 } 263 ], 264 (error, data) => { 265 console.log("DAHelper executeBatch result: " + data) 266 } 267 ); 268 ``` 269 270 ```js 271 // Promise mode: 272 var dataexecuteBatch = await DAHelper.executeBatch( 273 urivar, 274 [ 275 { 276 uri: urivar, 277 type: featureAbility.DataAbilityOperationType.TYPE_INSERT, 278 valuesBucket: 279 { 280 "executeBatch" : "value1", 281 }, 282 predicates: da, 283 expectedCount:0, 284 predicatesBackReferences: null, 285 interrupted:true, 286 } 287 ] 288 ); 289 ``` 290